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

1.210   ! brouard     1: /* $Id: imach.c,v 1.209 2015/11/17 22:12:03 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.210   ! brouard     4:   Revision 1.209  2015/11/17 22:12:03  brouard
        !             5:   Summary: Adding ftolpl parameter
        !             6:   Author: N Brouard
        !             7: 
        !             8:   We had difficulties to get smoothed confidence intervals. It was due
        !             9:   to the period prevalence which wasn't computed accurately. The inner
        !            10:   parameter ftolpl is now an outer parameter of the .imach parameter
        !            11:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
        !            12:   computation are long.
        !            13: 
1.209     brouard    14:   Revision 1.208  2015/11/17 14:31:57  brouard
                     15:   Summary: temporary
                     16: 
1.208     brouard    17:   Revision 1.207  2015/10/27 17:36:57  brouard
                     18:   *** empty log message ***
                     19: 
1.207     brouard    20:   Revision 1.206  2015/10/24 07:14:11  brouard
                     21:   *** empty log message ***
                     22: 
1.206     brouard    23:   Revision 1.205  2015/10/23 15:50:53  brouard
                     24:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     25: 
1.205     brouard    26:   Revision 1.204  2015/10/01 16:20:26  brouard
                     27:   Summary: Some new graphs of contribution to likelihood
                     28: 
1.204     brouard    29:   Revision 1.203  2015/09/30 17:45:14  brouard
                     30:   Summary: looking at better estimation of the hessian
                     31: 
                     32:   Also a better criteria for convergence to the period prevalence And
                     33:   therefore adding the number of years needed to converge. (The
                     34:   prevalence in any alive state shold sum to one
                     35: 
1.203     brouard    36:   Revision 1.202  2015/09/22 19:45:16  brouard
                     37:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     38: 
1.202     brouard    39:   Revision 1.201  2015/09/15 17:34:58  brouard
                     40:   Summary: 0.98r0
                     41: 
                     42:   - Some new graphs like suvival functions
                     43:   - Some bugs fixed like model=1+age+V2.
                     44: 
1.201     brouard    45:   Revision 1.200  2015/09/09 16:53:55  brouard
                     46:   Summary: Big bug thanks to Flavia
                     47: 
                     48:   Even model=1+age+V2. did not work anymore
                     49: 
1.200     brouard    50:   Revision 1.199  2015/09/07 14:09:23  brouard
                     51:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     52: 
1.199     brouard    53:   Revision 1.198  2015/09/03 07:14:39  brouard
                     54:   Summary: 0.98q5 Flavia
                     55: 
1.198     brouard    56:   Revision 1.197  2015/09/01 18:24:39  brouard
                     57:   *** empty log message ***
                     58: 
1.197     brouard    59:   Revision 1.196  2015/08/18 23:17:52  brouard
                     60:   Summary: 0.98q5
                     61: 
1.196     brouard    62:   Revision 1.195  2015/08/18 16:28:39  brouard
                     63:   Summary: Adding a hack for testing purpose
                     64: 
                     65:   After reading the title, ftol and model lines, if the comment line has
                     66:   a q, starting with #q, the answer at the end of the run is quit. It
                     67:   permits to run test files in batch with ctest. The former workaround was
                     68:   $ echo q | imach foo.imach
                     69: 
1.195     brouard    70:   Revision 1.194  2015/08/18 13:32:00  brouard
                     71:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     72: 
1.194     brouard    73:   Revision 1.193  2015/08/04 07:17:42  brouard
                     74:   Summary: 0.98q4
                     75: 
1.193     brouard    76:   Revision 1.192  2015/07/16 16:49:02  brouard
                     77:   Summary: Fixing some outputs
                     78: 
1.192     brouard    79:   Revision 1.191  2015/07/14 10:00:33  brouard
                     80:   Summary: Some fixes
                     81: 
1.191     brouard    82:   Revision 1.190  2015/05/05 08:51:13  brouard
                     83:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     84: 
                     85:   Fix 1+age+.
                     86: 
1.190     brouard    87:   Revision 1.189  2015/04/30 14:45:16  brouard
                     88:   Summary: 0.98q2
                     89: 
1.189     brouard    90:   Revision 1.188  2015/04/30 08:27:53  brouard
                     91:   *** empty log message ***
                     92: 
1.188     brouard    93:   Revision 1.187  2015/04/29 09:11:15  brouard
                     94:   *** empty log message ***
                     95: 
1.187     brouard    96:   Revision 1.186  2015/04/23 12:01:52  brouard
                     97:   Summary: V1*age is working now, version 0.98q1
                     98: 
                     99:   Some codes had been disabled in order to simplify and Vn*age was
                    100:   working in the optimization phase, ie, giving correct MLE parameters,
                    101:   but, as usual, outputs were not correct and program core dumped.
                    102: 
1.186     brouard   103:   Revision 1.185  2015/03/11 13:26:42  brouard
                    104:   Summary: Inclusion of compile and links command line for Intel Compiler
                    105: 
1.185     brouard   106:   Revision 1.184  2015/03/11 11:52:39  brouard
                    107:   Summary: Back from Windows 8. Intel Compiler
                    108: 
1.184     brouard   109:   Revision 1.183  2015/03/10 20:34:32  brouard
                    110:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    111: 
                    112:   We use directest instead of original Powell test; probably no
                    113:   incidence on the results, but better justifications;
                    114:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    115:   wrong results.
                    116: 
1.183     brouard   117:   Revision 1.182  2015/02/12 08:19:57  brouard
                    118:   Summary: Trying to keep directest which seems simpler and more general
                    119:   Author: Nicolas Brouard
                    120: 
1.182     brouard   121:   Revision 1.181  2015/02/11 23:22:24  brouard
                    122:   Summary: Comments on Powell added
                    123: 
                    124:   Author:
                    125: 
1.181     brouard   126:   Revision 1.180  2015/02/11 17:33:45  brouard
                    127:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    128: 
1.180     brouard   129:   Revision 1.179  2015/01/04 09:57:06  brouard
                    130:   Summary: back to OS/X
                    131: 
1.179     brouard   132:   Revision 1.178  2015/01/04 09:35:48  brouard
                    133:   *** empty log message ***
                    134: 
1.178     brouard   135:   Revision 1.177  2015/01/03 18:40:56  brouard
                    136:   Summary: Still testing ilc32 on OSX
                    137: 
1.177     brouard   138:   Revision 1.176  2015/01/03 16:45:04  brouard
                    139:   *** empty log message ***
                    140: 
1.176     brouard   141:   Revision 1.175  2015/01/03 16:33:42  brouard
                    142:   *** empty log message ***
                    143: 
1.175     brouard   144:   Revision 1.174  2015/01/03 16:15:49  brouard
                    145:   Summary: Still in cross-compilation
                    146: 
1.174     brouard   147:   Revision 1.173  2015/01/03 12:06:26  brouard
                    148:   Summary: trying to detect cross-compilation
                    149: 
1.173     brouard   150:   Revision 1.172  2014/12/27 12:07:47  brouard
                    151:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    152: 
1.172     brouard   153:   Revision 1.171  2014/12/23 13:26:59  brouard
                    154:   Summary: Back from Visual C
                    155: 
                    156:   Still problem with utsname.h on Windows
                    157: 
1.171     brouard   158:   Revision 1.170  2014/12/23 11:17:12  brouard
                    159:   Summary: Cleaning some \%% back to %%
                    160: 
                    161:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    162: 
1.170     brouard   163:   Revision 1.169  2014/12/22 23:08:31  brouard
                    164:   Summary: 0.98p
                    165: 
                    166:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    167: 
1.169     brouard   168:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   169:   Summary: update
1.169     brouard   170: 
1.168     brouard   171:   Revision 1.167  2014/12/22 13:50:56  brouard
                    172:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    173: 
                    174:   Testing on Linux 64
                    175: 
1.167     brouard   176:   Revision 1.166  2014/12/22 11:40:47  brouard
                    177:   *** empty log message ***
                    178: 
1.166     brouard   179:   Revision 1.165  2014/12/16 11:20:36  brouard
                    180:   Summary: After compiling on Visual C
                    181: 
                    182:   * imach.c (Module): Merging 1.61 to 1.162
                    183: 
1.165     brouard   184:   Revision 1.164  2014/12/16 10:52:11  brouard
                    185:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    186: 
                    187:   * imach.c (Module): Merging 1.61 to 1.162
                    188: 
1.164     brouard   189:   Revision 1.163  2014/12/16 10:30:11  brouard
                    190:   * imach.c (Module): Merging 1.61 to 1.162
                    191: 
1.163     brouard   192:   Revision 1.162  2014/09/25 11:43:39  brouard
                    193:   Summary: temporary backup 0.99!
                    194: 
1.162     brouard   195:   Revision 1.1  2014/09/16 11:06:58  brouard
                    196:   Summary: With some code (wrong) for nlopt
                    197: 
                    198:   Author:
                    199: 
                    200:   Revision 1.161  2014/09/15 20:41:41  brouard
                    201:   Summary: Problem with macro SQR on Intel compiler
                    202: 
1.161     brouard   203:   Revision 1.160  2014/09/02 09:24:05  brouard
                    204:   *** empty log message ***
                    205: 
1.160     brouard   206:   Revision 1.159  2014/09/01 10:34:10  brouard
                    207:   Summary: WIN32
                    208:   Author: Brouard
                    209: 
1.159     brouard   210:   Revision 1.158  2014/08/27 17:11:51  brouard
                    211:   *** empty log message ***
                    212: 
1.158     brouard   213:   Revision 1.157  2014/08/27 16:26:55  brouard
                    214:   Summary: Preparing windows Visual studio version
                    215:   Author: Brouard
                    216: 
                    217:   In order to compile on Visual studio, time.h is now correct and time_t
                    218:   and tm struct should be used. difftime should be used but sometimes I
                    219:   just make the differences in raw time format (time(&now).
                    220:   Trying to suppress #ifdef LINUX
                    221:   Add xdg-open for __linux in order to open default browser.
                    222: 
1.157     brouard   223:   Revision 1.156  2014/08/25 20:10:10  brouard
                    224:   *** empty log message ***
                    225: 
1.156     brouard   226:   Revision 1.155  2014/08/25 18:32:34  brouard
                    227:   Summary: New compile, minor changes
                    228:   Author: Brouard
                    229: 
1.155     brouard   230:   Revision 1.154  2014/06/20 17:32:08  brouard
                    231:   Summary: Outputs now all graphs of convergence to period prevalence
                    232: 
1.154     brouard   233:   Revision 1.153  2014/06/20 16:45:46  brouard
                    234:   Summary: If 3 live state, convergence to period prevalence on same graph
                    235:   Author: Brouard
                    236: 
1.153     brouard   237:   Revision 1.152  2014/06/18 17:54:09  brouard
                    238:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    239: 
1.152     brouard   240:   Revision 1.151  2014/06/18 16:43:30  brouard
                    241:   *** empty log message ***
                    242: 
1.151     brouard   243:   Revision 1.150  2014/06/18 16:42:35  brouard
                    244:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    245:   Author: brouard
                    246: 
1.150     brouard   247:   Revision 1.149  2014/06/18 15:51:14  brouard
                    248:   Summary: Some fixes in parameter files errors
                    249:   Author: Nicolas Brouard
                    250: 
1.149     brouard   251:   Revision 1.148  2014/06/17 17:38:48  brouard
                    252:   Summary: Nothing new
                    253:   Author: Brouard
                    254: 
                    255:   Just a new packaging for OS/X version 0.98nS
                    256: 
1.148     brouard   257:   Revision 1.147  2014/06/16 10:33:11  brouard
                    258:   *** empty log message ***
                    259: 
1.147     brouard   260:   Revision 1.146  2014/06/16 10:20:28  brouard
                    261:   Summary: Merge
                    262:   Author: Brouard
                    263: 
                    264:   Merge, before building revised version.
                    265: 
1.146     brouard   266:   Revision 1.145  2014/06/10 21:23:15  brouard
                    267:   Summary: Debugging with valgrind
                    268:   Author: Nicolas Brouard
                    269: 
                    270:   Lot of changes in order to output the results with some covariates
                    271:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    272:   improve the code.
                    273:   No more memory valgrind error but a lot has to be done in order to
                    274:   continue the work of splitting the code into subroutines.
                    275:   Also, decodemodel has been improved. Tricode is still not
                    276:   optimal. nbcode should be improved. Documentation has been added in
                    277:   the source code.
                    278: 
1.144     brouard   279:   Revision 1.143  2014/01/26 09:45:38  brouard
                    280:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    281: 
                    282:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    283:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    284: 
1.143     brouard   285:   Revision 1.142  2014/01/26 03:57:36  brouard
                    286:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    287: 
                    288:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    289: 
1.142     brouard   290:   Revision 1.141  2014/01/26 02:42:01  brouard
                    291:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    292: 
1.141     brouard   293:   Revision 1.140  2011/09/02 10:37:54  brouard
                    294:   Summary: times.h is ok with mingw32 now.
                    295: 
1.140     brouard   296:   Revision 1.139  2010/06/14 07:50:17  brouard
                    297:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    298:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    299: 
1.139     brouard   300:   Revision 1.138  2010/04/30 18:19:40  brouard
                    301:   *** empty log message ***
                    302: 
1.138     brouard   303:   Revision 1.137  2010/04/29 18:11:38  brouard
                    304:   (Module): Checking covariates for more complex models
                    305:   than V1+V2. A lot of change to be done. Unstable.
                    306: 
1.137     brouard   307:   Revision 1.136  2010/04/26 20:30:53  brouard
                    308:   (Module): merging some libgsl code. Fixing computation
                    309:   of likelione (using inter/intrapolation if mle = 0) in order to
                    310:   get same likelihood as if mle=1.
                    311:   Some cleaning of code and comments added.
                    312: 
1.136     brouard   313:   Revision 1.135  2009/10/29 15:33:14  brouard
                    314:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    315: 
1.135     brouard   316:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   319:   Revision 1.133  2009/07/06 10:21:25  brouard
                    320:   just nforces
                    321: 
1.133     brouard   322:   Revision 1.132  2009/07/06 08:22:05  brouard
                    323:   Many tings
                    324: 
1.132     brouard   325:   Revision 1.131  2009/06/20 16:22:47  brouard
                    326:   Some dimensions resccaled
                    327: 
1.131     brouard   328:   Revision 1.130  2009/05/26 06:44:34  brouard
                    329:   (Module): Max Covariate is now set to 20 instead of 8. A
                    330:   lot of cleaning with variables initialized to 0. Trying to make
                    331:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    332: 
1.130     brouard   333:   Revision 1.129  2007/08/31 13:49:27  lievre
                    334:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    335: 
1.129     lievre    336:   Revision 1.128  2006/06/30 13:02:05  brouard
                    337:   (Module): Clarifications on computing e.j
                    338: 
1.128     brouard   339:   Revision 1.127  2006/04/28 18:11:50  brouard
                    340:   (Module): Yes the sum of survivors was wrong since
                    341:   imach-114 because nhstepm was no more computed in the age
                    342:   loop. Now we define nhstepma in the age loop.
                    343:   (Module): In order to speed up (in case of numerous covariates) we
                    344:   compute health expectancies (without variances) in a first step
                    345:   and then all the health expectancies with variances or standard
                    346:   deviation (needs data from the Hessian matrices) which slows the
                    347:   computation.
                    348:   In the future we should be able to stop the program is only health
                    349:   expectancies and graph are needed without standard deviations.
                    350: 
1.127     brouard   351:   Revision 1.126  2006/04/28 17:23:28  brouard
                    352:   (Module): Yes the sum of survivors was wrong since
                    353:   imach-114 because nhstepm was no more computed in the age
                    354:   loop. Now we define nhstepma in the age loop.
                    355:   Version 0.98h
                    356: 
1.126     brouard   357:   Revision 1.125  2006/04/04 15:20:31  lievre
                    358:   Errors in calculation of health expectancies. Age was not initialized.
                    359:   Forecasting file added.
                    360: 
                    361:   Revision 1.124  2006/03/22 17:13:53  lievre
                    362:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    363:   The log-likelihood is printed in the log file
                    364: 
                    365:   Revision 1.123  2006/03/20 10:52:43  brouard
                    366:   * imach.c (Module): <title> changed, corresponds to .htm file
                    367:   name. <head> headers where missing.
                    368: 
                    369:   * imach.c (Module): Weights can have a decimal point as for
                    370:   English (a comma might work with a correct LC_NUMERIC environment,
                    371:   otherwise the weight is truncated).
                    372:   Modification of warning when the covariates values are not 0 or
                    373:   1.
                    374:   Version 0.98g
                    375: 
                    376:   Revision 1.122  2006/03/20 09:45:41  brouard
                    377:   (Module): Weights can have a decimal point as for
                    378:   English (a comma might work with a correct LC_NUMERIC environment,
                    379:   otherwise the weight is truncated).
                    380:   Modification of warning when the covariates values are not 0 or
                    381:   1.
                    382:   Version 0.98g
                    383: 
                    384:   Revision 1.121  2006/03/16 17:45:01  lievre
                    385:   * imach.c (Module): Comments concerning covariates added
                    386: 
                    387:   * imach.c (Module): refinements in the computation of lli if
                    388:   status=-2 in order to have more reliable computation if stepm is
                    389:   not 1 month. Version 0.98f
                    390: 
                    391:   Revision 1.120  2006/03/16 15:10:38  lievre
                    392:   (Module): refinements in the computation of lli if
                    393:   status=-2 in order to have more reliable computation if stepm is
                    394:   not 1 month. Version 0.98f
                    395: 
                    396:   Revision 1.119  2006/03/15 17:42:26  brouard
                    397:   (Module): Bug if status = -2, the loglikelihood was
                    398:   computed as likelihood omitting the logarithm. Version O.98e
                    399: 
                    400:   Revision 1.118  2006/03/14 18:20:07  brouard
                    401:   (Module): varevsij Comments added explaining the second
                    402:   table of variances if popbased=1 .
                    403:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    404:   (Module): Function pstamp added
                    405:   (Module): Version 0.98d
                    406: 
                    407:   Revision 1.117  2006/03/14 17:16:22  brouard
                    408:   (Module): varevsij Comments added explaining the second
                    409:   table of variances if popbased=1 .
                    410:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    411:   (Module): Function pstamp added
                    412:   (Module): Version 0.98d
                    413: 
                    414:   Revision 1.116  2006/03/06 10:29:27  brouard
                    415:   (Module): Variance-covariance wrong links and
                    416:   varian-covariance of ej. is needed (Saito).
                    417: 
                    418:   Revision 1.115  2006/02/27 12:17:45  brouard
                    419:   (Module): One freematrix added in mlikeli! 0.98c
                    420: 
                    421:   Revision 1.114  2006/02/26 12:57:58  brouard
                    422:   (Module): Some improvements in processing parameter
                    423:   filename with strsep.
                    424: 
                    425:   Revision 1.113  2006/02/24 14:20:24  brouard
                    426:   (Module): Memory leaks checks with valgrind and:
                    427:   datafile was not closed, some imatrix were not freed and on matrix
                    428:   allocation too.
                    429: 
                    430:   Revision 1.112  2006/01/30 09:55:26  brouard
                    431:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    432: 
                    433:   Revision 1.111  2006/01/25 20:38:18  brouard
                    434:   (Module): Lots of cleaning and bugs added (Gompertz)
                    435:   (Module): Comments can be added in data file. Missing date values
                    436:   can be a simple dot '.'.
                    437: 
                    438:   Revision 1.110  2006/01/25 00:51:50  brouard
                    439:   (Module): Lots of cleaning and bugs added (Gompertz)
                    440: 
                    441:   Revision 1.109  2006/01/24 19:37:15  brouard
                    442:   (Module): Comments (lines starting with a #) are allowed in data.
                    443: 
                    444:   Revision 1.108  2006/01/19 18:05:42  lievre
                    445:   Gnuplot problem appeared...
                    446:   To be fixed
                    447: 
                    448:   Revision 1.107  2006/01/19 16:20:37  brouard
                    449:   Test existence of gnuplot in imach path
                    450: 
                    451:   Revision 1.106  2006/01/19 13:24:36  brouard
                    452:   Some cleaning and links added in html output
                    453: 
                    454:   Revision 1.105  2006/01/05 20:23:19  lievre
                    455:   *** empty log message ***
                    456: 
                    457:   Revision 1.104  2005/09/30 16:11:43  lievre
                    458:   (Module): sump fixed, loop imx fixed, and simplifications.
                    459:   (Module): If the status is missing at the last wave but we know
                    460:   that the person is alive, then we can code his/her status as -2
                    461:   (instead of missing=-1 in earlier versions) and his/her
                    462:   contributions to the likelihood is 1 - Prob of dying from last
                    463:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    464:   the healthy state at last known wave). Version is 0.98
                    465: 
                    466:   Revision 1.103  2005/09/30 15:54:49  lievre
                    467:   (Module): sump fixed, loop imx fixed, and simplifications.
                    468: 
                    469:   Revision 1.102  2004/09/15 17:31:30  brouard
                    470:   Add the possibility to read data file including tab characters.
                    471: 
                    472:   Revision 1.101  2004/09/15 10:38:38  brouard
                    473:   Fix on curr_time
                    474: 
                    475:   Revision 1.100  2004/07/12 18:29:06  brouard
                    476:   Add version for Mac OS X. Just define UNIX in Makefile
                    477: 
                    478:   Revision 1.99  2004/06/05 08:57:40  brouard
                    479:   *** empty log message ***
                    480: 
                    481:   Revision 1.98  2004/05/16 15:05:56  brouard
                    482:   New version 0.97 . First attempt to estimate force of mortality
                    483:   directly from the data i.e. without the need of knowing the health
                    484:   state at each age, but using a Gompertz model: log u =a + b*age .
                    485:   This is the basic analysis of mortality and should be done before any
                    486:   other analysis, in order to test if the mortality estimated from the
                    487:   cross-longitudinal survey is different from the mortality estimated
                    488:   from other sources like vital statistic data.
                    489: 
                    490:   The same imach parameter file can be used but the option for mle should be -3.
                    491: 
1.133     brouard   492:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   493:   former routines in order to include the new code within the former code.
                    494: 
                    495:   The output is very simple: only an estimate of the intercept and of
                    496:   the slope with 95% confident intervals.
                    497: 
                    498:   Current limitations:
                    499:   A) Even if you enter covariates, i.e. with the
                    500:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    501:   B) There is no computation of Life Expectancy nor Life Table.
                    502: 
                    503:   Revision 1.97  2004/02/20 13:25:42  lievre
                    504:   Version 0.96d. Population forecasting command line is (temporarily)
                    505:   suppressed.
                    506: 
                    507:   Revision 1.96  2003/07/15 15:38:55  brouard
                    508:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    509:   rewritten within the same printf. Workaround: many printfs.
                    510: 
                    511:   Revision 1.95  2003/07/08 07:54:34  brouard
                    512:   * imach.c (Repository):
                    513:   (Repository): Using imachwizard code to output a more meaningful covariance
                    514:   matrix (cov(a12,c31) instead of numbers.
                    515: 
                    516:   Revision 1.94  2003/06/27 13:00:02  brouard
                    517:   Just cleaning
                    518: 
                    519:   Revision 1.93  2003/06/25 16:33:55  brouard
                    520:   (Module): On windows (cygwin) function asctime_r doesn't
                    521:   exist so I changed back to asctime which exists.
                    522:   (Module): Version 0.96b
                    523: 
                    524:   Revision 1.92  2003/06/25 16:30:45  brouard
                    525:   (Module): On windows (cygwin) function asctime_r doesn't
                    526:   exist so I changed back to asctime which exists.
                    527: 
                    528:   Revision 1.91  2003/06/25 15:30:29  brouard
                    529:   * imach.c (Repository): Duplicated warning errors corrected.
                    530:   (Repository): Elapsed time after each iteration is now output. It
                    531:   helps to forecast when convergence will be reached. Elapsed time
                    532:   is stamped in powell.  We created a new html file for the graphs
                    533:   concerning matrix of covariance. It has extension -cov.htm.
                    534: 
                    535:   Revision 1.90  2003/06/24 12:34:15  brouard
                    536:   (Module): Some bugs corrected for windows. Also, when
                    537:   mle=-1 a template is output in file "or"mypar.txt with the design
                    538:   of the covariance matrix to be input.
                    539: 
                    540:   Revision 1.89  2003/06/24 12:30:52  brouard
                    541:   (Module): Some bugs corrected for windows. Also, when
                    542:   mle=-1 a template is output in file "or"mypar.txt with the design
                    543:   of the covariance matrix to be input.
                    544: 
                    545:   Revision 1.88  2003/06/23 17:54:56  brouard
                    546:   * 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.
                    547: 
                    548:   Revision 1.87  2003/06/18 12:26:01  brouard
                    549:   Version 0.96
                    550: 
                    551:   Revision 1.86  2003/06/17 20:04:08  brouard
                    552:   (Module): Change position of html and gnuplot routines and added
                    553:   routine fileappend.
                    554: 
                    555:   Revision 1.85  2003/06/17 13:12:43  brouard
                    556:   * imach.c (Repository): Check when date of death was earlier that
                    557:   current date of interview. It may happen when the death was just
                    558:   prior to the death. In this case, dh was negative and likelihood
                    559:   was wrong (infinity). We still send an "Error" but patch by
                    560:   assuming that the date of death was just one stepm after the
                    561:   interview.
                    562:   (Repository): Because some people have very long ID (first column)
                    563:   we changed int to long in num[] and we added a new lvector for
                    564:   memory allocation. But we also truncated to 8 characters (left
                    565:   truncation)
                    566:   (Repository): No more line truncation errors.
                    567: 
                    568:   Revision 1.84  2003/06/13 21:44:43  brouard
                    569:   * imach.c (Repository): Replace "freqsummary" at a correct
                    570:   place. It differs from routine "prevalence" which may be called
                    571:   many times. Probs is memory consuming and must be used with
                    572:   parcimony.
                    573:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    574: 
                    575:   Revision 1.83  2003/06/10 13:39:11  lievre
                    576:   *** empty log message ***
                    577: 
                    578:   Revision 1.82  2003/06/05 15:57:20  brouard
                    579:   Add log in  imach.c and  fullversion number is now printed.
                    580: 
                    581: */
                    582: /*
                    583:    Interpolated Markov Chain
                    584: 
                    585:   Short summary of the programme:
                    586:   
                    587:   This program computes Healthy Life Expectancies from
                    588:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    589:   first survey ("cross") where individuals from different ages are
                    590:   interviewed on their health status or degree of disability (in the
                    591:   case of a health survey which is our main interest) -2- at least a
                    592:   second wave of interviews ("longitudinal") which measure each change
                    593:   (if any) in individual health status.  Health expectancies are
                    594:   computed from the time spent in each health state according to a
                    595:   model. More health states you consider, more time is necessary to reach the
                    596:   Maximum Likelihood of the parameters involved in the model.  The
                    597:   simplest model is the multinomial logistic model where pij is the
                    598:   probability to be observed in state j at the second wave
                    599:   conditional to be observed in state i at the first wave. Therefore
                    600:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    601:   'age' is age and 'sex' is a covariate. If you want to have a more
                    602:   complex model than "constant and age", you should modify the program
                    603:   where the markup *Covariates have to be included here again* invites
                    604:   you to do it.  More covariates you add, slower the
                    605:   convergence.
                    606: 
                    607:   The advantage of this computer programme, compared to a simple
                    608:   multinomial logistic model, is clear when the delay between waves is not
                    609:   identical for each individual. Also, if a individual missed an
                    610:   intermediate interview, the information is lost, but taken into
                    611:   account using an interpolation or extrapolation.  
                    612: 
                    613:   hPijx is the probability to be observed in state i at age x+h
                    614:   conditional to the observed state i at age x. The delay 'h' can be
                    615:   split into an exact number (nh*stepm) of unobserved intermediate
                    616:   states. This elementary transition (by month, quarter,
                    617:   semester or year) is modelled as a multinomial logistic.  The hPx
                    618:   matrix is simply the matrix product of nh*stepm elementary matrices
                    619:   and the contribution of each individual to the likelihood is simply
                    620:   hPijx.
                    621: 
                    622:   Also this programme outputs the covariance matrix of the parameters but also
                    623:   of the life expectancies. It also computes the period (stable) prevalence. 
                    624:   
1.133     brouard   625:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    626:            Institut national d'études démographiques, Paris.
1.126     brouard   627:   This software have been partly granted by Euro-REVES, a concerted action
                    628:   from the European Union.
                    629:   It is copyrighted identically to a GNU software product, ie programme and
                    630:   software can be distributed freely for non commercial use. Latest version
                    631:   can be accessed at http://euroreves.ined.fr/imach .
                    632: 
                    633:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    634:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    635:   
                    636:   **********************************************************************/
                    637: /*
                    638:   main
                    639:   read parameterfile
                    640:   read datafile
                    641:   concatwav
                    642:   freqsummary
                    643:   if (mle >= 1)
                    644:     mlikeli
                    645:   print results files
                    646:   if mle==1 
                    647:      computes hessian
                    648:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    649:       begin-prev-date,...
                    650:   open gnuplot file
                    651:   open html file
1.145     brouard   652:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    653:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    654:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    655:     freexexit2 possible for memory heap.
                    656: 
                    657:   h Pij x                         | pij_nom  ficrestpij
                    658:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    659:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    660:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    661: 
                    662:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    663:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    664:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    665:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    666:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    667: 
1.126     brouard   668:   forecasting if prevfcast==1 prevforecast call prevalence()
                    669:   health expectancies
                    670:   Variance-covariance of DFLE
                    671:   prevalence()
                    672:    movingaverage()
                    673:   varevsij() 
                    674:   if popbased==1 varevsij(,popbased)
                    675:   total life expectancies
                    676:   Variance of period (stable) prevalence
                    677:  end
                    678: */
                    679: 
1.187     brouard   680: /* #define DEBUG */
                    681: /* #define DEBUGBRENT */
1.203     brouard   682: /* #define DEBUGLINMIN */
                    683: /* #define DEBUGHESS */
                    684: #define DEBUGHESSIJ
                    685: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   686: #define POWELL /* Instead of NLOPT */
1.192     brouard   687: #define POWELLF1F3 /* Skip test */
1.186     brouard   688: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    689: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   690: 
                    691: #include <math.h>
                    692: #include <stdio.h>
                    693: #include <stdlib.h>
                    694: #include <string.h>
1.159     brouard   695: 
                    696: #ifdef _WIN32
                    697: #include <io.h>
1.172     brouard   698: #include <windows.h>
                    699: #include <tchar.h>
1.159     brouard   700: #else
1.126     brouard   701: #include <unistd.h>
1.159     brouard   702: #endif
1.126     brouard   703: 
                    704: #include <limits.h>
                    705: #include <sys/types.h>
1.171     brouard   706: 
                    707: #if defined(__GNUC__)
                    708: #include <sys/utsname.h> /* Doesn't work on Windows */
                    709: #endif
                    710: 
1.126     brouard   711: #include <sys/stat.h>
                    712: #include <errno.h>
1.159     brouard   713: /* extern int errno; */
1.126     brouard   714: 
1.157     brouard   715: /* #ifdef LINUX */
                    716: /* #include <time.h> */
                    717: /* #include "timeval.h" */
                    718: /* #else */
                    719: /* #include <sys/time.h> */
                    720: /* #endif */
                    721: 
1.126     brouard   722: #include <time.h>
                    723: 
1.136     brouard   724: #ifdef GSL
                    725: #include <gsl/gsl_errno.h>
                    726: #include <gsl/gsl_multimin.h>
                    727: #endif
                    728: 
1.167     brouard   729: 
1.162     brouard   730: #ifdef NLOPT
                    731: #include <nlopt.h>
                    732: typedef struct {
                    733:   double (* function)(double [] );
                    734: } myfunc_data ;
                    735: #endif
                    736: 
1.126     brouard   737: /* #include <libintl.h> */
                    738: /* #define _(String) gettext (String) */
                    739: 
1.141     brouard   740: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   741: 
                    742: #define GNUPLOTPROGRAM "gnuplot"
                    743: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    744: #define FILENAMELENGTH 132
                    745: 
                    746: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    747: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    748: 
1.144     brouard   749: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    750: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   751: 
                    752: #define NINTERVMAX 8
1.144     brouard   753: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    754: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    755: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   756: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   757: #define MAXN 20000
1.144     brouard   758: #define YEARM 12. /**< Number of months per year */
1.126     brouard   759: #define AGESUP 130
                    760: #define AGEBASE 40
1.194     brouard   761: #define AGEOVERFLOW 1.e20
1.164     brouard   762: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   763: #ifdef _WIN32
                    764: #define DIRSEPARATOR '\\'
                    765: #define CHARSEPARATOR "\\"
                    766: #define ODIRSEPARATOR '/'
                    767: #else
1.126     brouard   768: #define DIRSEPARATOR '/'
                    769: #define CHARSEPARATOR "/"
                    770: #define ODIRSEPARATOR '\\'
                    771: #endif
                    772: 
1.210   ! brouard   773: /* $Id: imach.c,v 1.209 2015/11/17 22:12:03 brouard Exp $ */
1.126     brouard   774: /* $State: Exp $ */
1.196     brouard   775: #include "version.h"
                    776: char version[]=__IMACH_VERSION__;
1.204     brouard   777: 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.210   ! brouard   778: char fullversion[]="$Revision: 1.209 $ $Date: 2015/11/17 22:12:03 $"; 
1.126     brouard   779: char strstart[80];
                    780: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   781: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   782: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   783: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    784: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    785: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    786: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    787: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    788: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    789: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    790: int cptcov=0; /* Working variable */
1.126     brouard   791: int npar=NPARMAX;
                    792: int nlstate=2; /* Number of live states */
                    793: int ndeath=1; /* Number of dead states */
1.130     brouard   794: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   795: int popbased=0;
                    796: 
                    797: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   798: int maxwav=0; /* Maxim number of waves */
                    799: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    800: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    801: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   802:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   803: int mle=1, weightopt=0;
1.126     brouard   804: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    805: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    806: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    807:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   808: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   809: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   810: double **matprod2(); /* test */
1.126     brouard   811: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    812: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   813: /*FILE *fic ; */ /* Used in readdata only */
                    814: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   815: FILE *ficlog, *ficrespow;
1.130     brouard   816: int globpr=0; /* Global variable for printing or not */
1.126     brouard   817: double fretone; /* Only one call to likelihood */
1.130     brouard   818: long ipmx=0; /* Number of contributions */
1.126     brouard   819: double sw; /* Sum of weights */
                    820: char filerespow[FILENAMELENGTH];
                    821: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    822: FILE *ficresilk;
                    823: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    824: FILE *ficresprobmorprev;
                    825: FILE *fichtm, *fichtmcov; /* Html File */
                    826: FILE *ficreseij;
                    827: char filerese[FILENAMELENGTH];
                    828: FILE *ficresstdeij;
                    829: char fileresstde[FILENAMELENGTH];
                    830: FILE *ficrescveij;
                    831: char filerescve[FILENAMELENGTH];
                    832: FILE  *ficresvij;
                    833: char fileresv[FILENAMELENGTH];
                    834: FILE  *ficresvpl;
                    835: char fileresvpl[FILENAMELENGTH];
                    836: char title[MAXLINE];
                    837: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    838: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    839: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    840: char command[FILENAMELENGTH];
                    841: int  outcmd=0;
                    842: 
                    843: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   844: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   845: char filelog[FILENAMELENGTH]; /* Log file */
                    846: char filerest[FILENAMELENGTH];
                    847: char fileregp[FILENAMELENGTH];
                    848: char popfile[FILENAMELENGTH];
                    849: 
                    850: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    851: 
1.157     brouard   852: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    853: /* struct timezone tzp; */
                    854: /* extern int gettimeofday(); */
                    855: struct tm tml, *gmtime(), *localtime();
                    856: 
                    857: extern time_t time();
                    858: 
                    859: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    860: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    861: struct tm tm;
                    862: 
1.126     brouard   863: char strcurr[80], strfor[80];
                    864: 
                    865: char *endptr;
                    866: long lval;
                    867: double dval;
                    868: 
                    869: #define NR_END 1
                    870: #define FREE_ARG char*
                    871: #define FTOL 1.0e-10
                    872: 
                    873: #define NRANSI 
                    874: #define ITMAX 200 
                    875: 
                    876: #define TOL 2.0e-4 
                    877: 
                    878: #define CGOLD 0.3819660 
                    879: #define ZEPS 1.0e-10 
                    880: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    881: 
                    882: #define GOLD 1.618034 
                    883: #define GLIMIT 100.0 
                    884: #define TINY 1.0e-20 
                    885: 
                    886: static double maxarg1,maxarg2;
                    887: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    888: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    889:   
                    890: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    891: #define rint(a) floor(a+0.5)
1.166     brouard   892: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   893: #define mytinydouble 1.0e-16
1.166     brouard   894: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    895: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    896: /* static double dsqrarg; */
                    897: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   898: static double sqrarg;
                    899: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    900: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    901: int agegomp= AGEGOMP;
                    902: 
                    903: int imx; 
                    904: int stepm=1;
                    905: /* Stepm, step in month: minimum step interpolation*/
                    906: 
                    907: int estepm;
                    908: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    909: 
                    910: int m,nb;
                    911: long *num;
1.197     brouard   912: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   913: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    914:                   covariate for which somebody answered excluding 
                    915:                   undefined. Usually 2: 0 and 1. */
                    916: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    917:                             covariate for which somebody answered including 
                    918:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   919: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    920: double **pmmij, ***probs;
                    921: double *ageexmed,*agecens;
                    922: double dateintmean=0;
                    923: 
                    924: double *weight;
                    925: int **s; /* Status */
1.141     brouard   926: double *agedc;
1.145     brouard   927: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   928:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   929:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   930: double  idx; 
                    931: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   932: int *Tage;
1.145     brouard   933: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   934: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   935: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   936: double *lsurv, *lpop, *tpop;
                    937: 
1.143     brouard   938: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    939: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   940: 
                    941: /**************** split *************************/
                    942: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    943: {
                    944:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    945:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    946:   */ 
                    947:   char *ss;                            /* pointer */
1.186     brouard   948:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   949: 
                    950:   l1 = strlen(path );                  /* length of path */
                    951:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    952:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    953:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    954:     strcpy( name, path );              /* we got the fullname name because no directory */
                    955:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    956:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    957:     /* get current working directory */
                    958:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   959: #ifdef WIN32
                    960:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    961: #else
                    962:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    963: #endif
1.126     brouard   964:       return( GLOCK_ERROR_GETCWD );
                    965:     }
                    966:     /* got dirc from getcwd*/
                    967:     printf(" DIRC = %s \n",dirc);
1.205     brouard   968:   } else {                             /* strip directory from path */
1.126     brouard   969:     ss++;                              /* after this, the filename */
                    970:     l2 = strlen( ss );                 /* length of filename */
                    971:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    972:     strcpy( name, ss );                /* save file name */
                    973:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   974:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   975:     printf(" DIRC2 = %s \n",dirc);
                    976:   }
                    977:   /* We add a separator at the end of dirc if not exists */
                    978:   l1 = strlen( dirc );                 /* length of directory */
                    979:   if( dirc[l1-1] != DIRSEPARATOR ){
                    980:     dirc[l1] =  DIRSEPARATOR;
                    981:     dirc[l1+1] = 0; 
                    982:     printf(" DIRC3 = %s \n",dirc);
                    983:   }
                    984:   ss = strrchr( name, '.' );           /* find last / */
                    985:   if (ss >0){
                    986:     ss++;
                    987:     strcpy(ext,ss);                    /* save extension */
                    988:     l1= strlen( name);
                    989:     l2= strlen(ss)+1;
                    990:     strncpy( finame, name, l1-l2);
                    991:     finame[l1-l2]= 0;
                    992:   }
                    993: 
                    994:   return( 0 );                         /* we're done */
                    995: }
                    996: 
                    997: 
                    998: /******************************************/
                    999: 
                   1000: void replace_back_to_slash(char *s, char*t)
                   1001: {
                   1002:   int i;
                   1003:   int lg=0;
                   1004:   i=0;
                   1005:   lg=strlen(t);
                   1006:   for(i=0; i<= lg; i++) {
                   1007:     (s[i] = t[i]);
                   1008:     if (t[i]== '\\') s[i]='/';
                   1009:   }
                   1010: }
                   1011: 
1.132     brouard  1012: char *trimbb(char *out, char *in)
1.137     brouard  1013: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1014:   char *s;
                   1015:   s=out;
                   1016:   while (*in != '\0'){
1.137     brouard  1017:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1018:       in++;
                   1019:     }
                   1020:     *out++ = *in++;
                   1021:   }
                   1022:   *out='\0';
                   1023:   return s;
                   1024: }
                   1025: 
1.187     brouard  1026: /* char *substrchaine(char *out, char *in, char *chain) */
                   1027: /* { */
                   1028: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1029: /*   char *s, *t; */
                   1030: /*   t=in;s=out; */
                   1031: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1032: /*     *out++ = *in++; */
                   1033: /*   } */
                   1034: 
                   1035: /*   /\* *in matches *chain *\/ */
                   1036: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1037: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1038: /*   } */
                   1039: /*   in--; chain--; */
                   1040: /*   while ( (*in != '\0')){ */
                   1041: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1042: /*     *out++ = *in++; */
                   1043: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1044: /*   } */
                   1045: /*   *out='\0'; */
                   1046: /*   out=s; */
                   1047: /*   return out; */
                   1048: /* } */
                   1049: char *substrchaine(char *out, char *in, char *chain)
                   1050: {
                   1051:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1052:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1053: 
                   1054:   char *strloc;
                   1055: 
                   1056:   strcpy (out, in); 
                   1057:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1058:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1059:   if(strloc != NULL){ 
                   1060:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1061:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1062:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1063:   }
                   1064:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1065:   return out;
                   1066: }
                   1067: 
                   1068: 
1.145     brouard  1069: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1070: {
1.187     brouard  1071:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1072:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1073:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1074:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1075:   */
1.160     brouard  1076:   char *s, *t;
1.145     brouard  1077:   t=in;s=in;
                   1078:   while ((*in != occ) && (*in != '\0')){
                   1079:     *alocc++ = *in++;
                   1080:   }
                   1081:   if( *in == occ){
                   1082:     *(alocc)='\0';
                   1083:     s=++in;
                   1084:   }
                   1085:  
                   1086:   if (s == t) {/* occ not found */
                   1087:     *(alocc-(in-s))='\0';
                   1088:     in=s;
                   1089:   }
                   1090:   while ( *in != '\0'){
                   1091:     *blocc++ = *in++;
                   1092:   }
                   1093: 
                   1094:   *blocc='\0';
                   1095:   return t;
                   1096: }
1.137     brouard  1097: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1098: {
1.187     brouard  1099:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1100:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1101:      gives blocc="abcdef2ghi" and alocc="j".
                   1102:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1103:   */
                   1104:   char *s, *t;
                   1105:   t=in;s=in;
                   1106:   while (*in != '\0'){
                   1107:     while( *in == occ){
                   1108:       *blocc++ = *in++;
                   1109:       s=in;
                   1110:     }
                   1111:     *blocc++ = *in++;
                   1112:   }
                   1113:   if (s == t) /* occ not found */
                   1114:     *(blocc-(in-s))='\0';
                   1115:   else
                   1116:     *(blocc-(in-s)-1)='\0';
                   1117:   in=s;
                   1118:   while ( *in != '\0'){
                   1119:     *alocc++ = *in++;
                   1120:   }
                   1121: 
                   1122:   *alocc='\0';
                   1123:   return s;
                   1124: }
                   1125: 
1.126     brouard  1126: int nbocc(char *s, char occ)
                   1127: {
                   1128:   int i,j=0;
                   1129:   int lg=20;
                   1130:   i=0;
                   1131:   lg=strlen(s);
                   1132:   for(i=0; i<= lg; i++) {
                   1133:   if  (s[i] == occ ) j++;
                   1134:   }
                   1135:   return j;
                   1136: }
                   1137: 
1.137     brouard  1138: /* void cutv(char *u,char *v, char*t, char occ) */
                   1139: /* { */
                   1140: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1141: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1142: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1143: /*   int i,lg,j,p=0; */
                   1144: /*   i=0; */
                   1145: /*   lg=strlen(t); */
                   1146: /*   for(j=0; j<=lg-1; j++) { */
                   1147: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1148: /*   } */
1.126     brouard  1149: 
1.137     brouard  1150: /*   for(j=0; j<p; j++) { */
                   1151: /*     (u[j] = t[j]); */
                   1152: /*   } */
                   1153: /*      u[p]='\0'; */
1.126     brouard  1154: 
1.137     brouard  1155: /*    for(j=0; j<= lg; j++) { */
                   1156: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1157: /*   } */
                   1158: /* } */
1.126     brouard  1159: 
1.160     brouard  1160: #ifdef _WIN32
                   1161: char * strsep(char **pp, const char *delim)
                   1162: {
                   1163:   char *p, *q;
                   1164:          
                   1165:   if ((p = *pp) == NULL)
                   1166:     return 0;
                   1167:   if ((q = strpbrk (p, delim)) != NULL)
                   1168:   {
                   1169:     *pp = q + 1;
                   1170:     *q = '\0';
                   1171:   }
                   1172:   else
                   1173:     *pp = 0;
                   1174:   return p;
                   1175: }
                   1176: #endif
                   1177: 
1.126     brouard  1178: /********************** nrerror ********************/
                   1179: 
                   1180: void nrerror(char error_text[])
                   1181: {
                   1182:   fprintf(stderr,"ERREUR ...\n");
                   1183:   fprintf(stderr,"%s\n",error_text);
                   1184:   exit(EXIT_FAILURE);
                   1185: }
                   1186: /*********************** vector *******************/
                   1187: double *vector(int nl, int nh)
                   1188: {
                   1189:   double *v;
                   1190:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1191:   if (!v) nrerror("allocation failure in vector");
                   1192:   return v-nl+NR_END;
                   1193: }
                   1194: 
                   1195: /************************ free vector ******************/
                   1196: void free_vector(double*v, int nl, int nh)
                   1197: {
                   1198:   free((FREE_ARG)(v+nl-NR_END));
                   1199: }
                   1200: 
                   1201: /************************ivector *******************************/
                   1202: int *ivector(long nl,long nh)
                   1203: {
                   1204:   int *v;
                   1205:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1206:   if (!v) nrerror("allocation failure in ivector");
                   1207:   return v-nl+NR_END;
                   1208: }
                   1209: 
                   1210: /******************free ivector **************************/
                   1211: void free_ivector(int *v, long nl, long nh)
                   1212: {
                   1213:   free((FREE_ARG)(v+nl-NR_END));
                   1214: }
                   1215: 
                   1216: /************************lvector *******************************/
                   1217: long *lvector(long nl,long nh)
                   1218: {
                   1219:   long *v;
                   1220:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1221:   if (!v) nrerror("allocation failure in ivector");
                   1222:   return v-nl+NR_END;
                   1223: }
                   1224: 
                   1225: /******************free lvector **************************/
                   1226: void free_lvector(long *v, long nl, long nh)
                   1227: {
                   1228:   free((FREE_ARG)(v+nl-NR_END));
                   1229: }
                   1230: 
                   1231: /******************* imatrix *******************************/
                   1232: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1233:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1234: { 
                   1235:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1236:   int **m; 
                   1237:   
                   1238:   /* allocate pointers to rows */ 
                   1239:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1240:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1241:   m += NR_END; 
                   1242:   m -= nrl; 
                   1243:   
                   1244:   
                   1245:   /* allocate rows and set pointers to them */ 
                   1246:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1247:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1248:   m[nrl] += NR_END; 
                   1249:   m[nrl] -= ncl; 
                   1250:   
                   1251:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1252:   
                   1253:   /* return pointer to array of pointers to rows */ 
                   1254:   return m; 
                   1255: } 
                   1256: 
                   1257: /****************** free_imatrix *************************/
                   1258: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1259:       int **m;
                   1260:       long nch,ncl,nrh,nrl; 
                   1261:      /* free an int matrix allocated by imatrix() */ 
                   1262: { 
                   1263:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1264:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1265: } 
                   1266: 
                   1267: /******************* matrix *******************************/
                   1268: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1269: {
                   1270:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1271:   double **m;
                   1272: 
                   1273:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1274:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1275:   m += NR_END;
                   1276:   m -= nrl;
                   1277: 
                   1278:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1279:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1280:   m[nrl] += NR_END;
                   1281:   m[nrl] -= ncl;
                   1282: 
                   1283:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1284:   return m;
1.145     brouard  1285:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1286: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1287: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1288:    */
                   1289: }
                   1290: 
                   1291: /*************************free matrix ************************/
                   1292: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1293: {
                   1294:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1295:   free((FREE_ARG)(m+nrl-NR_END));
                   1296: }
                   1297: 
                   1298: /******************* ma3x *******************************/
                   1299: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1300: {
                   1301:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1302:   double ***m;
                   1303: 
                   1304:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1305:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1306:   m += NR_END;
                   1307:   m -= nrl;
                   1308: 
                   1309:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1310:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1311:   m[nrl] += NR_END;
                   1312:   m[nrl] -= ncl;
                   1313: 
                   1314:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1315: 
                   1316:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1317:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1318:   m[nrl][ncl] += NR_END;
                   1319:   m[nrl][ncl] -= nll;
                   1320:   for (j=ncl+1; j<=nch; j++) 
                   1321:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1322:   
                   1323:   for (i=nrl+1; i<=nrh; i++) {
                   1324:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1325:     for (j=ncl+1; j<=nch; j++) 
                   1326:       m[i][j]=m[i][j-1]+nlay;
                   1327:   }
                   1328:   return m; 
                   1329:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1330:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1331:   */
                   1332: }
                   1333: 
                   1334: /*************************free ma3x ************************/
                   1335: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1336: {
                   1337:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1338:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1339:   free((FREE_ARG)(m+nrl-NR_END));
                   1340: }
                   1341: 
                   1342: /*************** function subdirf ***********/
                   1343: char *subdirf(char fileres[])
                   1344: {
                   1345:   /* Caution optionfilefiname is hidden */
                   1346:   strcpy(tmpout,optionfilefiname);
                   1347:   strcat(tmpout,"/"); /* Add to the right */
                   1348:   strcat(tmpout,fileres);
                   1349:   return tmpout;
                   1350: }
                   1351: 
                   1352: /*************** function subdirf2 ***********/
                   1353: char *subdirf2(char fileres[], char *preop)
                   1354: {
                   1355:   
                   1356:   /* Caution optionfilefiname is hidden */
                   1357:   strcpy(tmpout,optionfilefiname);
                   1358:   strcat(tmpout,"/");
                   1359:   strcat(tmpout,preop);
                   1360:   strcat(tmpout,fileres);
                   1361:   return tmpout;
                   1362: }
                   1363: 
                   1364: /*************** function subdirf3 ***********/
                   1365: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1366: {
                   1367:   
                   1368:   /* Caution optionfilefiname is hidden */
                   1369:   strcpy(tmpout,optionfilefiname);
                   1370:   strcat(tmpout,"/");
                   1371:   strcat(tmpout,preop);
                   1372:   strcat(tmpout,preop2);
                   1373:   strcat(tmpout,fileres);
                   1374:   return tmpout;
                   1375: }
                   1376: 
1.162     brouard  1377: char *asc_diff_time(long time_sec, char ascdiff[])
                   1378: {
                   1379:   long sec_left, days, hours, minutes;
                   1380:   days = (time_sec) / (60*60*24);
                   1381:   sec_left = (time_sec) % (60*60*24);
                   1382:   hours = (sec_left) / (60*60) ;
                   1383:   sec_left = (sec_left) %(60*60);
                   1384:   minutes = (sec_left) /60;
                   1385:   sec_left = (sec_left) % (60);
                   1386:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1387:   return ascdiff;
                   1388: }
                   1389: 
1.126     brouard  1390: /***************** f1dim *************************/
                   1391: extern int ncom; 
                   1392: extern double *pcom,*xicom;
                   1393: extern double (*nrfunc)(double []); 
                   1394:  
                   1395: double f1dim(double x) 
                   1396: { 
                   1397:   int j; 
                   1398:   double f;
                   1399:   double *xt; 
                   1400:  
                   1401:   xt=vector(1,ncom); 
                   1402:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1403:   f=(*nrfunc)(xt); 
                   1404:   free_vector(xt,1,ncom); 
                   1405:   return f; 
                   1406: } 
                   1407: 
                   1408: /*****************brent *************************/
                   1409: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1410: {
                   1411:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1412:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1413:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1414:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1415:    * returned function value. 
                   1416:   */
1.126     brouard  1417:   int iter; 
                   1418:   double a,b,d,etemp;
1.159     brouard  1419:   double fu=0,fv,fw,fx;
1.164     brouard  1420:   double ftemp=0.;
1.126     brouard  1421:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1422:   double e=0.0; 
                   1423:  
                   1424:   a=(ax < cx ? ax : cx); 
                   1425:   b=(ax > cx ? ax : cx); 
                   1426:   x=w=v=bx; 
                   1427:   fw=fv=fx=(*f)(x); 
                   1428:   for (iter=1;iter<=ITMAX;iter++) { 
                   1429:     xm=0.5*(a+b); 
                   1430:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1431:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1432:     printf(".");fflush(stdout);
                   1433:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1434: #ifdef DEBUGBRENT
1.126     brouard  1435:     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);
                   1436:     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);
                   1437:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1438: #endif
                   1439:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1440:       *xmin=x; 
                   1441:       return fx; 
                   1442:     } 
                   1443:     ftemp=fu;
                   1444:     if (fabs(e) > tol1) { 
                   1445:       r=(x-w)*(fx-fv); 
                   1446:       q=(x-v)*(fx-fw); 
                   1447:       p=(x-v)*q-(x-w)*r; 
                   1448:       q=2.0*(q-r); 
                   1449:       if (q > 0.0) p = -p; 
                   1450:       q=fabs(q); 
                   1451:       etemp=e; 
                   1452:       e=d; 
                   1453:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1454:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1455:       else { 
                   1456:        d=p/q; 
                   1457:        u=x+d; 
                   1458:        if (u-a < tol2 || b-u < tol2) 
                   1459:          d=SIGN(tol1,xm-x); 
                   1460:       } 
                   1461:     } else { 
                   1462:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1463:     } 
                   1464:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1465:     fu=(*f)(u); 
                   1466:     if (fu <= fx) { 
                   1467:       if (u >= x) a=x; else b=x; 
                   1468:       SHFT(v,w,x,u) 
1.183     brouard  1469:       SHFT(fv,fw,fx,fu) 
                   1470:     } else { 
                   1471:       if (u < x) a=u; else b=u; 
                   1472:       if (fu <= fw || w == x) { 
                   1473:        v=w; 
                   1474:        w=u; 
                   1475:        fv=fw; 
                   1476:        fw=fu; 
                   1477:       } else if (fu <= fv || v == x || v == w) { 
                   1478:        v=u; 
                   1479:        fv=fu; 
                   1480:       } 
                   1481:     } 
1.126     brouard  1482:   } 
                   1483:   nrerror("Too many iterations in brent"); 
                   1484:   *xmin=x; 
                   1485:   return fx; 
                   1486: } 
                   1487: 
                   1488: /****************** mnbrak ***********************/
                   1489: 
                   1490: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1491:            double (*func)(double)) 
1.183     brouard  1492: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1493: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1494: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1495: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1496:    */
1.126     brouard  1497:   double ulim,u,r,q, dum;
                   1498:   double fu; 
1.187     brouard  1499: 
                   1500:   double scale=10.;
                   1501:   int iterscale=0;
                   1502: 
                   1503:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1504:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1505: 
                   1506: 
                   1507:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1508:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1509:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1510:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1511:   /* } */
                   1512: 
1.126     brouard  1513:   if (*fb > *fa) { 
                   1514:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1515:     SHFT(dum,*fb,*fa,dum) 
                   1516:   } 
1.126     brouard  1517:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1518:   *fc=(*func)(*cx); 
1.183     brouard  1519: #ifdef DEBUG
                   1520:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1521:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1522: #endif
                   1523:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1524:     r=(*bx-*ax)*(*fb-*fc); 
                   1525:     q=(*bx-*cx)*(*fb-*fa); 
                   1526:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1527:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1528:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1529:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1530:       fu=(*func)(u); 
1.163     brouard  1531: #ifdef DEBUG
                   1532:       /* f(x)=A(x-u)**2+f(u) */
                   1533:       double A, fparabu; 
                   1534:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1535:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1536:       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);
                   1537:       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  1538:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1539:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1540:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1541:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1542: #endif 
1.184     brouard  1543: #ifdef MNBRAKORIGINAL
1.183     brouard  1544: #else
1.191     brouard  1545: /*       if (fu > *fc) { */
                   1546: /* #ifdef DEBUG */
                   1547: /*       printf("mnbrak4  fu > fc \n"); */
                   1548: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1549: /* #endif */
                   1550: /*     /\* 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 *\\/  *\/ */
                   1551: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1552: /*     dum=u; /\* Shifting c and u *\/ */
                   1553: /*     u = *cx; */
                   1554: /*     *cx = dum; */
                   1555: /*     dum = fu; */
                   1556: /*     fu = *fc; */
                   1557: /*     *fc =dum; */
                   1558: /*       } else { /\* end *\/ */
                   1559: /* #ifdef DEBUG */
                   1560: /*       printf("mnbrak3  fu < fc \n"); */
                   1561: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1562: /* #endif */
                   1563: /*     dum=u; /\* Shifting c and u *\/ */
                   1564: /*     u = *cx; */
                   1565: /*     *cx = dum; */
                   1566: /*     dum = fu; */
                   1567: /*     fu = *fc; */
                   1568: /*     *fc =dum; */
                   1569: /*       } */
1.183     brouard  1570: #ifdef DEBUG
1.191     brouard  1571:       printf("mnbrak34  fu < or >= fc \n");
                   1572:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1573: #endif
1.191     brouard  1574:       dum=u; /* Shifting c and u */
                   1575:       u = *cx;
                   1576:       *cx = dum;
                   1577:       dum = fu;
                   1578:       fu = *fc;
                   1579:       *fc =dum;
1.183     brouard  1580: #endif
1.162     brouard  1581:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1582: #ifdef DEBUG
                   1583:       printf("mnbrak2  u after c but before ulim\n");
                   1584:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1585: #endif
1.126     brouard  1586:       fu=(*func)(u); 
                   1587:       if (fu < *fc) { 
1.183     brouard  1588: #ifdef DEBUG
                   1589:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1590:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1591: #endif
1.126     brouard  1592:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1593:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1594:       } 
1.162     brouard  1595:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1596: #ifdef DEBUG
                   1597:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1598:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1599: #endif
1.126     brouard  1600:       u=ulim; 
                   1601:       fu=(*func)(u); 
1.183     brouard  1602:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1603: #ifdef DEBUG
                   1604:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1605:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1606: #endif
1.126     brouard  1607:       u=(*cx)+GOLD*(*cx-*bx); 
                   1608:       fu=(*func)(u); 
1.183     brouard  1609:     } /* end tests */
1.126     brouard  1610:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1611:     SHFT(*fa,*fb,*fc,fu) 
                   1612: #ifdef DEBUG
                   1613:       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);
                   1614:       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);
                   1615: #endif
                   1616:   } /* 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  1617: } 
                   1618: 
                   1619: /*************** linmin ************************/
1.162     brouard  1620: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1621: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1622: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1623: the value of func at the returned location p . This is actually all accomplished by calling the
                   1624: routines mnbrak and brent .*/
1.126     brouard  1625: int ncom; 
                   1626: double *pcom,*xicom;
                   1627: double (*nrfunc)(double []); 
                   1628:  
                   1629: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1630: { 
                   1631:   double brent(double ax, double bx, double cx, 
                   1632:               double (*f)(double), double tol, double *xmin); 
                   1633:   double f1dim(double x); 
                   1634:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1635:              double *fc, double (*func)(double)); 
                   1636:   int j; 
                   1637:   double xx,xmin,bx,ax; 
                   1638:   double fx,fb,fa;
1.187     brouard  1639: 
1.203     brouard  1640: #ifdef LINMINORIGINAL
                   1641: #else
                   1642:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1643: #endif
                   1644:   
1.126     brouard  1645:   ncom=n; 
                   1646:   pcom=vector(1,n); 
                   1647:   xicom=vector(1,n); 
                   1648:   nrfunc=func; 
                   1649:   for (j=1;j<=n;j++) { 
                   1650:     pcom[j]=p[j]; 
1.202     brouard  1651:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1652:   } 
1.187     brouard  1653: 
1.203     brouard  1654: #ifdef LINMINORIGINAL
                   1655:   xx=1.;
                   1656: #else
                   1657:   axs=0.0;
                   1658:   xxs=1.;
                   1659:   do{
                   1660:     xx= xxs;
                   1661: #endif
1.187     brouard  1662:     ax=0.;
                   1663:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1664:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1665:     /* 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))   */
                   1666:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1667:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1668:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1669:     /* 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  1670: #ifdef LINMINORIGINAL
                   1671: #else
                   1672:     if (fx != fx){
                   1673:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1674:        printf("|");
                   1675:        fprintf(ficlog,"|");
                   1676: #ifdef DEBUGLINMIN
                   1677:        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);
                   1678: #endif
                   1679:     }
                   1680:   }while(fx != fx);
                   1681: #endif
                   1682:   
1.191     brouard  1683: #ifdef DEBUGLINMIN
                   1684:   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  1685:   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  1686: #endif
1.187     brouard  1687:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1688:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1689:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1690:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1691:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1692: #ifdef DEBUG
                   1693:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1694:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1695: #endif
1.191     brouard  1696: #ifdef DEBUGLINMIN
                   1697:   printf("linmin end ");
1.202     brouard  1698:   fprintf(ficlog,"linmin end ");
1.191     brouard  1699: #endif
1.126     brouard  1700:   for (j=1;j<=n;j++) { 
1.203     brouard  1701: #ifdef LINMINORIGINAL
                   1702:     xi[j] *= xmin; 
                   1703: #else
                   1704: #ifdef DEBUGLINMIN
                   1705:     if(xxs <1.0)
                   1706:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1707: #endif
                   1708:     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) */
                   1709: #ifdef DEBUGLINMIN
                   1710:     if(xxs <1.0)
                   1711:       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 );
                   1712: #endif
                   1713: #endif
1.187     brouard  1714:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1715:   } 
1.191     brouard  1716: #ifdef DEBUGLINMIN
1.203     brouard  1717:   printf("\n");
1.191     brouard  1718:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1719:   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  1720:   for (j=1;j<=n;j++) { 
1.202     brouard  1721:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1722:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1723:     if(j % ncovmodel == 0){
1.191     brouard  1724:       printf("\n");
1.202     brouard  1725:       fprintf(ficlog,"\n");
                   1726:     }
1.191     brouard  1727:   }
1.203     brouard  1728: #else
1.191     brouard  1729: #endif
1.126     brouard  1730:   free_vector(xicom,1,n); 
                   1731:   free_vector(pcom,1,n); 
                   1732: } 
                   1733: 
                   1734: 
                   1735: /*************** powell ************************/
1.162     brouard  1736: /*
                   1737: Minimization of a function func of n variables. Input consists of an initial starting point
                   1738: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1739: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1740: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1741: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1742: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1743:  */
1.126     brouard  1744: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1745:            double (*func)(double [])) 
                   1746: { 
                   1747:   void linmin(double p[], double xi[], int n, double *fret, 
                   1748:              double (*func)(double [])); 
                   1749:   int i,ibig,j; 
                   1750:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1751:   double directest;
1.126     brouard  1752:   double fp,fptt;
                   1753:   double *xits;
                   1754:   int niterf, itmp;
                   1755: 
                   1756:   pt=vector(1,n); 
                   1757:   ptt=vector(1,n); 
                   1758:   xit=vector(1,n); 
                   1759:   xits=vector(1,n); 
                   1760:   *fret=(*func)(p); 
                   1761:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1762:   rcurr_time = time(NULL);  
1.126     brouard  1763:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1764:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1765:     ibig=0; 
                   1766:     del=0.0; 
1.157     brouard  1767:     rlast_time=rcurr_time;
                   1768:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1769:     rcurr_time = time(NULL);  
                   1770:     curr_time = *localtime(&rcurr_time);
                   1771:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1772:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1773: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1774:     for (i=1;i<=n;i++) {
1.126     brouard  1775:       printf(" %d %.12f",i, p[i]);
                   1776:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1777:       fprintf(ficrespow," %.12lf", p[i]);
                   1778:     }
                   1779:     printf("\n");
                   1780:     fprintf(ficlog,"\n");
                   1781:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1782:     if(*iter <=3){
1.157     brouard  1783:       tml = *localtime(&rcurr_time);
                   1784:       strcpy(strcurr,asctime(&tml));
                   1785:       rforecast_time=rcurr_time; 
1.126     brouard  1786:       itmp = strlen(strcurr);
                   1787:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1788:        strcurr[itmp-1]='\0';
1.162     brouard  1789:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1790:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1791:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1792:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1793:        forecast_time = *localtime(&rforecast_time);
                   1794:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1795:        itmp = strlen(strfor);
                   1796:        if(strfor[itmp-1]=='\n')
                   1797:        strfor[itmp-1]='\0';
1.157     brouard  1798:        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);
                   1799:        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  1800:       }
                   1801:     }
1.187     brouard  1802:     for (i=1;i<=n;i++) { /* For each direction i */
                   1803:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1804:       fptt=(*fret); 
                   1805: #ifdef DEBUG
1.203     brouard  1806:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1807:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1808: #endif
1.203     brouard  1809:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1810:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1811:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1812:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1813:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1814:        /* because that direction will be replaced unless the gain del is small */
                   1815:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1816:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1817:        /* with the new direction. */
1.126     brouard  1818:        del=fabs(fptt-(*fret)); 
                   1819:        ibig=i; 
                   1820:       } 
                   1821: #ifdef DEBUG
                   1822:       printf("%d %.12e",i,(*fret));
                   1823:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1824:       for (j=1;j<=n;j++) {
                   1825:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1826:        printf(" x(%d)=%.12e",j,xit[j]);
                   1827:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1828:       }
                   1829:       for(j=1;j<=n;j++) {
1.162     brouard  1830:        printf(" p(%d)=%.12e",j,p[j]);
                   1831:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1832:       }
                   1833:       printf("\n");
                   1834:       fprintf(ficlog,"\n");
                   1835: #endif
1.187     brouard  1836:     } /* end loop on each direction i */
                   1837:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1838:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1839:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1840:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1841:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1842:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1843:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1844:       /* decreased of more than 3.84  */
                   1845:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1846:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1847:       /* By adding 10 parameters more the gain should be 18.31 */
                   1848: 
                   1849:       /* Starting the program with initial values given by a former maximization will simply change */
                   1850:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1851:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1852:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1853: #ifdef DEBUG
                   1854:       int k[2],l;
                   1855:       k[0]=1;
                   1856:       k[1]=-1;
                   1857:       printf("Max: %.12e",(*func)(p));
                   1858:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1859:       for (j=1;j<=n;j++) {
                   1860:        printf(" %.12e",p[j]);
                   1861:        fprintf(ficlog," %.12e",p[j]);
                   1862:       }
                   1863:       printf("\n");
                   1864:       fprintf(ficlog,"\n");
                   1865:       for(l=0;l<=1;l++) {
                   1866:        for (j=1;j<=n;j++) {
                   1867:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1868:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1869:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1870:        }
                   1871:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1872:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1873:       }
                   1874: #endif
                   1875: 
                   1876: 
                   1877:       free_vector(xit,1,n); 
                   1878:       free_vector(xits,1,n); 
                   1879:       free_vector(ptt,1,n); 
                   1880:       free_vector(pt,1,n); 
                   1881:       return; 
1.192     brouard  1882:     } /* enough precision */ 
1.126     brouard  1883:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1884:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1885:       ptt[j]=2.0*p[j]-pt[j]; 
                   1886:       xit[j]=p[j]-pt[j]; 
                   1887:       pt[j]=p[j]; 
                   1888:     } 
1.181     brouard  1889:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1890: #ifdef POWELLF1F3
                   1891: #else
1.161     brouard  1892:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1893: #endif
1.162     brouard  1894:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1895:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1896:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1897:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1898:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1899:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1900:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1901: #ifdef NRCORIGINAL
                   1902:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1903: #else
                   1904:       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  1905:       t= t- del*SQR(fp-fptt);
1.183     brouard  1906: #endif
1.202     brouard  1907:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1908: #ifdef DEBUG
1.181     brouard  1909:       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);
                   1910:       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  1911:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1912:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1913:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1914:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1915:       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);
                   1916:       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);
                   1917: #endif
1.183     brouard  1918: #ifdef POWELLORIGINAL
                   1919:       if (t < 0.0) { /* Then we use it for new direction */
                   1920: #else
1.182     brouard  1921:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1922:        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  1923:         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  1924:         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  1925:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1926:       } 
1.181     brouard  1927:       if (directest < 0.0) { /* Then we use it for new direction */
                   1928: #endif
1.191     brouard  1929: #ifdef DEBUGLINMIN
                   1930:        printf("Before linmin in direction P%d-P0\n",n);
                   1931:        for (j=1;j<=n;j++) { 
1.202     brouard  1932:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1933:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1934:          if(j % ncovmodel == 0){
1.191     brouard  1935:            printf("\n");
1.202     brouard  1936:            fprintf(ficlog,"\n");
                   1937:          }
1.191     brouard  1938:        }
                   1939: #endif
1.187     brouard  1940:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1941: #ifdef DEBUGLINMIN
                   1942:        for (j=1;j<=n;j++) { 
                   1943:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1944:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1945:          if(j % ncovmodel == 0){
1.191     brouard  1946:            printf("\n");
1.202     brouard  1947:            fprintf(ficlog,"\n");
                   1948:          }
1.191     brouard  1949:        }
                   1950: #endif
1.126     brouard  1951:        for (j=1;j<=n;j++) { 
1.181     brouard  1952:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1953:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1954:        }
1.181     brouard  1955:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1956:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1957: 
1.126     brouard  1958: #ifdef DEBUG
1.164     brouard  1959:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1960:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1961:        for(j=1;j<=n;j++){
                   1962:          printf(" %.12e",xit[j]);
                   1963:          fprintf(ficlog," %.12e",xit[j]);
                   1964:        }
                   1965:        printf("\n");
                   1966:        fprintf(ficlog,"\n");
                   1967: #endif
1.192     brouard  1968:       } /* end of t or directest negative */
                   1969: #ifdef POWELLF1F3
                   1970: #else
1.162     brouard  1971:     } /* end if (fptt < fp)  */
1.192     brouard  1972: #endif
                   1973:   } /* loop iteration */ 
1.126     brouard  1974: } 
                   1975: 
                   1976: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1977: 
1.203     brouard  1978: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1979: {
                   1980:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  1981:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  1982:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   1983:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   1984:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   1985:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   1986:   /* Initial matrix pimij */
                   1987:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   1988:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   1989:   /*  0,                   0                  , 1} */
                   1990:   /*
                   1991:    * and after some iteration: */
                   1992:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   1993:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   1994:   /*  0,                   0                  , 1} */
                   1995:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   1996:   /* {0.51571254859325999, 0.4842874514067399, */
                   1997:   /*  0.51326036147820708, 0.48673963852179264} */
                   1998:   /* If we start from prlim again, prlim tends to a constant matrix */
                   1999: 
1.126     brouard  2000:   int i, ii,j,k;
1.209     brouard  2001:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2002:   /* double **matprod2(); */ /* test */
1.131     brouard  2003:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  2004:   double **newm;
1.209     brouard  2005:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2006:   int ncvloop=0;
1.169     brouard  2007:   
1.209     brouard  2008:   min=vector(1,nlstate);
                   2009:   max=vector(1,nlstate);
                   2010:   meandiff=vector(1,nlstate);
                   2011: 
1.126     brouard  2012:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2013:     for (j=1;j<=nlstate+ndeath;j++){
                   2014:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2015:     }
1.169     brouard  2016:   
                   2017:   cov[1]=1.;
                   2018:   
                   2019:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2020:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2021:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2022:     ncvloop++;
1.126     brouard  2023:     newm=savm;
                   2024:     /* Covariates have to be included here again */
1.138     brouard  2025:     cov[2]=agefin;
1.187     brouard  2026:     if(nagesqr==1)
                   2027:       cov[3]= agefin*agefin;;
1.138     brouard  2028:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2029:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2030:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2031:       /* 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  2032:     }
1.186     brouard  2033:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2034:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2035:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2036:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2037:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2038:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2039:     
                   2040:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2041:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2042:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2043:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2044:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2045:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2046:     
1.126     brouard  2047:     savm=oldm;
                   2048:     oldm=newm;
1.209     brouard  2049: 
                   2050:     for(j=1; j<=nlstate; j++){
                   2051:       max[j]=0.;
                   2052:       min[j]=1.;
                   2053:     }
                   2054:     for(i=1;i<=nlstate;i++){
                   2055:       sumnew=0;
                   2056:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2057:       for(j=1; j<=nlstate; j++){ 
                   2058:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2059:        max[j]=FMAX(max[j],prlim[i][j]);
                   2060:        min[j]=FMIN(min[j],prlim[i][j]);
                   2061:       }
                   2062:     }
                   2063: 
1.126     brouard  2064:     maxmax=0.;
1.209     brouard  2065:     for(j=1; j<=nlstate; j++){
                   2066:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2067:       maxmax=FMAX(maxmax,meandiff[j]);
                   2068:       /* 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  2069:     } /* j loop */
1.203     brouard  2070:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2071:     /* 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  2072:     if(maxmax < ftolpl){
1.209     brouard  2073:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2074:       free_vector(min,1,nlstate);
                   2075:       free_vector(max,1,nlstate);
                   2076:       free_vector(meandiff,1,nlstate);
1.126     brouard  2077:       return prlim;
                   2078:     }
1.169     brouard  2079:   } /* age loop */
1.208     brouard  2080:     /* After some age loop it doesn't converge */
1.209     brouard  2081:   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  2082: 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  2083:   /* 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); */
                   2084:   free_vector(min,1,nlstate);
                   2085:   free_vector(max,1,nlstate);
                   2086:   free_vector(meandiff,1,nlstate);
1.208     brouard  2087:   
1.169     brouard  2088:   return prlim; /* should not reach here */
1.126     brouard  2089: }
                   2090: 
                   2091: /*************** transition probabilities ***************/ 
                   2092: 
                   2093: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2094: {
1.138     brouard  2095:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2096:      computes the probability to be observed in state j being in state i by appying the
                   2097:      model to the ncovmodel covariates (including constant and age).
                   2098:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2099:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2100:      ncth covariate in the global vector x is given by the formula:
                   2101:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2102:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2103:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2104:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2105:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2106:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2107:   */
                   2108:   double s1, lnpijopii;
1.126     brouard  2109:   /*double t34;*/
1.164     brouard  2110:   int i,j, nc, ii, jj;
1.126     brouard  2111: 
                   2112:     for(i=1; i<= nlstate; i++){
                   2113:       for(j=1; j<i;j++){
1.138     brouard  2114:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2115:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2116:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2117: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2118:        }
1.138     brouard  2119:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2120: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2121:       }
                   2122:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2123:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2124:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2125:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2126: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2127:        }
1.138     brouard  2128:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2129:       }
                   2130:     }
                   2131:     
                   2132:     for(i=1; i<= nlstate; i++){
                   2133:       s1=0;
1.131     brouard  2134:       for(j=1; j<i; j++){
1.138     brouard  2135:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2136:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2137:       }
                   2138:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2139:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2140:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2141:       }
1.138     brouard  2142:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2143:       ps[i][i]=1./(s1+1.);
1.138     brouard  2144:       /* Computing other pijs */
1.126     brouard  2145:       for(j=1; j<i; j++)
                   2146:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2147:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2148:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2149:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2150:     } /* end i */
                   2151:     
                   2152:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2153:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2154:        ps[ii][jj]=0;
                   2155:        ps[ii][ii]=1;
                   2156:       }
                   2157:     }
                   2158:     
1.145     brouard  2159:     
                   2160:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2161:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2162:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2163:     /*   } */
                   2164:     /*   printf("\n "); */
                   2165:     /* } */
                   2166:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2167:     /*
1.126     brouard  2168:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2169:       goto end;*/
                   2170:     return ps;
                   2171: }
                   2172: 
                   2173: /**************** Product of 2 matrices ******************/
                   2174: 
1.145     brouard  2175: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2176: {
                   2177:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2178:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2179:   /* in, b, out are matrice of pointers which should have been initialized 
                   2180:      before: only the contents of out is modified. The function returns
                   2181:      a pointer to pointers identical to out */
1.145     brouard  2182:   int i, j, k;
1.126     brouard  2183:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2184:     for(k=ncolol; k<=ncoloh; k++){
                   2185:       out[i][k]=0.;
                   2186:       for(j=ncl; j<=nch; j++)
                   2187:        out[i][k] +=in[i][j]*b[j][k];
                   2188:     }
1.126     brouard  2189:   return out;
                   2190: }
                   2191: 
                   2192: 
                   2193: /************* Higher Matrix Product ***************/
                   2194: 
                   2195: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2196: {
                   2197:   /* Computes the transition matrix starting at age 'age' over 
                   2198:      'nhstepm*hstepm*stepm' months (i.e. until
                   2199:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2200:      nhstepm*hstepm matrices. 
                   2201:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2202:      (typically every 2 years instead of every month which is too big 
                   2203:      for the memory).
                   2204:      Model is determined by parameters x and covariates have to be 
                   2205:      included manually here. 
                   2206: 
                   2207:      */
                   2208: 
                   2209:   int i, j, d, h, k;
1.131     brouard  2210:   double **out, cov[NCOVMAX+1];
1.126     brouard  2211:   double **newm;
1.187     brouard  2212:   double agexact;
1.126     brouard  2213: 
                   2214:   /* Hstepm could be zero and should return the unit matrix */
                   2215:   for (i=1;i<=nlstate+ndeath;i++)
                   2216:     for (j=1;j<=nlstate+ndeath;j++){
                   2217:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2218:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2219:     }
                   2220:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2221:   for(h=1; h <=nhstepm; h++){
                   2222:     for(d=1; d <=hstepm; d++){
                   2223:       newm=savm;
                   2224:       /* Covariates have to be included here again */
                   2225:       cov[1]=1.;
1.187     brouard  2226:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2227:       cov[2]=agexact;
                   2228:       if(nagesqr==1)
                   2229:        cov[3]= agexact*agexact;
1.131     brouard  2230:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2231:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2232:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2233:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2234:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2235:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2236:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2237:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2238:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2239:        /* 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  2240: 
                   2241: 
                   2242:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2243:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2244:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2245:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2246:       savm=oldm;
                   2247:       oldm=newm;
                   2248:     }
                   2249:     for(i=1; i<=nlstate+ndeath; i++)
                   2250:       for(j=1;j<=nlstate+ndeath;j++) {
                   2251:        po[i][j][h]=newm[i][j];
1.128     brouard  2252:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2253:       }
1.128     brouard  2254:     /*printf("h=%d ",h);*/
1.126     brouard  2255:   } /* end h */
1.128     brouard  2256: /*     printf("\n H=%d \n",h); */
1.126     brouard  2257:   return po;
                   2258: }
                   2259: 
1.162     brouard  2260: #ifdef NLOPT
                   2261:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2262:   double fret;
                   2263:   double *xt;
                   2264:   int j;
                   2265:   myfunc_data *d2 = (myfunc_data *) pd;
                   2266: /* xt = (p1-1); */
                   2267:   xt=vector(1,n); 
                   2268:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2269: 
                   2270:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2271:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2272:   printf("Function = %.12lf ",fret);
                   2273:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2274:   printf("\n");
                   2275:  free_vector(xt,1,n);
                   2276:   return fret;
                   2277: }
                   2278: #endif
1.126     brouard  2279: 
                   2280: /*************** log-likelihood *************/
                   2281: double func( double *x)
                   2282: {
                   2283:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2284:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2285:   double **out;
                   2286:   double sw; /* Sum of weights */
                   2287:   double lli; /* Individual log likelihood */
                   2288:   int s1, s2;
                   2289:   double bbh, survp;
                   2290:   long ipmx;
1.187     brouard  2291:   double agexact;
1.126     brouard  2292:   /*extern weight */
                   2293:   /* We are differentiating ll according to initial status */
                   2294:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2295:   /*for(i=1;i<imx;i++) 
                   2296:     printf(" %d\n",s[4][i]);
                   2297:   */
1.162     brouard  2298: 
                   2299:   ++countcallfunc;
                   2300: 
1.126     brouard  2301:   cov[1]=1.;
                   2302: 
                   2303:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2304: 
                   2305:   if(mle==1){
                   2306:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2307:       /* Computes the values of the ncovmodel covariates of the model
                   2308:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2309:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2310:         to be observed in j being in i according to the model.
                   2311:        */
1.145     brouard  2312:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2313:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2314:       }
1.137     brouard  2315:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2316:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2317:         has been calculated etc */
1.126     brouard  2318:       for(mi=1; mi<= wav[i]-1; mi++){
                   2319:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2320:          for (j=1;j<=nlstate+ndeath;j++){
                   2321:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2322:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2323:          }
                   2324:        for(d=0; d<dh[mi][i]; d++){
                   2325:          newm=savm;
1.187     brouard  2326:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2327:          cov[2]=agexact;
                   2328:          if(nagesqr==1)
                   2329:            cov[3]= agexact*agexact;
1.126     brouard  2330:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2331:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2332:          }
                   2333:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2334:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2335:          savm=oldm;
                   2336:          oldm=newm;
                   2337:        } /* end mult */
                   2338:       
                   2339:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2340:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2341:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2342:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2343:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2344:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2345:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2346:         * probability in order to take into account the bias as a fraction of the way
                   2347:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2348:         * -stepm/2 to stepm/2 .
                   2349:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2350:         * For stepm > 1 the results are less biased than in previous versions. 
                   2351:         */
                   2352:        s1=s[mw[mi][i]][i];
                   2353:        s2=s[mw[mi+1][i]][i];
                   2354:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2355:        /* bias bh is positive if real duration
                   2356:         * is higher than the multiple of stepm and negative otherwise.
                   2357:         */
                   2358:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2359:        if( s2 > nlstate){ 
                   2360:          /* i.e. if s2 is a death state and if the date of death is known 
                   2361:             then the contribution to the likelihood is the probability to 
                   2362:             die between last step unit time and current  step unit time, 
                   2363:             which is also equal to probability to die before dh 
                   2364:             minus probability to die before dh-stepm . 
                   2365:             In version up to 0.92 likelihood was computed
                   2366:        as if date of death was unknown. Death was treated as any other
                   2367:        health state: the date of the interview describes the actual state
                   2368:        and not the date of a change in health state. The former idea was
                   2369:        to consider that at each interview the state was recorded
                   2370:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2371:        introduced the exact date of death then we should have modified
                   2372:        the contribution of an exact death to the likelihood. This new
                   2373:        contribution is smaller and very dependent of the step unit
                   2374:        stepm. It is no more the probability to die between last interview
                   2375:        and month of death but the probability to survive from last
                   2376:        interview up to one month before death multiplied by the
                   2377:        probability to die within a month. Thanks to Chris
                   2378:        Jackson for correcting this bug.  Former versions increased
                   2379:        mortality artificially. The bad side is that we add another loop
                   2380:        which slows down the processing. The difference can be up to 10%
                   2381:        lower mortality.
                   2382:          */
1.183     brouard  2383:        /* If, at the beginning of the maximization mostly, the
                   2384:           cumulative probability or probability to be dead is
                   2385:           constant (ie = 1) over time d, the difference is equal to
                   2386:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2387:           s1 at precedent wave, to be dead a month before current
                   2388:           wave is equal to probability, being at state s1 at
                   2389:           precedent wave, to be dead at mont of the current
                   2390:           wave. Then the observed probability (that this person died)
                   2391:           is null according to current estimated parameter. In fact,
                   2392:           it should be very low but not zero otherwise the log go to
                   2393:           infinity.
                   2394:        */
                   2395: /* #ifdef INFINITYORIGINAL */
                   2396: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2397: /* #else */
                   2398: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2399: /*         lli=log(mytinydouble); */
                   2400: /*       else */
                   2401: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2402: /* #endif */
                   2403:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2404: 
                   2405:        } else if  (s2==-2) {
                   2406:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2407:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2408:          /*survp += out[s1][j]; */
                   2409:          lli= log(survp);
                   2410:        }
                   2411:        
                   2412:        else if  (s2==-4) { 
                   2413:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2414:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2415:          lli= log(survp); 
                   2416:        } 
                   2417: 
                   2418:        else if  (s2==-5) { 
                   2419:          for (j=1,survp=0. ; j<=2; j++)  
                   2420:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2421:          lli= log(survp); 
                   2422:        } 
                   2423:        
                   2424:        else{
                   2425:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2426:          /*  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 */
                   2427:        } 
                   2428:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2429:        /*if(lli ==000.0)*/
                   2430:        /*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); */
                   2431:        ipmx +=1;
                   2432:        sw += weight[i];
                   2433:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2434:        /* if (lli < log(mytinydouble)){ */
                   2435:        /*   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); */
                   2436:        /*   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]); */
                   2437:        /* } */
1.126     brouard  2438:       } /* end of wave */
                   2439:     } /* end of individual */
                   2440:   }  else if(mle==2){
                   2441:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2442:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2443:       for(mi=1; mi<= wav[i]-1; mi++){
                   2444:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2445:          for (j=1;j<=nlstate+ndeath;j++){
                   2446:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2447:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2448:          }
                   2449:        for(d=0; d<=dh[mi][i]; d++){
                   2450:          newm=savm;
1.187     brouard  2451:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2452:          cov[2]=agexact;
                   2453:          if(nagesqr==1)
                   2454:            cov[3]= agexact*agexact;
1.126     brouard  2455:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2456:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2457:          }
                   2458:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2459:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2460:          savm=oldm;
                   2461:          oldm=newm;
                   2462:        } /* end mult */
                   2463:       
                   2464:        s1=s[mw[mi][i]][i];
                   2465:        s2=s[mw[mi+1][i]][i];
                   2466:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2467:        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 */
                   2468:        ipmx +=1;
                   2469:        sw += weight[i];
                   2470:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2471:       } /* end of wave */
                   2472:     } /* end of individual */
                   2473:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2474:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2475:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2476:       for(mi=1; mi<= wav[i]-1; mi++){
                   2477:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2478:          for (j=1;j<=nlstate+ndeath;j++){
                   2479:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2480:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2481:          }
                   2482:        for(d=0; d<dh[mi][i]; d++){
                   2483:          newm=savm;
1.187     brouard  2484:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2485:          cov[2]=agexact;
                   2486:          if(nagesqr==1)
                   2487:            cov[3]= agexact*agexact;
1.126     brouard  2488:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2489:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2490:          }
                   2491:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2492:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2493:          savm=oldm;
                   2494:          oldm=newm;
                   2495:        } /* end mult */
                   2496:       
                   2497:        s1=s[mw[mi][i]][i];
                   2498:        s2=s[mw[mi+1][i]][i];
                   2499:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2500:        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 */
                   2501:        ipmx +=1;
                   2502:        sw += weight[i];
                   2503:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2504:       } /* end of wave */
                   2505:     } /* end of individual */
                   2506:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2507:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2508:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2509:       for(mi=1; mi<= wav[i]-1; mi++){
                   2510:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2511:          for (j=1;j<=nlstate+ndeath;j++){
                   2512:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2513:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2514:          }
                   2515:        for(d=0; d<dh[mi][i]; d++){
                   2516:          newm=savm;
1.187     brouard  2517:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2518:          cov[2]=agexact;
                   2519:          if(nagesqr==1)
                   2520:            cov[3]= agexact*agexact;
1.126     brouard  2521:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2522:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2523:          }
                   2524:        
                   2525:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2526:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2527:          savm=oldm;
                   2528:          oldm=newm;
                   2529:        } /* end mult */
                   2530:       
                   2531:        s1=s[mw[mi][i]][i];
                   2532:        s2=s[mw[mi+1][i]][i];
                   2533:        if( s2 > nlstate){ 
                   2534:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2535:        }else{
                   2536:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2537:        }
                   2538:        ipmx +=1;
                   2539:        sw += weight[i];
                   2540:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2541: /*     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]); */
                   2542:       } /* end of wave */
                   2543:     } /* end of individual */
                   2544:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2545:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2546:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2547:       for(mi=1; mi<= wav[i]-1; mi++){
                   2548:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2549:          for (j=1;j<=nlstate+ndeath;j++){
                   2550:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2551:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2552:          }
                   2553:        for(d=0; d<dh[mi][i]; d++){
                   2554:          newm=savm;
1.187     brouard  2555:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2556:          cov[2]=agexact;
                   2557:          if(nagesqr==1)
                   2558:            cov[3]= agexact*agexact;
1.126     brouard  2559:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2560:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2561:          }
                   2562:        
                   2563:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2564:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2565:          savm=oldm;
                   2566:          oldm=newm;
                   2567:        } /* end mult */
                   2568:       
                   2569:        s1=s[mw[mi][i]][i];
                   2570:        s2=s[mw[mi+1][i]][i];
                   2571:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2572:        ipmx +=1;
                   2573:        sw += weight[i];
                   2574:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2575:        /*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]);*/
                   2576:       } /* end of wave */
                   2577:     } /* end of individual */
                   2578:   } /* End of if */
                   2579:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2580:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2581:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2582:   return -l;
                   2583: }
                   2584: 
                   2585: /*************** log-likelihood *************/
                   2586: double funcone( double *x)
                   2587: {
                   2588:   /* Same as likeli but slower because of a lot of printf and if */
                   2589:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2590:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2591:   double **out;
                   2592:   double lli; /* Individual log likelihood */
                   2593:   double llt;
                   2594:   int s1, s2;
                   2595:   double bbh, survp;
1.187     brouard  2596:   double agexact;
1.126     brouard  2597:   /*extern weight */
                   2598:   /* We are differentiating ll according to initial status */
                   2599:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2600:   /*for(i=1;i<imx;i++) 
                   2601:     printf(" %d\n",s[4][i]);
                   2602:   */
                   2603:   cov[1]=1.;
                   2604: 
                   2605:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2606: 
                   2607:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2608:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2609:     for(mi=1; mi<= wav[i]-1; mi++){
                   2610:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2611:        for (j=1;j<=nlstate+ndeath;j++){
                   2612:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2613:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2614:        }
                   2615:       for(d=0; d<dh[mi][i]; d++){
                   2616:        newm=savm;
1.187     brouard  2617:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2618:        cov[2]=agexact;
                   2619:        if(nagesqr==1)
                   2620:          cov[3]= agexact*agexact;
1.126     brouard  2621:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2622:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2623:        }
1.187     brouard  2624: 
1.145     brouard  2625:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2626:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2627:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2628:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2629:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2630:        savm=oldm;
                   2631:        oldm=newm;
                   2632:       } /* end mult */
                   2633:       
                   2634:       s1=s[mw[mi][i]][i];
                   2635:       s2=s[mw[mi+1][i]][i];
                   2636:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2637:       /* bias is positive if real duration
                   2638:        * is higher than the multiple of stepm and negative otherwise.
                   2639:        */
                   2640:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2641:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2642:       } else if  (s2==-2) {
                   2643:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2644:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2645:        lli= log(survp);
                   2646:       }else if (mle==1){
                   2647:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2648:       } else if(mle==2){
                   2649:        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 */
                   2650:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2651:        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 */
                   2652:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2653:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2654:       } else{  /* mle=0 back to 1 */
                   2655:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2656:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2657:       } /* End of if */
                   2658:       ipmx +=1;
                   2659:       sw += weight[i];
                   2660:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2661:       /*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  2662:       if(globpr){
1.205     brouard  2663:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2664:  %11.6f %11.6f %11.6f ", \
1.205     brouard  2665:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  2666:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2667:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2668:          llt +=ll[k]*gipmx/gsw;
                   2669:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2670:        }
                   2671:        fprintf(ficresilk," %10.6f\n", -llt);
                   2672:       }
                   2673:     } /* end of wave */
                   2674:   } /* end of individual */
                   2675:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2676:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2677:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2678:   if(globpr==0){ /* First time we count the contributions and weights */
                   2679:     gipmx=ipmx;
                   2680:     gsw=sw;
                   2681:   }
                   2682:   return -l;
                   2683: }
                   2684: 
                   2685: 
                   2686: /*************** function likelione ***********/
                   2687: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2688: {
                   2689:   /* This routine should help understanding what is done with 
                   2690:      the selection of individuals/waves and
                   2691:      to check the exact contribution to the likelihood.
                   2692:      Plotting could be done.
                   2693:    */
                   2694:   int k;
                   2695: 
                   2696:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2697:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2698:     strcat(fileresilk,fileresu);
1.126     brouard  2699:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2700:       printf("Problem with resultfile: %s\n", fileresilk);
                   2701:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2702:     }
1.205     brouard  2703:     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  2704:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2705:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2706:     for(k=1; k<=nlstate; k++) 
                   2707:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2708:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2709:   }
                   2710: 
                   2711:   *fretone=(*funcone)(p);
                   2712:   if(*globpri !=0){
                   2713:     fclose(ficresilk);
1.205     brouard  2714:     if (mle ==0)
                   2715:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2716:     else if(mle >=1)
                   2717:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2718:     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  2719:     
1.208     brouard  2720:       
                   2721:     for (k=1; k<= nlstate ; k++) {
                   2722:       fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   2723: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   2724:     }
1.207     brouard  2725:     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  2726: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2727:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2728: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2729:     fflush(fichtm);
1.205     brouard  2730:   }
1.126     brouard  2731:   return;
                   2732: }
                   2733: 
                   2734: 
                   2735: /*********** Maximum Likelihood Estimation ***************/
                   2736: 
                   2737: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2738: {
1.165     brouard  2739:   int i,j, iter=0;
1.126     brouard  2740:   double **xi;
                   2741:   double fret;
                   2742:   double fretone; /* Only one call to likelihood */
                   2743:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2744: 
                   2745: #ifdef NLOPT
                   2746:   int creturn;
                   2747:   nlopt_opt opt;
                   2748:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2749:   double *lb;
                   2750:   double minf; /* the minimum objective value, upon return */
                   2751:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2752:   myfunc_data dinst, *d = &dinst;
                   2753: #endif
                   2754: 
                   2755: 
1.126     brouard  2756:   xi=matrix(1,npar,1,npar);
                   2757:   for (i=1;i<=npar;i++)
                   2758:     for (j=1;j<=npar;j++)
                   2759:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2760:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2761:   strcpy(filerespow,"POW_"); 
1.126     brouard  2762:   strcat(filerespow,fileres);
                   2763:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2764:     printf("Problem with resultfile: %s\n", filerespow);
                   2765:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2766:   }
                   2767:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2768:   for (i=1;i<=nlstate;i++)
                   2769:     for(j=1;j<=nlstate+ndeath;j++)
                   2770:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2771:   fprintf(ficrespow,"\n");
1.162     brouard  2772: #ifdef POWELL
1.126     brouard  2773:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2774: #endif
1.126     brouard  2775: 
1.162     brouard  2776: #ifdef NLOPT
                   2777: #ifdef NEWUOA
                   2778:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2779: #else
                   2780:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2781: #endif
                   2782:   lb=vector(0,npar-1);
                   2783:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2784:   nlopt_set_lower_bounds(opt, lb);
                   2785:   nlopt_set_initial_step1(opt, 0.1);
                   2786:   
                   2787:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2788:   d->function = func;
                   2789:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2790:   nlopt_set_min_objective(opt, myfunc, d);
                   2791:   nlopt_set_xtol_rel(opt, ftol);
                   2792:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2793:     printf("nlopt failed! %d\n",creturn); 
                   2794:   }
                   2795:   else {
                   2796:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2797:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2798:     iter=1; /* not equal */
                   2799:   }
                   2800:   nlopt_destroy(opt);
                   2801: #endif
1.126     brouard  2802:   free_matrix(xi,1,npar,1,npar);
                   2803:   fclose(ficrespow);
1.203     brouard  2804:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2805:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2806:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2807: 
                   2808: }
                   2809: 
                   2810: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2811: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2812: {
                   2813:   double  **a,**y,*x,pd;
1.203     brouard  2814:   /* double **hess; */
1.164     brouard  2815:   int i, j;
1.126     brouard  2816:   int *indx;
                   2817: 
                   2818:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2819:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2820:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2821:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2822:   double gompertz(double p[]);
1.203     brouard  2823:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2824: 
                   2825:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2826:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2827:   for (i=1;i<=npar;i++){
1.203     brouard  2828:     printf("%d-",i);fflush(stdout);
                   2829:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2830:    
                   2831:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2832:     
                   2833:     /*  printf(" %f ",p[i]);
                   2834:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2835:   }
                   2836:   
                   2837:   for (i=1;i<=npar;i++) {
                   2838:     for (j=1;j<=npar;j++)  {
                   2839:       if (j>i) { 
1.203     brouard  2840:        printf(".%d-%d",i,j);fflush(stdout);
                   2841:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2842:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2843:        
                   2844:        hess[j][i]=hess[i][j];    
                   2845:        /*printf(" %lf ",hess[i][j]);*/
                   2846:       }
                   2847:     }
                   2848:   }
                   2849:   printf("\n");
                   2850:   fprintf(ficlog,"\n");
                   2851: 
                   2852:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2853:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2854:   
                   2855:   a=matrix(1,npar,1,npar);
                   2856:   y=matrix(1,npar,1,npar);
                   2857:   x=vector(1,npar);
                   2858:   indx=ivector(1,npar);
                   2859:   for (i=1;i<=npar;i++)
                   2860:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2861:   ludcmp(a,npar,indx,&pd);
                   2862: 
                   2863:   for (j=1;j<=npar;j++) {
                   2864:     for (i=1;i<=npar;i++) x[i]=0;
                   2865:     x[j]=1;
                   2866:     lubksb(a,npar,indx,x);
                   2867:     for (i=1;i<=npar;i++){ 
                   2868:       matcov[i][j]=x[i];
                   2869:     }
                   2870:   }
                   2871: 
                   2872:   printf("\n#Hessian matrix#\n");
                   2873:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2874:   for (i=1;i<=npar;i++) { 
                   2875:     for (j=1;j<=npar;j++) { 
1.203     brouard  2876:       printf("%.6e ",hess[i][j]);
                   2877:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2878:     }
                   2879:     printf("\n");
                   2880:     fprintf(ficlog,"\n");
                   2881:   }
                   2882: 
1.203     brouard  2883:   /* printf("\n#Covariance matrix#\n"); */
                   2884:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2885:   /* for (i=1;i<=npar;i++) {  */
                   2886:   /*   for (j=1;j<=npar;j++) {  */
                   2887:   /*     printf("%.6e ",matcov[i][j]); */
                   2888:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2889:   /*   } */
                   2890:   /*   printf("\n"); */
                   2891:   /*   fprintf(ficlog,"\n"); */
                   2892:   /* } */
                   2893: 
1.126     brouard  2894:   /* Recompute Inverse */
1.203     brouard  2895:   /* for (i=1;i<=npar;i++) */
                   2896:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2897:   /* ludcmp(a,npar,indx,&pd); */
                   2898: 
                   2899:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2900: 
                   2901:   /* for (j=1;j<=npar;j++) { */
                   2902:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2903:   /*   x[j]=1; */
                   2904:   /*   lubksb(a,npar,indx,x); */
                   2905:   /*   for (i=1;i<=npar;i++){  */
                   2906:   /*     y[i][j]=x[i]; */
                   2907:   /*     printf("%.3e ",y[i][j]); */
                   2908:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2909:   /*   } */
                   2910:   /*   printf("\n"); */
                   2911:   /*   fprintf(ficlog,"\n"); */
                   2912:   /* } */
                   2913: 
                   2914:   /* Verifying the inverse matrix */
                   2915: #ifdef DEBUGHESS
                   2916:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2917: 
1.203     brouard  2918:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2919:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2920: 
                   2921:   for (j=1;j<=npar;j++) {
                   2922:     for (i=1;i<=npar;i++){ 
1.203     brouard  2923:       printf("%.2f ",y[i][j]);
                   2924:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2925:     }
                   2926:     printf("\n");
                   2927:     fprintf(ficlog,"\n");
                   2928:   }
1.203     brouard  2929: #endif
1.126     brouard  2930: 
                   2931:   free_matrix(a,1,npar,1,npar);
                   2932:   free_matrix(y,1,npar,1,npar);
                   2933:   free_vector(x,1,npar);
                   2934:   free_ivector(indx,1,npar);
1.203     brouard  2935:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2936: 
                   2937: 
                   2938: }
                   2939: 
                   2940: /*************** hessian matrix ****************/
                   2941: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2942: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2943:   int i;
                   2944:   int l=1, lmax=20;
1.203     brouard  2945:   double k1,k2, res, fx;
1.132     brouard  2946:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2947:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2948:   int k=0,kmax=10;
                   2949:   double l1;
                   2950: 
                   2951:   fx=func(x);
                   2952:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2953:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2954:     l1=pow(10,l);
                   2955:     delts=delt;
                   2956:     for(k=1 ; k <kmax; k=k+1){
                   2957:       delt = delta*(l1*k);
                   2958:       p2[theta]=x[theta] +delt;
1.145     brouard  2959:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2960:       p2[theta]=x[theta]-delt;
                   2961:       k2=func(p2)-fx;
                   2962:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  2963:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2964:       
1.203     brouard  2965: #ifdef DEBUGHESSII
1.126     brouard  2966:       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);
                   2967:       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);
                   2968: #endif
                   2969:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2970:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2971:        k=kmax;
                   2972:       }
                   2973:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2974:        k=kmax; l=lmax*10;
1.126     brouard  2975:       }
                   2976:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2977:        delts=delt;
                   2978:       }
1.203     brouard  2979:     } /* End loop k */
1.126     brouard  2980:   }
                   2981:   delti[theta]=delts;
                   2982:   return res; 
                   2983:   
                   2984: }
                   2985: 
1.203     brouard  2986: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2987: {
                   2988:   int i;
1.164     brouard  2989:   int l=1, lmax=20;
1.126     brouard  2990:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2991:   double p2[MAXPARM+1];
1.203     brouard  2992:   int k, kmax=1;
                   2993:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  2994: 
                   2995:   int firstime=0;
1.203     brouard  2996:   
1.126     brouard  2997:   fx=func(x);
1.203     brouard  2998:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  2999:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3000:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3001:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3002:     k1=func(p2)-fx;
                   3003:   
1.203     brouard  3004:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3005:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3006:     k2=func(p2)-fx;
                   3007:   
1.203     brouard  3008:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3009:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3010:     k3=func(p2)-fx;
                   3011:   
1.203     brouard  3012:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3013:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3014:     k4=func(p2)-fx;
1.203     brouard  3015:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3016:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3017:       firstime=1;
1.203     brouard  3018:       kmax=kmax+10;
1.208     brouard  3019:     }
                   3020:     if(kmax >=10 || firstime ==1){
1.203     brouard  3021:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3022:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3023:       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);
                   3024:       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);
                   3025:     }
                   3026: #ifdef DEBUGHESSIJ
                   3027:     v1=hess[thetai][thetai];
                   3028:     v2=hess[thetaj][thetaj];
                   3029:     cv12=res;
                   3030:     /* Computing eigen value of Hessian matrix */
                   3031:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3032:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3033:     if ((lc2 <0) || (lc1 <0) ){
                   3034:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3035:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3036:       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);
                   3037:       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);
                   3038:     }
1.126     brouard  3039: #endif
                   3040:   }
                   3041:   return res;
                   3042: }
                   3043: 
1.203     brouard  3044:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3045: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3046: /* { */
                   3047: /*   int i; */
                   3048: /*   int l=1, lmax=20; */
                   3049: /*   double k1,k2,k3,k4,res,fx; */
                   3050: /*   double p2[MAXPARM+1]; */
                   3051: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3052: /*   int k=0,kmax=10; */
                   3053: /*   double l1; */
                   3054:   
                   3055: /*   fx=func(x); */
                   3056: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3057: /*     l1=pow(10,l); */
                   3058: /*     delts=delt; */
                   3059: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3060: /*       delt = delti*(l1*k); */
                   3061: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3062: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3063: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3064: /*       k1=func(p2)-fx; */
                   3065:       
                   3066: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3067: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3068: /*       k2=func(p2)-fx; */
                   3069:       
                   3070: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3071: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3072: /*       k3=func(p2)-fx; */
                   3073:       
                   3074: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3075: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3076: /*       k4=func(p2)-fx; */
                   3077: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3078: /* #ifdef DEBUGHESSIJ */
                   3079: /*       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); */
                   3080: /*       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); */
                   3081: /* #endif */
                   3082: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3083: /*     k=kmax; */
                   3084: /*       } */
                   3085: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3086: /*     k=kmax; l=lmax*10; */
                   3087: /*       } */
                   3088: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3089: /*     delts=delt; */
                   3090: /*       } */
                   3091: /*     } /\* End loop k *\/ */
                   3092: /*   } */
                   3093: /*   delti[theta]=delts; */
                   3094: /*   return res;  */
                   3095: /* } */
                   3096: 
                   3097: 
1.126     brouard  3098: /************** Inverse of matrix **************/
                   3099: void ludcmp(double **a, int n, int *indx, double *d) 
                   3100: { 
                   3101:   int i,imax,j,k; 
                   3102:   double big,dum,sum,temp; 
                   3103:   double *vv; 
                   3104:  
                   3105:   vv=vector(1,n); 
                   3106:   *d=1.0; 
                   3107:   for (i=1;i<=n;i++) { 
                   3108:     big=0.0; 
                   3109:     for (j=1;j<=n;j++) 
                   3110:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3111:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3112:     vv[i]=1.0/big; 
                   3113:   } 
                   3114:   for (j=1;j<=n;j++) { 
                   3115:     for (i=1;i<j;i++) { 
                   3116:       sum=a[i][j]; 
                   3117:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3118:       a[i][j]=sum; 
                   3119:     } 
                   3120:     big=0.0; 
                   3121:     for (i=j;i<=n;i++) { 
                   3122:       sum=a[i][j]; 
                   3123:       for (k=1;k<j;k++) 
                   3124:        sum -= a[i][k]*a[k][j]; 
                   3125:       a[i][j]=sum; 
                   3126:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3127:        big=dum; 
                   3128:        imax=i; 
                   3129:       } 
                   3130:     } 
                   3131:     if (j != imax) { 
                   3132:       for (k=1;k<=n;k++) { 
                   3133:        dum=a[imax][k]; 
                   3134:        a[imax][k]=a[j][k]; 
                   3135:        a[j][k]=dum; 
                   3136:       } 
                   3137:       *d = -(*d); 
                   3138:       vv[imax]=vv[j]; 
                   3139:     } 
                   3140:     indx[j]=imax; 
                   3141:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3142:     if (j != n) { 
                   3143:       dum=1.0/(a[j][j]); 
                   3144:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3145:     } 
                   3146:   } 
                   3147:   free_vector(vv,1,n);  /* Doesn't work */
                   3148: ;
                   3149: } 
                   3150: 
                   3151: void lubksb(double **a, int n, int *indx, double b[]) 
                   3152: { 
                   3153:   int i,ii=0,ip,j; 
                   3154:   double sum; 
                   3155:  
                   3156:   for (i=1;i<=n;i++) { 
                   3157:     ip=indx[i]; 
                   3158:     sum=b[ip]; 
                   3159:     b[ip]=b[i]; 
                   3160:     if (ii) 
                   3161:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3162:     else if (sum) ii=i; 
                   3163:     b[i]=sum; 
                   3164:   } 
                   3165:   for (i=n;i>=1;i--) { 
                   3166:     sum=b[i]; 
                   3167:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3168:     b[i]=sum/a[i][i]; 
                   3169:   } 
                   3170: } 
                   3171: 
                   3172: void pstamp(FILE *fichier)
                   3173: {
1.196     brouard  3174:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3175: }
                   3176: 
                   3177: /************ Frequencies ********************/
                   3178: 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[])
                   3179: {  /* Some frequencies */
                   3180:   
1.164     brouard  3181:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3182:   int first;
                   3183:   double ***freq; /* Frequencies */
                   3184:   double *pp, **prop;
                   3185:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3186:   char fileresp[FILENAMELENGTH];
                   3187:   
                   3188:   pp=vector(1,nlstate);
                   3189:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3190:   strcpy(fileresp,"P_");
                   3191:   strcat(fileresp,fileresu);
1.126     brouard  3192:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3193:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3194:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3195:     exit(0);
                   3196:   }
                   3197:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3198:   j1=0;
                   3199:   
                   3200:   j=cptcoveff;
                   3201:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3202: 
                   3203:   first=1;
                   3204: 
1.169     brouard  3205:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3206:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3207:   /*    j1++; */
1.145     brouard  3208:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3209:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3210:        scanf("%d", i);*/
                   3211:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3212:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3213:          for(m=iagemin; m <= iagemax+3; m++)
                   3214:            freq[i][jk][m]=0;
1.143     brouard  3215:       
                   3216:       for (i=1; i<=nlstate; i++)  
                   3217:        for(m=iagemin; m <= iagemax+3; m++)
                   3218:          prop[i][m]=0;
1.126     brouard  3219:       
                   3220:       dateintsum=0;
                   3221:       k2cpt=0;
                   3222:       for (i=1; i<=imx; i++) {
                   3223:        bool=1;
1.210   ! brouard  3224:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3225:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3226:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3227:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3228:               bool=0;
1.198     brouard  3229:               /* 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", 
                   3230:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3231:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3232:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3233:             } 
1.210   ! brouard  3234:        } /* cptcovn > 0 */
1.144     brouard  3235:  
1.126     brouard  3236:        if (bool==1){
                   3237:          for(m=firstpass; m<=lastpass; m++){
                   3238:            k2=anint[m][i]+(mint[m][i]/12.);
                   3239:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3240:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3241:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3242:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3243:              if (m<lastpass) {
                   3244:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3245:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3246:              }
                   3247:              
1.210   ! brouard  3248:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
1.126     brouard  3249:                dateintsum=dateintsum+k2;
                   3250:                k2cpt++;
1.210   ! brouard  3251:                /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.126     brouard  3252:              }
                   3253:              /*}*/
1.210   ! brouard  3254:          } /* end m */
        !          3255:        } /* end bool */
        !          3256:       } /* end i = 1 to imx */
1.126     brouard  3257:        
                   3258:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3259:       pstamp(ficresp);
                   3260:       if  (cptcovn>0) {
                   3261:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3262:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3263:        fprintf(ficresp, "**********\n#");
1.143     brouard  3264:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3265:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3266:        fprintf(ficlog, "**********\n#");
1.126     brouard  3267:       }
                   3268:       for(i=1; i<=nlstate;i++) 
                   3269:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3270:       fprintf(ficresp, "\n");
                   3271:       
                   3272:       for(i=iagemin; i <= iagemax+3; i++){
                   3273:        if(i==iagemax+3){
                   3274:          fprintf(ficlog,"Total");
                   3275:        }else{
                   3276:          if(first==1){
                   3277:            first=0;
                   3278:            printf("See log file for details...\n");
                   3279:          }
                   3280:          fprintf(ficlog,"Age %d", i);
                   3281:        }
                   3282:        for(jk=1; jk <=nlstate ; jk++){
                   3283:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3284:            pp[jk] += freq[jk][m][i]; 
                   3285:        }
                   3286:        for(jk=1; jk <=nlstate ; jk++){
                   3287:          for(m=-1, pos=0; m <=0 ; m++)
                   3288:            pos += freq[jk][m][i];
                   3289:          if(pp[jk]>=1.e-10){
                   3290:            if(first==1){
1.132     brouard  3291:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3292:            }
                   3293:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3294:          }else{
                   3295:            if(first==1)
                   3296:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3297:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3298:          }
                   3299:        }
                   3300: 
                   3301:        for(jk=1; jk <=nlstate ; jk++){
                   3302:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3303:            pp[jk] += freq[jk][m][i];
                   3304:        }       
                   3305:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3306:          pos += pp[jk];
                   3307:          posprop += prop[jk][i];
                   3308:        }
                   3309:        for(jk=1; jk <=nlstate ; jk++){
                   3310:          if(pos>=1.e-5){
                   3311:            if(first==1)
                   3312:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3313:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3314:          }else{
                   3315:            if(first==1)
                   3316:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3317:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3318:          }
                   3319:          if( i <= iagemax){
                   3320:            if(pos>=1.e-5){
                   3321:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3322:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3323:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3324:            }
                   3325:            else
                   3326:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3327:          }
                   3328:        }
                   3329:        
                   3330:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3331:          for(m=-1; m <=nlstate+ndeath; m++)
                   3332:            if(freq[jk][m][i] !=0 ) {
                   3333:            if(first==1)
                   3334:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3335:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3336:            }
                   3337:        if(i <= iagemax)
                   3338:          fprintf(ficresp,"\n");
                   3339:        if(first==1)
                   3340:          printf("Others in log...\n");
                   3341:        fprintf(ficlog,"\n");
1.210   ! brouard  3342:       } /* end loop i */
1.145     brouard  3343:       /*}*/
1.210   ! brouard  3344:   } /* end j1 */
1.126     brouard  3345:   dateintmean=dateintsum/k2cpt; 
                   3346:  
                   3347:   fclose(ficresp);
                   3348:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3349:   free_vector(pp,1,nlstate);
                   3350:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3351:   /* End of Freq */
                   3352: }
                   3353: 
                   3354: /************ Prevalence ********************/
                   3355: 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)
                   3356: {  
                   3357:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3358:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3359:      We still use firstpass and lastpass as another selection.
                   3360:   */
                   3361:  
1.164     brouard  3362:   int i, m, jk, j1, bool, z1,j;
                   3363: 
                   3364:   double **prop;
                   3365:   double posprop; 
1.126     brouard  3366:   double  y2; /* in fractional years */
                   3367:   int iagemin, iagemax;
1.145     brouard  3368:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3369: 
                   3370:   iagemin= (int) agemin;
                   3371:   iagemax= (int) agemax;
                   3372:   /*pp=vector(1,nlstate);*/
                   3373:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3374:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3375:   j1=0;
                   3376:   
1.145     brouard  3377:   /*j=cptcoveff;*/
1.126     brouard  3378:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3379:   
1.145     brouard  3380:   first=1;
                   3381:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3382:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3383:       j1++;*/
1.126     brouard  3384:       
                   3385:       for (i=1; i<=nlstate; i++)  
                   3386:        for(m=iagemin; m <= iagemax+3; m++)
                   3387:          prop[i][m]=0.0;
                   3388:      
                   3389:       for (i=1; i<=imx; i++) { /* Each individual */
                   3390:        bool=1;
                   3391:        if  (cptcovn>0) {
                   3392:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3393:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3394:              bool=0;
                   3395:        } 
                   3396:        if (bool==1) { 
                   3397:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3398:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3399:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3400:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3401:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3402:              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); 
                   3403:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3404:                /*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]]);*/
                   3405:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3406:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3407:              } 
                   3408:            }
                   3409:          } /* end selection of waves */
                   3410:        }
                   3411:       }
                   3412:       for(i=iagemin; i <= iagemax+3; i++){  
                   3413:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3414:          posprop += prop[jk][i]; 
                   3415:        } 
1.145     brouard  3416:        
1.126     brouard  3417:        for(jk=1; jk <=nlstate ; jk++){     
                   3418:          if( i <=  iagemax){ 
                   3419:            if(posprop>=1.e-5){ 
                   3420:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3421:            } else{
                   3422:              if(first==1){
                   3423:                first=0;
                   3424:                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]);
                   3425:              }
                   3426:            }
1.126     brouard  3427:          } 
                   3428:        }/* end jk */ 
                   3429:       }/* end i */ 
1.145     brouard  3430:     /*} *//* end i1 */
                   3431:   } /* end j1 */
1.126     brouard  3432:   
                   3433:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3434:   /*free_vector(pp,1,nlstate);*/
                   3435:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3436: }  /* End of prevalence */
                   3437: 
                   3438: /************* Waves Concatenation ***************/
                   3439: 
                   3440: 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)
                   3441: {
                   3442:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3443:      Death is a valid wave (if date is known).
                   3444:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3445:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3446:      and mw[mi+1][i]. dh depends on stepm.
                   3447:      */
                   3448: 
                   3449:   int i, mi, m;
                   3450:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3451:      double sum=0., jmean=0.;*/
                   3452:   int first;
                   3453:   int j, k=0,jk, ju, jl;
                   3454:   double sum=0.;
                   3455:   first=0;
1.164     brouard  3456:   jmin=100000;
1.126     brouard  3457:   jmax=-1;
                   3458:   jmean=0.;
                   3459:   for(i=1; i<=imx; i++){
                   3460:     mi=0;
                   3461:     m=firstpass;
                   3462:     while(s[m][i] <= nlstate){
                   3463:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3464:        mw[++mi][i]=m;
                   3465:       if(m >=lastpass)
                   3466:        break;
                   3467:       else
                   3468:        m++;
                   3469:     }/* end while */
                   3470:     if (s[m][i] > nlstate){
                   3471:       mi++;    /* Death is another wave */
                   3472:       /* if(mi==0)  never been interviewed correctly before death */
                   3473:         /* Only death is a correct wave */
                   3474:       mw[mi][i]=m;
                   3475:     }
                   3476: 
                   3477:     wav[i]=mi;
                   3478:     if(mi==0){
                   3479:       nbwarn++;
                   3480:       if(first==0){
                   3481:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3482:        first=1;
                   3483:       }
                   3484:       if(first==1){
                   3485:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3486:       }
                   3487:     } /* end mi==0 */
                   3488:   } /* End individuals */
                   3489: 
                   3490:   for(i=1; i<=imx; i++){
                   3491:     for(mi=1; mi<wav[i];mi++){
                   3492:       if (stepm <=0)
                   3493:        dh[mi][i]=1;
                   3494:       else{
                   3495:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3496:          if (agedc[i] < 2*AGESUP) {
                   3497:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3498:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3499:            else if(j<0){
                   3500:              nberr++;
                   3501:              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]);
                   3502:              j=1; /* Temporary Dangerous patch */
                   3503:              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);
                   3504:              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]);
                   3505:              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);
                   3506:            }
                   3507:            k=k+1;
                   3508:            if (j >= jmax){
                   3509:              jmax=j;
                   3510:              ijmax=i;
                   3511:            }
                   3512:            if (j <= jmin){
                   3513:              jmin=j;
                   3514:              ijmin=i;
                   3515:            }
                   3516:            sum=sum+j;
                   3517:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3518:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3519:          }
                   3520:        }
                   3521:        else{
                   3522:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3523: /*       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]); */
                   3524: 
                   3525:          k=k+1;
                   3526:          if (j >= jmax) {
                   3527:            jmax=j;
                   3528:            ijmax=i;
                   3529:          }
                   3530:          else if (j <= jmin){
                   3531:            jmin=j;
                   3532:            ijmin=i;
                   3533:          }
                   3534:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3535:          /*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]);*/
                   3536:          if(j<0){
                   3537:            nberr++;
                   3538:            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]);
                   3539:            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]);
                   3540:          }
                   3541:          sum=sum+j;
                   3542:        }
                   3543:        jk= j/stepm;
                   3544:        jl= j -jk*stepm;
                   3545:        ju= j -(jk+1)*stepm;
                   3546:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3547:          if(jl==0){
                   3548:            dh[mi][i]=jk;
                   3549:            bh[mi][i]=0;
                   3550:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3551:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3552:            dh[mi][i]=jk+1;
                   3553:            bh[mi][i]=ju;
                   3554:          }
                   3555:        }else{
                   3556:          if(jl <= -ju){
                   3557:            dh[mi][i]=jk;
                   3558:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3559:                                 * is higher than the multiple of stepm and negative otherwise.
                   3560:                                 */
                   3561:          }
                   3562:          else{
                   3563:            dh[mi][i]=jk+1;
                   3564:            bh[mi][i]=ju;
                   3565:          }
                   3566:          if(dh[mi][i]==0){
                   3567:            dh[mi][i]=1; /* At least one step */
                   3568:            bh[mi][i]=ju; /* At least one step */
                   3569:            /*  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);*/
                   3570:          }
                   3571:        } /* end if mle */
                   3572:       }
                   3573:     } /* end wave */
                   3574:   }
                   3575:   jmean=sum/k;
                   3576:   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  3577:   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  3578:  }
                   3579: 
                   3580: /*********** Tricode ****************************/
1.145     brouard  3581: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3582: {
1.144     brouard  3583:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3584:   /*     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  3585:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3586:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3587:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3588:   */
1.130     brouard  3589: 
1.145     brouard  3590:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3591:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3592:   int cptcode=0; /* Modality max of covariates j */
                   3593:   int modmincovj=0; /* Modality min of covariates j */
                   3594: 
                   3595: 
1.126     brouard  3596:   cptcoveff=0; 
                   3597:  
1.144     brouard  3598:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3599: 
1.145     brouard  3600:   /* Loop on covariates without age and products */
1.186     brouard  3601:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3602:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3603:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3604:                               modality of this covariate Vj*/ 
1.145     brouard  3605:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3606:                                    * If product of Vn*Vm, still boolean *:
                   3607:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3608:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3609:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3610:                                      modality of the nth covariate of individual i. */
1.145     brouard  3611:       if (ij > modmaxcovj)
                   3612:         modmaxcovj=ij; 
                   3613:       else if (ij < modmincovj) 
                   3614:        modmincovj=ij; 
                   3615:       if ((ij < -1) && (ij > NCOVMAX)){
                   3616:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3617:        exit(1);
                   3618:       }else
1.136     brouard  3619:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3620:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3621:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3622:       /* getting the maximum value of the modality of the covariate
                   3623:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3624:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3625:     } /* end for loop on individuals i */
1.145     brouard  3626:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3627:     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  3628:     cptcode=modmaxcovj;
1.137     brouard  3629:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3630:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3631:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3632:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3633:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3634:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3635:        if( k != -1){
                   3636:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3637:                             covariate for which somebody answered excluding 
                   3638:                             undefined. Usually 2: 0 and 1. */
                   3639:        }
                   3640:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3641:                             covariate for which somebody answered including 
                   3642:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3643:       }
                   3644:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3645:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3646:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3647: 
1.136     brouard  3648:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3649:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3650:        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  3651:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3652:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3653:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3654:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3655:        nbcode[Tvar[j]][ij]=k;
                   3656:        nbcode[Tvar[j]][1]=0;
                   3657:        nbcode[Tvar[j]][2]=1;
                   3658:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3659:        To be continued (not working yet).
1.145     brouard  3660:     */
1.197     brouard  3661:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3662:     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*/
                   3663:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3664:          break;
                   3665:        }
                   3666:        ij++;
1.197     brouard  3667:        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  3668:        cptcode = ij; /* New max modality for covar j */
                   3669:     } /* end of loop on modality i=-1 to 1 or more */
                   3670:       
                   3671:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3672:     /*         /\*recode from 0 *\/ */
                   3673:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3674:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3675:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3676:     /*         } */
                   3677:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3678:     /*         if (ij > ncodemax[j]) { */
                   3679:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3680:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3681:     /*           break; */
                   3682:     /*         } */
                   3683:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3684:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3685:   
1.145     brouard  3686:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3687:   
1.187     brouard  3688:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3689:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3690:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3691:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3692:  } 
1.126     brouard  3693: 
1.192     brouard  3694:  ij=0;
1.145     brouard  3695:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3696:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3697:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3698:      ij++;
1.145     brouard  3699:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3700:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3701:    }else{
                   3702:        /* Tvaraff[ij]=0; */
                   3703:    }
1.126     brouard  3704:  }
1.192     brouard  3705:  /* ij--; */
1.144     brouard  3706:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3707: 
1.126     brouard  3708: }
                   3709: 
1.145     brouard  3710: 
1.126     brouard  3711: /*********** Health Expectancies ****************/
                   3712: 
1.127     brouard  3713: 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  3714: 
                   3715: {
                   3716:   /* Health expectancies, no variances */
1.164     brouard  3717:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3718:   int nhstepma, nstepma; /* Decreasing with age */
                   3719:   double age, agelim, hf;
                   3720:   double ***p3mat;
                   3721:   double eip;
                   3722: 
                   3723:   pstamp(ficreseij);
                   3724:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3725:   fprintf(ficreseij,"# Age");
                   3726:   for(i=1; i<=nlstate;i++){
                   3727:     for(j=1; j<=nlstate;j++){
                   3728:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3729:     }
                   3730:     fprintf(ficreseij," e%1d. ",i);
                   3731:   }
                   3732:   fprintf(ficreseij,"\n");
                   3733: 
                   3734:   
                   3735:   if(estepm < stepm){
                   3736:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3737:   }
                   3738:   else  hstepm=estepm;   
                   3739:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3740:    * This is mainly to measure the difference between two models: for example
                   3741:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3742:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3743:    * progression in between and thus overestimating or underestimating according
                   3744:    * to the curvature of the survival function. If, for the same date, we 
                   3745:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3746:    * to compare the new estimate of Life expectancy with the same linear 
                   3747:    * hypothesis. A more precise result, taking into account a more precise
                   3748:    * curvature will be obtained if estepm is as small as stepm. */
                   3749: 
                   3750:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3751:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3752:      nhstepm is the number of hstepm from age to agelim 
                   3753:      nstepm is the number of stepm from age to agelin. 
                   3754:      Look at hpijx to understand the reason of that which relies in memory size
                   3755:      and note for a fixed period like estepm months */
                   3756:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3757:      survival function given by stepm (the optimization length). Unfortunately it
                   3758:      means that if the survival funtion is printed only each two years of age and if
                   3759:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3760:      results. So we changed our mind and took the option of the best precision.
                   3761:   */
                   3762:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3763: 
                   3764:   agelim=AGESUP;
                   3765:   /* If stepm=6 months */
                   3766:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3767:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3768:     
                   3769: /* nhstepm age range expressed in number of stepm */
                   3770:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3771:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3772:   /* if (stepm >= YEARM) hstepm=1;*/
                   3773:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3774:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3775: 
                   3776:   for (age=bage; age<=fage; age ++){ 
                   3777:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3778:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3779:     /* if (stepm >= YEARM) hstepm=1;*/
                   3780:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3781: 
                   3782:     /* If stepm=6 months */
                   3783:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3784:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3785:     
                   3786:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3787:     
                   3788:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3789:     
                   3790:     printf("%d|",(int)age);fflush(stdout);
                   3791:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3792:     
                   3793:     /* Computing expectancies */
                   3794:     for(i=1; i<=nlstate;i++)
                   3795:       for(j=1; j<=nlstate;j++)
                   3796:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3797:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3798:          
                   3799:          /* 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]);*/
                   3800: 
                   3801:        }
                   3802: 
                   3803:     fprintf(ficreseij,"%3.0f",age );
                   3804:     for(i=1; i<=nlstate;i++){
                   3805:       eip=0;
                   3806:       for(j=1; j<=nlstate;j++){
                   3807:        eip +=eij[i][j][(int)age];
                   3808:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3809:       }
                   3810:       fprintf(ficreseij,"%9.4f", eip );
                   3811:     }
                   3812:     fprintf(ficreseij,"\n");
                   3813:     
                   3814:   }
                   3815:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3816:   printf("\n");
                   3817:   fprintf(ficlog,"\n");
                   3818:   
                   3819: }
                   3820: 
1.127     brouard  3821: 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  3822: 
                   3823: {
                   3824:   /* Covariances of health expectancies eij and of total life expectancies according
                   3825:    to initial status i, ei. .
                   3826:   */
                   3827:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3828:   int nhstepma, nstepma; /* Decreasing with age */
                   3829:   double age, agelim, hf;
                   3830:   double ***p3matp, ***p3matm, ***varhe;
                   3831:   double **dnewm,**doldm;
                   3832:   double *xp, *xm;
                   3833:   double **gp, **gm;
                   3834:   double ***gradg, ***trgradg;
                   3835:   int theta;
                   3836: 
                   3837:   double eip, vip;
                   3838: 
                   3839:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3840:   xp=vector(1,npar);
                   3841:   xm=vector(1,npar);
                   3842:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3843:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3844:   
                   3845:   pstamp(ficresstdeij);
                   3846:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3847:   fprintf(ficresstdeij,"# Age");
                   3848:   for(i=1; i<=nlstate;i++){
                   3849:     for(j=1; j<=nlstate;j++)
                   3850:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3851:     fprintf(ficresstdeij," e%1d. ",i);
                   3852:   }
                   3853:   fprintf(ficresstdeij,"\n");
                   3854: 
                   3855:   pstamp(ficrescveij);
                   3856:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3857:   fprintf(ficrescveij,"# Age");
                   3858:   for(i=1; i<=nlstate;i++)
                   3859:     for(j=1; j<=nlstate;j++){
                   3860:       cptj= (j-1)*nlstate+i;
                   3861:       for(i2=1; i2<=nlstate;i2++)
                   3862:        for(j2=1; j2<=nlstate;j2++){
                   3863:          cptj2= (j2-1)*nlstate+i2;
                   3864:          if(cptj2 <= cptj)
                   3865:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3866:        }
                   3867:     }
                   3868:   fprintf(ficrescveij,"\n");
                   3869:   
                   3870:   if(estepm < stepm){
                   3871:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3872:   }
                   3873:   else  hstepm=estepm;   
                   3874:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3875:    * This is mainly to measure the difference between two models: for example
                   3876:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3877:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3878:    * progression in between and thus overestimating or underestimating according
                   3879:    * to the curvature of the survival function. If, for the same date, we 
                   3880:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3881:    * to compare the new estimate of Life expectancy with the same linear 
                   3882:    * hypothesis. A more precise result, taking into account a more precise
                   3883:    * curvature will be obtained if estepm is as small as stepm. */
                   3884: 
                   3885:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3886:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3887:      nhstepm is the number of hstepm from age to agelim 
                   3888:      nstepm is the number of stepm from age to agelin. 
                   3889:      Look at hpijx to understand the reason of that which relies in memory size
                   3890:      and note for a fixed period like estepm months */
                   3891:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3892:      survival function given by stepm (the optimization length). Unfortunately it
                   3893:      means that if the survival funtion is printed only each two years of age and if
                   3894:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3895:      results. So we changed our mind and took the option of the best precision.
                   3896:   */
                   3897:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3898: 
                   3899:   /* If stepm=6 months */
                   3900:   /* nhstepm age range expressed in number of stepm */
                   3901:   agelim=AGESUP;
                   3902:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3903:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3904:   /* if (stepm >= YEARM) hstepm=1;*/
                   3905:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3906:   
                   3907:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3908:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3909:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3910:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3911:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3912:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3913: 
                   3914:   for (age=bage; age<=fage; age ++){ 
                   3915:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3916:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3917:     /* if (stepm >= YEARM) hstepm=1;*/
                   3918:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3919: 
                   3920:     /* If stepm=6 months */
                   3921:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3922:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3923:     
                   3924:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3925: 
                   3926:     /* Computing  Variances of health expectancies */
                   3927:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3928:        decrease memory allocation */
                   3929:     for(theta=1; theta <=npar; theta++){
                   3930:       for(i=1; i<=npar; i++){ 
                   3931:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3932:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3933:       }
                   3934:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3935:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3936:   
                   3937:       for(j=1; j<= nlstate; j++){
                   3938:        for(i=1; i<=nlstate; i++){
                   3939:          for(h=0; h<=nhstepm-1; h++){
                   3940:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3941:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3942:          }
                   3943:        }
                   3944:       }
                   3945:      
                   3946:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3947:        for(h=0; h<=nhstepm-1; h++){
                   3948:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3949:        }
                   3950:     }/* End theta */
                   3951:     
                   3952:     
                   3953:     for(h=0; h<=nhstepm-1; h++)
                   3954:       for(j=1; j<=nlstate*nlstate;j++)
                   3955:        for(theta=1; theta <=npar; theta++)
                   3956:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3957:     
                   3958: 
                   3959:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3960:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3961:        varhe[ij][ji][(int)age] =0.;
                   3962: 
                   3963:      printf("%d|",(int)age);fflush(stdout);
                   3964:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3965:      for(h=0;h<=nhstepm-1;h++){
                   3966:       for(k=0;k<=nhstepm-1;k++){
                   3967:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3968:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3969:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3970:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3971:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3972:       }
                   3973:     }
                   3974: 
                   3975:     /* Computing expectancies */
                   3976:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3977:     for(i=1; i<=nlstate;i++)
                   3978:       for(j=1; j<=nlstate;j++)
                   3979:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3980:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3981:          
                   3982:          /* 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]);*/
                   3983: 
                   3984:        }
                   3985: 
                   3986:     fprintf(ficresstdeij,"%3.0f",age );
                   3987:     for(i=1; i<=nlstate;i++){
                   3988:       eip=0.;
                   3989:       vip=0.;
                   3990:       for(j=1; j<=nlstate;j++){
                   3991:        eip += eij[i][j][(int)age];
                   3992:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3993:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3994:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3995:       }
                   3996:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3997:     }
                   3998:     fprintf(ficresstdeij,"\n");
                   3999: 
                   4000:     fprintf(ficrescveij,"%3.0f",age );
                   4001:     for(i=1; i<=nlstate;i++)
                   4002:       for(j=1; j<=nlstate;j++){
                   4003:        cptj= (j-1)*nlstate+i;
                   4004:        for(i2=1; i2<=nlstate;i2++)
                   4005:          for(j2=1; j2<=nlstate;j2++){
                   4006:            cptj2= (j2-1)*nlstate+i2;
                   4007:            if(cptj2 <= cptj)
                   4008:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4009:          }
                   4010:       }
                   4011:     fprintf(ficrescveij,"\n");
                   4012:    
                   4013:   }
                   4014:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4015:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4016:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4017:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4018:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4019:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4020:   printf("\n");
                   4021:   fprintf(ficlog,"\n");
                   4022: 
                   4023:   free_vector(xm,1,npar);
                   4024:   free_vector(xp,1,npar);
                   4025:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4026:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4027:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4028: }
                   4029: 
                   4030: /************ Variance ******************/
1.209     brouard  4031:  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  4032: {
                   4033:   /* Variance of health expectancies */
                   4034:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4035:   /* double **newm;*/
1.169     brouard  4036:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4037:   
                   4038:   int movingaverage();
1.126     brouard  4039:   double **dnewm,**doldm;
                   4040:   double **dnewmp,**doldmp;
                   4041:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4042:   int k;
1.126     brouard  4043:   double *xp;
                   4044:   double **gp, **gm;  /* for var eij */
                   4045:   double ***gradg, ***trgradg; /*for var eij */
                   4046:   double **gradgp, **trgradgp; /* for var p point j */
                   4047:   double *gpp, *gmp; /* for var p point j */
                   4048:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4049:   double ***p3mat;
                   4050:   double age,agelim, hf;
                   4051:   double ***mobaverage;
                   4052:   int theta;
                   4053:   char digit[4];
                   4054:   char digitp[25];
                   4055: 
                   4056:   char fileresprobmorprev[FILENAMELENGTH];
                   4057: 
                   4058:   if(popbased==1){
                   4059:     if(mobilav!=0)
1.201     brouard  4060:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4061:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4062:   }
                   4063:   else 
1.201     brouard  4064:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4065: 
                   4066:   if (mobilav!=0) {
                   4067:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4068:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4069:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4070:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4071:     }
                   4072:   }
                   4073: 
1.201     brouard  4074:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4075:   sprintf(digit,"%-d",ij);
                   4076:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4077:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4078:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4079:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4080:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4081:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4082:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4083:   }
                   4084:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4085:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4086:   pstamp(ficresprobmorprev);
                   4087:   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);
                   4088:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4089:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4090:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4091:     for(i=1; i<=nlstate;i++)
                   4092:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4093:   }  
                   4094:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4095:   
1.126     brouard  4096:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4097:   fprintf(ficgp,"\nunset title \n");
                   4098: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4099:   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");
                   4100:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4101: /*   } */
                   4102:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4103:   pstamp(ficresvij);
                   4104:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4105:   if(popbased==1)
1.128     brouard  4106:     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  4107:   else
                   4108:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4109:   fprintf(ficresvij,"# Age");
                   4110:   for(i=1; i<=nlstate;i++)
                   4111:     for(j=1; j<=nlstate;j++)
                   4112:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4113:   fprintf(ficresvij,"\n");
                   4114: 
                   4115:   xp=vector(1,npar);
                   4116:   dnewm=matrix(1,nlstate,1,npar);
                   4117:   doldm=matrix(1,nlstate,1,nlstate);
                   4118:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4119:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4120: 
                   4121:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4122:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4123:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4124:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4125:   
                   4126:   if(estepm < stepm){
                   4127:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4128:   }
                   4129:   else  hstepm=estepm;   
                   4130:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4131:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4132:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4133:      nstepm is the number of stepm from age to agelim. 
1.209     brouard  4134:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4135:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4136:      survival function given by stepm (the optimization length). Unfortunately it
                   4137:      means that if the survival funtion is printed every two years of age and if
                   4138:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4139:      results. So we changed our mind and took the option of the best precision.
                   4140:   */
                   4141:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4142:   agelim = AGESUP;
                   4143:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4144:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4145:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4146:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4147:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4148:     gp=matrix(0,nhstepm,1,nlstate);
                   4149:     gm=matrix(0,nhstepm,1,nlstate);
                   4150: 
                   4151: 
                   4152:     for(theta=1; theta <=npar; theta++){
                   4153:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4154:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4155:       }
1.209     brouard  4156: 
                   4157:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4158: 
                   4159:       if (popbased==1) {
                   4160:        if(mobilav ==0){
                   4161:          for(i=1; i<=nlstate;i++)
                   4162:            prlim[i][i]=probs[(int)age][i][ij];
                   4163:        }else{ /* mobilav */ 
                   4164:          for(i=1; i<=nlstate;i++)
                   4165:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4166:        }
                   4167:       }
                   4168:   
1.209     brouard  4169:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4170:       for(j=1; j<= nlstate; j++){
                   4171:        for(h=0; h<=nhstepm; h++){
                   4172:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4173:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4174:        }
                   4175:       }
1.209     brouard  4176:       /* Next for computing probability of death (h=1 means
1.126     brouard  4177:          computed over hstepm matrices product = hstepm*stepm months) 
                   4178:          as a weighted average of prlim.
                   4179:       */
                   4180:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4181:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4182:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4183:       }    
                   4184:       /* end probability of death */
                   4185: 
                   4186:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4187:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4188: 
                   4189:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4190:  
                   4191:       if (popbased==1) {
                   4192:        if(mobilav ==0){
                   4193:          for(i=1; i<=nlstate;i++)
                   4194:            prlim[i][i]=probs[(int)age][i][ij];
                   4195:        }else{ /* mobilav */ 
                   4196:          for(i=1; i<=nlstate;i++)
                   4197:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4198:        }
                   4199:       }
                   4200: 
1.209     brouard  4201:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4202: 
1.128     brouard  4203:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4204:        for(h=0; h<=nhstepm; h++){
                   4205:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4206:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4207:        }
                   4208:       }
                   4209:       /* This for computing probability of death (h=1 means
                   4210:          computed over hstepm matrices product = hstepm*stepm months) 
                   4211:          as a weighted average of prlim.
                   4212:       */
                   4213:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4214:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4215:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4216:       }    
                   4217:       /* end probability of death */
                   4218: 
                   4219:       for(j=1; j<= nlstate; j++) /* vareij */
                   4220:        for(h=0; h<=nhstepm; h++){
                   4221:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4222:        }
                   4223: 
                   4224:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4225:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4226:       }
                   4227: 
                   4228:     } /* End theta */
                   4229: 
                   4230:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4231: 
                   4232:     for(h=0; h<=nhstepm; h++) /* veij */
                   4233:       for(j=1; j<=nlstate;j++)
                   4234:        for(theta=1; theta <=npar; theta++)
                   4235:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4236: 
                   4237:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4238:       for(theta=1; theta <=npar; theta++)
                   4239:        trgradgp[j][theta]=gradgp[theta][j];
                   4240:   
                   4241: 
                   4242:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4243:     for(i=1;i<=nlstate;i++)
                   4244:       for(j=1;j<=nlstate;j++)
                   4245:        vareij[i][j][(int)age] =0.;
                   4246: 
                   4247:     for(h=0;h<=nhstepm;h++){
                   4248:       for(k=0;k<=nhstepm;k++){
                   4249:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4250:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4251:        for(i=1;i<=nlstate;i++)
                   4252:          for(j=1;j<=nlstate;j++)
                   4253:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4254:       }
                   4255:     }
                   4256:   
                   4257:     /* pptj */
                   4258:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4259:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4260:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4261:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4262:        varppt[j][i]=doldmp[j][i];
                   4263:     /* end ppptj */
                   4264:     /*  x centered again */
1.209     brouard  4265: 
                   4266:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4267:  
                   4268:     if (popbased==1) {
                   4269:       if(mobilav ==0){
                   4270:        for(i=1; i<=nlstate;i++)
                   4271:          prlim[i][i]=probs[(int)age][i][ij];
                   4272:       }else{ /* mobilav */ 
                   4273:        for(i=1; i<=nlstate;i++)
                   4274:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4275:       }
                   4276:     }
                   4277:              
                   4278:     /* This for computing probability of death (h=1 means
                   4279:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4280:        as a weighted average of prlim.
                   4281:     */
1.209     brouard  4282:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4283:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4284:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4285:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4286:     }    
                   4287:     /* end probability of death */
                   4288: 
                   4289:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4290:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4291:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4292:       for(i=1; i<=nlstate;i++){
                   4293:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4294:       }
                   4295:     } 
                   4296:     fprintf(ficresprobmorprev,"\n");
                   4297: 
                   4298:     fprintf(ficresvij,"%.0f ",age );
                   4299:     for(i=1; i<=nlstate;i++)
                   4300:       for(j=1; j<=nlstate;j++){
                   4301:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4302:       }
                   4303:     fprintf(ficresvij,"\n");
                   4304:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4305:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4306:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4307:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4308:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4309:   } /* End age */
                   4310:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4311:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4312:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4313:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4314:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4315:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4316:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4317:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4318:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4319: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4320: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4321: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4322:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4323:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4324:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4325:   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  4326:   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  4327:   /*  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  4328: */
1.199     brouard  4329: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4330:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4331: 
                   4332:   free_vector(xp,1,npar);
                   4333:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4334:   free_matrix(dnewm,1,nlstate,1,npar);
                   4335:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4336:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4337:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4338:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4339:   fclose(ficresprobmorprev);
                   4340:   fflush(ficgp);
                   4341:   fflush(fichtm); 
                   4342: }  /* end varevsij */
                   4343: 
                   4344: /************ Variance of prevlim ******************/
1.209     brouard  4345:  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  4346: {
1.205     brouard  4347:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4348:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4349: 
1.126     brouard  4350:   double **dnewm,**doldm;
                   4351:   int i, j, nhstepm, hstepm;
                   4352:   double *xp;
                   4353:   double *gp, *gm;
                   4354:   double **gradg, **trgradg;
1.208     brouard  4355:   double **mgm, **mgp;
1.126     brouard  4356:   double age,agelim;
                   4357:   int theta;
                   4358:   
                   4359:   pstamp(ficresvpl);
                   4360:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4361:   fprintf(ficresvpl,"# Age");
                   4362:   for(i=1; i<=nlstate;i++)
                   4363:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4364:   fprintf(ficresvpl,"\n");
                   4365: 
                   4366:   xp=vector(1,npar);
                   4367:   dnewm=matrix(1,nlstate,1,npar);
                   4368:   doldm=matrix(1,nlstate,1,nlstate);
                   4369:   
                   4370:   hstepm=1*YEARM; /* Every year of age */
                   4371:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4372:   agelim = AGESUP;
                   4373:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4374:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4375:     if (stepm >= YEARM) hstepm=1;
                   4376:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4377:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4378:     mgp=matrix(1,npar,1,nlstate);
                   4379:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4380:     gp=vector(1,nlstate);
                   4381:     gm=vector(1,nlstate);
                   4382: 
                   4383:     for(theta=1; theta <=npar; theta++){
                   4384:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4385:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4386:       }
1.209     brouard  4387:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4388:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4389:       else
                   4390:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4391:       for(i=1;i<=nlstate;i++){
1.126     brouard  4392:        gp[i] = prlim[i][i];
1.208     brouard  4393:        mgp[theta][i] = prlim[i][i];
                   4394:       }
1.126     brouard  4395:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4396:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4397:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4398:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4399:       else
                   4400:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4401:       for(i=1;i<=nlstate;i++){
1.126     brouard  4402:        gm[i] = prlim[i][i];
1.208     brouard  4403:        mgm[theta][i] = prlim[i][i];
                   4404:       }
1.126     brouard  4405:       for(i=1;i<=nlstate;i++)
                   4406:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  4407:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4408:     } /* End theta */
                   4409: 
                   4410:     trgradg =matrix(1,nlstate,1,npar);
                   4411: 
                   4412:     for(j=1; j<=nlstate;j++)
                   4413:       for(theta=1; theta <=npar; theta++)
                   4414:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  4415:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4416:     /*   printf("\nmgm mgp %d ",(int)age); */
                   4417:     /*   for(j=1; j<=nlstate;j++){ */
                   4418:     /*         printf(" %d ",j); */
                   4419:     /*         for(theta=1; theta <=npar; theta++) */
                   4420:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   4421:     /*         printf("\n "); */
                   4422:     /*   } */
                   4423:     /* } */
                   4424:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4425:     /*   printf("\n gradg %d ",(int)age); */
                   4426:     /*   for(j=1; j<=nlstate;j++){ */
                   4427:     /*         printf("%d ",j); */
                   4428:     /*         for(theta=1; theta <=npar; theta++) */
                   4429:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   4430:     /*         printf("\n "); */
                   4431:     /*   } */
                   4432:     /* } */
1.126     brouard  4433: 
                   4434:     for(i=1;i<=nlstate;i++)
                   4435:       varpl[i][(int)age] =0.;
1.209     brouard  4436:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4437:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4438:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4439:     }else{
1.126     brouard  4440:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4441:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4442:     }
1.126     brouard  4443:     for(i=1;i<=nlstate;i++)
                   4444:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4445: 
                   4446:     fprintf(ficresvpl,"%.0f ",age );
                   4447:     for(i=1; i<=nlstate;i++)
                   4448:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4449:     fprintf(ficresvpl,"\n");
                   4450:     free_vector(gp,1,nlstate);
                   4451:     free_vector(gm,1,nlstate);
1.208     brouard  4452:     free_matrix(mgm,1,npar,1,nlstate);
                   4453:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4454:     free_matrix(gradg,1,npar,1,nlstate);
                   4455:     free_matrix(trgradg,1,nlstate,1,npar);
                   4456:   } /* End age */
                   4457: 
                   4458:   free_vector(xp,1,npar);
                   4459:   free_matrix(doldm,1,nlstate,1,npar);
                   4460:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4461: 
                   4462: }
                   4463: 
                   4464: /************ Variance of one-step probabilities  ******************/
                   4465: 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[])
                   4466: {
1.164     brouard  4467:   int i, j=0,  k1, l1, tj;
1.126     brouard  4468:   int k2, l2, j1,  z1;
1.164     brouard  4469:   int k=0, l;
1.145     brouard  4470:   int first=1, first1, first2;
1.126     brouard  4471:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4472:   double **dnewm,**doldm;
                   4473:   double *xp;
                   4474:   double *gp, *gm;
                   4475:   double **gradg, **trgradg;
                   4476:   double **mu;
1.164     brouard  4477:   double age, cov[NCOVMAX+1];
1.126     brouard  4478:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4479:   int theta;
                   4480:   char fileresprob[FILENAMELENGTH];
                   4481:   char fileresprobcov[FILENAMELENGTH];
                   4482:   char fileresprobcor[FILENAMELENGTH];
                   4483:   double ***varpij;
                   4484: 
1.201     brouard  4485:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4486:   strcat(fileresprob,fileres);
                   4487:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4488:     printf("Problem with resultfile: %s\n", fileresprob);
                   4489:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4490:   }
1.201     brouard  4491:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4492:   strcat(fileresprobcov,fileresu);
1.126     brouard  4493:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4494:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4495:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4496:   }
1.201     brouard  4497:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4498:   strcat(fileresprobcor,fileresu);
1.126     brouard  4499:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4500:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4501:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4502:   }
                   4503:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4504:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4505:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4506:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4507:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4508:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4509:   pstamp(ficresprob);
                   4510:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4511:   fprintf(ficresprob,"# Age");
                   4512:   pstamp(ficresprobcov);
                   4513:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4514:   fprintf(ficresprobcov,"# Age");
                   4515:   pstamp(ficresprobcor);
                   4516:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4517:   fprintf(ficresprobcor,"# Age");
                   4518: 
                   4519: 
                   4520:   for(i=1; i<=nlstate;i++)
                   4521:     for(j=1; j<=(nlstate+ndeath);j++){
                   4522:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4523:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4524:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4525:     }  
                   4526:  /* fprintf(ficresprob,"\n");
                   4527:   fprintf(ficresprobcov,"\n");
                   4528:   fprintf(ficresprobcor,"\n");
                   4529:  */
1.131     brouard  4530:   xp=vector(1,npar);
1.126     brouard  4531:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4532:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4533:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4534:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4535:   first=1;
                   4536:   fprintf(ficgp,"\n# Routine varprob");
                   4537:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4538:   fprintf(fichtm,"\n");
                   4539: 
1.200     brouard  4540:   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  4541:   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);
                   4542:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4543: and drawn. It helps understanding how is the covariance between two incidences.\
                   4544:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4545:   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. \
                   4546: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4547: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4548: standard deviations wide on each axis. <br>\
                   4549:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4550:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4551: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4552: 
                   4553:   cov[1]=1;
1.145     brouard  4554:   /* tj=cptcoveff; */
                   4555:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4556:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4557:   j1=0;
1.145     brouard  4558:   for(j1=1; j1<=tj;j1++){
                   4559:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4560:     /*j1++;*/
1.126     brouard  4561:       if  (cptcovn>0) {
                   4562:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4563:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4564:        fprintf(ficresprob, "**********\n#\n");
                   4565:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4566:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4567:        fprintf(ficresprobcov, "**********\n#\n");
                   4568:        
                   4569:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4570:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4571:        fprintf(ficgp, "**********\n#\n");
                   4572:        
                   4573:        
                   4574:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4575:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4576:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4577:        
                   4578:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4579:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4580:        fprintf(ficresprobcor, "**********\n#");    
                   4581:       }
                   4582:       
1.145     brouard  4583:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4584:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4585:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4586:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4587:       for (age=bage; age<=fage; age ++){ 
                   4588:        cov[2]=age;
1.187     brouard  4589:        if(nagesqr==1)
                   4590:          cov[3]= age*age;
1.126     brouard  4591:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4592:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4593:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4594:                                                         * 1  1 1 1 1
                   4595:                                                         * 2  2 1 1 1
                   4596:                                                         * 3  1 2 1 1
                   4597:                                                         */
                   4598:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4599:        }
1.186     brouard  4600:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4601:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4602:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4603:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4604:        
                   4605:     
                   4606:        for(theta=1; theta <=npar; theta++){
                   4607:          for(i=1; i<=npar; i++)
                   4608:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4609:          
                   4610:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4611:          
                   4612:          k=0;
                   4613:          for(i=1; i<= (nlstate); i++){
                   4614:            for(j=1; j<=(nlstate+ndeath);j++){
                   4615:              k=k+1;
                   4616:              gp[k]=pmmij[i][j];
                   4617:            }
                   4618:          }
                   4619:          
                   4620:          for(i=1; i<=npar; i++)
                   4621:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4622:     
                   4623:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4624:          k=0;
                   4625:          for(i=1; i<=(nlstate); i++){
                   4626:            for(j=1; j<=(nlstate+ndeath);j++){
                   4627:              k=k+1;
                   4628:              gm[k]=pmmij[i][j];
                   4629:            }
                   4630:          }
                   4631:      
                   4632:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4633:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4634:        }
                   4635: 
                   4636:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4637:          for(theta=1; theta <=npar; theta++)
                   4638:            trgradg[j][theta]=gradg[theta][j];
                   4639:        
                   4640:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4641:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4642: 
                   4643:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4644:        
                   4645:        k=0;
                   4646:        for(i=1; i<=(nlstate); i++){
                   4647:          for(j=1; j<=(nlstate+ndeath);j++){
                   4648:            k=k+1;
                   4649:            mu[k][(int) age]=pmmij[i][j];
                   4650:          }
                   4651:        }
                   4652:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4653:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4654:            varpij[i][j][(int)age] = doldm[i][j];
                   4655: 
                   4656:        /*printf("\n%d ",(int)age);
                   4657:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4658:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4659:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4660:          }*/
                   4661: 
                   4662:        fprintf(ficresprob,"\n%d ",(int)age);
                   4663:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4664:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4665: 
                   4666:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4667:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4668:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4669:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4670:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4671:        }
                   4672:        i=0;
                   4673:        for (k=1; k<=(nlstate);k++){
                   4674:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4675:            i++;
1.126     brouard  4676:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4677:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4678:            for (j=1; j<=i;j++){
1.145     brouard  4679:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4680:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4681:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4682:            }
                   4683:          }
                   4684:        }/* end of loop for state */
                   4685:       } /* end of loop for age */
1.145     brouard  4686:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4687:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4688:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4689:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4690:       
1.126     brouard  4691:       /* Confidence intervalle of pij  */
                   4692:       /*
1.131     brouard  4693:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4694:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4695:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4696:        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);
                   4697:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4698:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4699:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4700:       */
                   4701: 
                   4702:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4703:       first1=1;first2=2;
1.126     brouard  4704:       for (k2=1; k2<=(nlstate);k2++){
                   4705:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4706:          if(l2==k2) continue;
                   4707:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4708:          for (k1=1; k1<=(nlstate);k1++){
                   4709:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4710:              if(l1==k1) continue;
                   4711:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4712:              if(i<=j) continue;
                   4713:              for (age=bage; age<=fage; age ++){ 
                   4714:                if ((int)age %5==0){
                   4715:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4716:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4717:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4718:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4719:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4720:                  c12=cv12/sqrt(v1*v2);
                   4721:                  /* Computing eigen value of matrix of covariance */
                   4722:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4723:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4724:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4725:                    if(first2==1){
                   4726:                      first1=0;
                   4727:                    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);
                   4728:                    }
                   4729:                    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);
                   4730:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4731:                    /* lc2=fabs(lc2); */
1.135     brouard  4732:                  }
                   4733: 
1.126     brouard  4734:                  /* Eigen vectors */
                   4735:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4736:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4737:                  v21=(lc1-v1)/cv12*v11;
                   4738:                  v12=-v21;
                   4739:                  v22=v11;
                   4740:                  tnalp=v21/v11;
                   4741:                  if(first1==1){
                   4742:                    first1=0;
                   4743:                    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);
                   4744:                  }
                   4745:                  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);
                   4746:                  /*printf(fignu*/
                   4747:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4748:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4749:                  if(first==1){
                   4750:                    first=0;
1.200     brouard  4751:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4752:                    fprintf(ficgp,"\nset parametric;unset label");
                   4753:                    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  4754:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4755:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4756:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4757: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4758:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4759:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4760:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4761:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4762:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4763:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4764:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4765:                    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",\
                   4766:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4767:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4768:                  }else{
                   4769:                    first=0;
                   4770:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4771:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4772:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4773:                    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",\
                   4774:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4775:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4776:                  }/* if first */
                   4777:                } /* age mod 5 */
                   4778:              } /* end loop age */
1.201     brouard  4779:              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  4780:              first=1;
                   4781:            } /*l12 */
                   4782:          } /* k12 */
                   4783:        } /*l1 */
                   4784:       }/* k1 */
1.169     brouard  4785:       /* } */ /* loop covariates */
1.126     brouard  4786:   }
                   4787:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4788:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4789:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4790:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4791:   free_vector(xp,1,npar);
                   4792:   fclose(ficresprob);
                   4793:   fclose(ficresprobcov);
                   4794:   fclose(ficresprobcor);
                   4795:   fflush(ficgp);
                   4796:   fflush(fichtmcov);
                   4797: }
                   4798: 
                   4799: 
                   4800: /******************* Printing html file ***********/
1.201     brouard  4801: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4802:                  int lastpass, int stepm, int weightopt, char model[],\
                   4803:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4804:                  int popforecast, int estepm ,\
                   4805:                  double jprev1, double mprev1,double anprev1, \
                   4806:                  double jprev2, double mprev2,double anprev2){
                   4807:   int jj1, k1, i1, cpt;
                   4808: 
                   4809:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4810:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4811: </ul>");
                   4812:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4813:  - 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  4814:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4815:    fprintf(fichtm,"\
                   4816:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4817:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4818:    fprintf(fichtm,"\
                   4819:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4820:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4821:    fprintf(fichtm,"\
1.128     brouard  4822:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
1.126     brouard  4823:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4824:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4825:    fprintf(fichtm,"\
                   4826:  - Population projections by age and states: \
1.201     brouard  4827:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4828: 
                   4829: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4830: 
1.145     brouard  4831:  m=pow(2,cptcoveff);
1.126     brouard  4832:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4833: 
                   4834:  jj1=0;
                   4835:  for(k1=1; k1<=m;k1++){
1.192     brouard  4836:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4837:      jj1++;
                   4838:      if (cptcovn > 0) {
                   4839:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4840:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4841:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4842:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4843:        }
1.126     brouard  4844:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4845:      }
1.201     brouard  4846:      /* aij, bij */
                   4847:      fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
                   4848: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4849:      /* Pij */
1.202     brouard  4850:      fprintf(fichtm,"<br>\n- Pij or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  4851: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4852:      /* Quasi-incidences */
1.201     brouard  4853:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4854:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4855:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4856: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4857: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4858:      /* Survival functions (period) in state j */
                   4859:      for(cpt=1; cpt<=nlstate;cpt++){
                   4860:        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> \
                   4861: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4862:      }
                   4863:      /* State specific survival functions (period) */
                   4864:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  4865:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  4866:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4867:  <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);
                   4868:      }
                   4869:      /* Period (stable) prevalence in each health state */
                   4870:      for(cpt=1; cpt<=nlstate;cpt++){
                   4871:        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> \
                   4872: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4873:      }
1.126     brouard  4874:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  4875:        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  4876: <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  4877:      }
1.192     brouard  4878:    /* } /\* end i1 *\/ */
1.126     brouard  4879:  }/* End k1 */
                   4880:  fprintf(fichtm,"</ul>");
                   4881: 
                   4882:  fprintf(fichtm,"\
                   4883: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4884:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  4885:  - 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  4886: But because parameters are usually highly correlated (a higher incidence of disability \
                   4887: and a higher incidence of recovery can give very close observed transition) it might \
                   4888: be very useful to look not only at linear confidence intervals estimated from the \
                   4889: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4890: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4891: covariance matrix of the one-step probabilities. \
                   4892: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4893: 
1.193     brouard  4894:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4895:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4896:  fprintf(fichtm,"\
                   4897:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4898:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4899: 
                   4900:  fprintf(fichtm,"\
                   4901:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4902:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4903:  fprintf(fichtm,"\
                   4904:  - 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): \
                   4905:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4906:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4907:  fprintf(fichtm,"\
                   4908:  - (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): \
                   4909:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4910:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4911:  fprintf(fichtm,"\
1.128     brouard  4912:  - 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  4913:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4914:  fprintf(fichtm,"\
1.128     brouard  4915:  - 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  4916:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4917:  fprintf(fichtm,"\
                   4918:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4919:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4920: 
                   4921: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4922: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4923: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4924: /*     <br>",fileres,fileres,fileres,fileres); */
                   4925: /*  else  */
                   4926: /*    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); */
                   4927:  fflush(fichtm);
                   4928:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4929: 
1.145     brouard  4930:  m=pow(2,cptcoveff);
1.126     brouard  4931:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4932: 
                   4933:  jj1=0;
                   4934:  for(k1=1; k1<=m;k1++){
1.192     brouard  4935:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4936:      jj1++;
                   4937:      if (cptcovn > 0) {
                   4938:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4939:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4940:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4941:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4942:      }
                   4943:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4944:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  4945: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   4946: <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  4947:      }
                   4948:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4949: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4950: true period expectancies (those weighted with period prevalences are also\
                   4951:  drawn in addition to the population based expectancies computed using\
1.205     brouard  4952:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   4953: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4954:    /* } /\* end i1 *\/ */
1.126     brouard  4955:  }/* End k1 */
                   4956:  fprintf(fichtm,"</ul>");
                   4957:  fflush(fichtm);
                   4958: }
                   4959: 
                   4960: /******************* Gnuplot file **************/
1.201     brouard  4961: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4962: 
                   4963:   char dirfileres[132],optfileres[132];
1.164     brouard  4964:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4965:   int ng=0;
1.201     brouard  4966:   int vpopbased;
1.126     brouard  4967: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4968: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4969: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4970: /*   } */
                   4971: 
                   4972:   /*#ifdef windows */
                   4973:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4974:     /*#endif */
                   4975:   m=pow(2,cptcoveff);
                   4976: 
1.210   ! brouard  4977:   /* Projected Prevalences */
        !          4978: /* plot "NAGI0w_V1V2_monthlyb2b-proj/F_NAGI0w_V1V2_monthlyb2b-proj.txt" u 6:((($1 == 1) && ($2==0) && ($3==2) &&($4==0))? $7/(1-$13):1/0) t 'p11' w line */
        !          4979: /* replot ""  u 6:((($1 == 1) && ($2==0) && ($3==2) &&($4==0))? $8/(1-$14):1/0) t 'p21' w line */
        !          4980: /* replot ""  u 6:((($1 == 1) && ($2==0) && ($3==2) &&($4==0)&&($9!=0))? $9/(1-$15):1/0) t 'p.1' w line */
        !          4981: 
1.202     brouard  4982:   /* Contribution to likelihood */
                   4983:   /* Plot the probability implied in the likelihood */
                   4984:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4985:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4986:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  4987:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  4988: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  4989:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   4990: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   4991:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  4992:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4993:     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  4994:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4995:     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  4996:     for (i=1; i<= nlstate ; i ++) {
                   4997:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  4998:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   4999:       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  5000:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.205     brouard  5001:        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  5002:       }
                   5003:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5004:     }
                   5005:     /* 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 */             
                   5006:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5007:     /* 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  5008:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5009:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5010: 
1.126     brouard  5011:   strcpy(dirfileres,optionfilefiname);
                   5012:   strcpy(optfileres,"vpl");
                   5013:  /* 1eme*/
1.201     brouard  5014:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  5015:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  5016:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  5017:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5018:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5019:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5020: set ylabel \"Probability\" \n\
1.199     brouard  5021: set ter svg size 640, 480\n\
1.201     brouard  5022: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5023: 
                   5024:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5025:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5026:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5027:      }
1.201     brouard  5028:      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  5029:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5030:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5031:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5032:      } 
1.201     brouard  5033:      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  5034:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5035:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5036:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5037:      }  
1.201     brouard  5038:      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));
                   5039:      fprintf(ficgp,"\nset out \n");
                   5040:     } /* k1 */
                   5041:   } /* cpt */
1.126     brouard  5042:   /*2 eme*/
1.153     brouard  5043:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  5044:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  5045:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5046:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5047:       if(vpopbased==0)
                   5048:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5049:       else
                   5050:        fprintf(ficgp,"\nreplot ");
                   5051:       for (i=1; i<= nlstate+1 ; i ++) {
                   5052:        k=2*i;
                   5053:        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);
                   5054:        for (j=1; j<= nlstate+1 ; j ++) {
                   5055:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5056:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5057:        }   
                   5058:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5059:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5060:        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);
                   5061:        for (j=1; j<= nlstate+1 ; j ++) {
                   5062:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5063:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5064:        }   
                   5065:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5066:        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);
                   5067:        for (j=1; j<= nlstate+1 ; j ++) {
                   5068:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5069:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5070:        }   
                   5071:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5072:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5073:       } /* state */
                   5074:     } /* vpopbased */
                   5075:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5076:   } /* k1 */
1.126     brouard  5077:   /*3eme*/
                   5078:   
                   5079:   for (k1=1; k1<= m ; k1 ++) { 
                   5080:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   5081:       /*       k=2+nlstate*(2*cpt-2); */
                   5082:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5083:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5084:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5085: 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  5086:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5087:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5088:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5089:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5090:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5091:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5092:        
                   5093:       */
                   5094:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5095:        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  5096:        /*      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);*/
                   5097:        
                   5098:       } 
1.201     brouard  5099:       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  5100:     }
                   5101:   }
                   5102:   
1.201     brouard  5103:   /* Survival functions (period) from state i in state j by initial state i */
                   5104:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5105:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5106:       k=3;
                   5107:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   5108:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5109:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5110: set ter svg size 640, 480\n\
                   5111: unset log y\n\
                   5112: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5113:       for (i=1; i<= nlstate ; i ++){
                   5114:        if(i==1)
                   5115:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5116:        else
                   5117:          fprintf(ficgp,", '' ");
                   5118:        l=(nlstate+ndeath)*(i-1)+1;
                   5119:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5120:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5121:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5122:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5123:       } /* nlstate */
                   5124:       fprintf(ficgp,"\nset out\n");
                   5125:     } /* end cpt state*/ 
                   5126:   } /* end covariate */  
                   5127: 
                   5128:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5129:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5130:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5131:       k=3;
                   5132:       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);
                   5133:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5134:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5135: set ter svg size 640, 480\n\
                   5136: unset log y\n\
                   5137: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5138:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5139:        if(j==1)
                   5140:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5141:        else
                   5142:          fprintf(ficgp,", '' ");
                   5143:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5144:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5145:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5146:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5147:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5148:       } /* nlstate */
                   5149:       fprintf(ficgp,", '' ");
                   5150:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5151:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5152:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5153:        if(j < nlstate)
                   5154:          fprintf(ficgp,"$%d +",k+l);
                   5155:        else
                   5156:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5157:       }
                   5158:       fprintf(ficgp,"\nset out\n");
                   5159:     } /* end cpt state*/ 
                   5160:   } /* end covariate */  
                   5161: 
1.202     brouard  5162:   /* CV preval stable (period) for each covariate */
                   5163:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  5164:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  5165:       k=3;
1.153     brouard  5166:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  5167:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5168:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5169: set ter svg size 640, 480\n\
1.126     brouard  5170: unset log y\n\
1.153     brouard  5171: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5172:       for (i=1; i<= nlstate ; i ++){
                   5173:        if(i==1)
1.201     brouard  5174:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5175:        else
                   5176:          fprintf(ficgp,", '' ");
1.154     brouard  5177:        l=(nlstate+ndeath)*(i-1)+1;
                   5178:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5179:        for (j=2; j<= nlstate ; j ++)
                   5180:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5181:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5182:       } /* nlstate */
1.201     brouard  5183:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5184:     } /* end cpt state*/ 
                   5185:   } /* end covariate */  
1.201     brouard  5186: 
1.126     brouard  5187:   /* proba elementaires */
1.187     brouard  5188:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5189:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5190:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5191:     for(k=1; k <=(nlstate+ndeath); k++){
                   5192:       if (k != i) {
1.187     brouard  5193:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5194:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5195:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5196:          jk++; 
                   5197:        }
1.187     brouard  5198:        fprintf(ficgp,"\n");
1.126     brouard  5199:       }
                   5200:     }
                   5201:    }
1.187     brouard  5202:   fprintf(ficgp,"##############\n#\n");
                   5203: 
1.145     brouard  5204:   /*goto avoid;*/
1.200     brouard  5205:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5206:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5207:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5208:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5209:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5210:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5211:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5212:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5213:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5214:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5215:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5216:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5217:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5218:   fprintf(ficgp,"#\n");
1.201     brouard  5219:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5220:      fprintf(ficgp,"# ng=%d\n",ng);
                   5221:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5222:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5223:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5224:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5225:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5226:        if (ng==1){
                   5227:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5228:         fprintf(ficgp,"\nunset log y");
                   5229:        }else if (ng==2){
                   5230:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5231:         fprintf(ficgp,"\nset log y");
                   5232:        }else if (ng==3){
1.126     brouard  5233:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5234:         fprintf(ficgp,"\nset log y");
                   5235:        }else
                   5236:         fprintf(ficgp,"\nunset title ");
                   5237:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5238:        i=1;
                   5239:        for(k2=1; k2<=nlstate; k2++) {
                   5240:         k3=i;
                   5241:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5242:           if (k != k2){
1.201     brouard  5243:             switch( ng) {
                   5244:             case 1:
1.187     brouard  5245:               if(nagesqr==0)
1.201     brouard  5246:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5247:               else /* nagesqr =1 */
1.201     brouard  5248:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5249:               break;
                   5250:             case 2: /* ng=2 */
1.187     brouard  5251:               if(nagesqr==0)
                   5252:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5253:               else /* nagesqr =1 */
1.201     brouard  5254:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5255:               break;
                   5256:             case 3:
                   5257:               if(nagesqr==0)
                   5258:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5259:               else /* nagesqr =1 */
                   5260:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5261:               break;
                   5262:             }
1.141     brouard  5263:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5264:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5265:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5266:               if(ij <=cptcovage) { /* Bug valgrind */
                   5267:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5268:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5269:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5270:                   ij++;
                   5271:                 }
1.186     brouard  5272:               }
                   5273:               else
1.198     brouard  5274:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5275:             }
1.201     brouard  5276:             if(ng != 1){
                   5277:               fprintf(ficgp,")/(1");
1.126     brouard  5278:             
1.201     brouard  5279:               for(k1=1; k1 <=nlstate; k1++){ 
                   5280:                 if(nagesqr==0)
                   5281:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5282:                 else /* nagesqr =1 */
                   5283:                   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);
                   5284:                 
                   5285:                 ij=1;
                   5286:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5287:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5288:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5289:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5290:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5291:                       ij++;
                   5292:                     }
1.197     brouard  5293:                   }
1.201     brouard  5294:                   else
                   5295:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5296:                 }
1.201     brouard  5297:                 fprintf(ficgp,")");
1.126     brouard  5298:               }
                   5299:               fprintf(ficgp,")");
1.201     brouard  5300:               if(ng ==2)
                   5301:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5302:               else /* ng= 3 */
                   5303:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5304:             }else{ /* end ng <> 1 */
                   5305:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5306:             }
                   5307:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5308:             i=i+ncovmodel;
                   5309:           }
                   5310:         } /* end k */
                   5311:        } /* end k2 */
1.201     brouard  5312:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5313:      } /* end jk */
                   5314:    } /* end ng */
1.164     brouard  5315:  /* avoid: */
1.126     brouard  5316:    fflush(ficgp); 
                   5317: }  /* end gnuplot */
                   5318: 
                   5319: 
                   5320: /*************** Moving average **************/
                   5321: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5322: 
                   5323:   int i, cpt, cptcod;
                   5324:   int modcovmax =1;
                   5325:   int mobilavrange, mob;
                   5326:   double age;
                   5327: 
                   5328:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5329:                           a covariate has 2 modalities */
                   5330:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5331: 
                   5332:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5333:     if(mobilav==1) mobilavrange=5; /* default */
                   5334:     else mobilavrange=mobilav;
                   5335:     for (age=bage; age<=fage; age++)
                   5336:       for (i=1; i<=nlstate;i++)
                   5337:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5338:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5339:     /* We keep the original values on the extreme ages bage, fage and for 
                   5340:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5341:        we use a 5 terms etc. until the borders are no more concerned. 
                   5342:     */ 
                   5343:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5344:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5345:        for (i=1; i<=nlstate;i++){
                   5346:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5347:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5348:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5349:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5350:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5351:              }
                   5352:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5353:          }
                   5354:        }
                   5355:       }/* end age */
                   5356:     }/* end mob */
                   5357:   }else return -1;
                   5358:   return 0;
                   5359: }/* End movingaverage */
                   5360: 
                   5361: 
                   5362: /************** Forecasting ******************/
1.169     brouard  5363: 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  5364:   /* proj1, year, month, day of starting projection 
                   5365:      agemin, agemax range of age
                   5366:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5367:      anproj2 year of en of projection (same day and month as proj1).
                   5368:   */
1.164     brouard  5369:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5370:   double agec; /* generic age */
                   5371:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5372:   double *popeffectif,*popcount;
                   5373:   double ***p3mat;
                   5374:   double ***mobaverage;
                   5375:   char fileresf[FILENAMELENGTH];
                   5376: 
                   5377:   agelim=AGESUP;
                   5378:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5379:  
1.201     brouard  5380:   strcpy(fileresf,"F_"); 
                   5381:   strcat(fileresf,fileresu);
1.126     brouard  5382:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5383:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5384:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5385:   }
                   5386:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5387:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5388: 
                   5389:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5390: 
                   5391:   if (mobilav!=0) {
                   5392:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5393:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5394:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5395:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5396:     }
                   5397:   }
                   5398: 
                   5399:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5400:   if (stepm<=12) stepsize=1;
                   5401:   if(estepm < stepm){
                   5402:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5403:   }
                   5404:   else  hstepm=estepm;   
                   5405: 
                   5406:   hstepm=hstepm/stepm; 
                   5407:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5408:                                fractional in yp1 */
                   5409:   anprojmean=yp;
                   5410:   yp2=modf((yp1*12),&yp);
                   5411:   mprojmean=yp;
                   5412:   yp1=modf((yp2*30.5),&yp);
                   5413:   jprojmean=yp;
                   5414:   if(jprojmean==0) jprojmean=1;
                   5415:   if(mprojmean==0) jprojmean=1;
                   5416: 
                   5417:   i1=cptcoveff;
                   5418:   if (cptcovn < 1){i1=1;}
                   5419:   
                   5420:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5421:   
                   5422:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5423: 
                   5424: /*           if (h==(int)(YEARM*yearp)){ */
                   5425:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5426:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5427:       k=k+1;
                   5428:       fprintf(ficresf,"\n#******");
                   5429:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5430:        fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5431:       }
                   5432:       fprintf(ficresf,"******\n");
                   5433:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5434:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5435:        for(i=1; i<=nlstate;i++)              
                   5436:           fprintf(ficresf," p%d%d",i,j);
                   5437:        fprintf(ficresf," p.%d",j);
                   5438:       }
                   5439:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5440:        fprintf(ficresf,"\n");
                   5441:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5442: 
                   5443:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5444:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5445:          nhstepm = nhstepm/hstepm; 
                   5446:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5447:          oldm=oldms;savm=savms;
                   5448:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5449:        
                   5450:          for (h=0; h<=nhstepm; h++){
                   5451:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5452:               fprintf(ficresf,"\n");
                   5453:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5454:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5455:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5456:            } 
                   5457:            for(j=1; j<=nlstate+ndeath;j++) {
                   5458:              ppij=0.;
                   5459:              for(i=1; i<=nlstate;i++) {
                   5460:                if (mobilav==1) 
                   5461:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5462:                else {
                   5463:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5464:                }
                   5465:                if (h*hstepm/YEARM*stepm== yearp) {
                   5466:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5467:                }
                   5468:              } /* end i */
                   5469:              if (h*hstepm/YEARM*stepm==yearp) {
                   5470:                fprintf(ficresf," %.3f", ppij);
                   5471:              }
                   5472:            }/* end j */
                   5473:          } /* end h */
                   5474:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5475:        } /* end agec */
                   5476:       } /* end yearp */
                   5477:     } /* end cptcod */
                   5478:   } /* end  cptcov */
                   5479:        
                   5480:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5481: 
                   5482:   fclose(ficresf);
                   5483: }
                   5484: 
                   5485: /************** Forecasting *****not tested NB*************/
1.169     brouard  5486: 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  5487:   
                   5488:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5489:   int *popage;
                   5490:   double calagedatem, agelim, kk1, kk2;
                   5491:   double *popeffectif,*popcount;
                   5492:   double ***p3mat,***tabpop,***tabpopprev;
                   5493:   double ***mobaverage;
                   5494:   char filerespop[FILENAMELENGTH];
                   5495: 
                   5496:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5497:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5498:   agelim=AGESUP;
                   5499:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5500:   
                   5501:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5502:   
                   5503:   
1.201     brouard  5504:   strcpy(filerespop,"POP_"); 
                   5505:   strcat(filerespop,fileresu);
1.126     brouard  5506:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5507:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5508:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5509:   }
                   5510:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5511:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5512: 
                   5513:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5514: 
                   5515:   if (mobilav!=0) {
                   5516:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5517:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5518:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5519:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5520:     }
                   5521:   }
                   5522: 
                   5523:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5524:   if (stepm<=12) stepsize=1;
                   5525:   
                   5526:   agelim=AGESUP;
                   5527:   
                   5528:   hstepm=1;
                   5529:   hstepm=hstepm/stepm; 
                   5530:   
                   5531:   if (popforecast==1) {
                   5532:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5533:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5534:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5535:     } 
                   5536:     popage=ivector(0,AGESUP);
                   5537:     popeffectif=vector(0,AGESUP);
                   5538:     popcount=vector(0,AGESUP);
                   5539:     
                   5540:     i=1;   
                   5541:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5542:    
                   5543:     imx=i;
                   5544:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5545:   }
                   5546: 
                   5547:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5548:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5549:       k=k+1;
                   5550:       fprintf(ficrespop,"\n#******");
                   5551:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5552:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5553:       }
                   5554:       fprintf(ficrespop,"******\n");
                   5555:       fprintf(ficrespop,"# Age");
                   5556:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5557:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5558:       
                   5559:       for (cpt=0; cpt<=0;cpt++) { 
                   5560:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5561:        
                   5562:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5563:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5564:          nhstepm = nhstepm/hstepm; 
                   5565:          
                   5566:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5567:          oldm=oldms;savm=savms;
                   5568:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5569:        
                   5570:          for (h=0; h<=nhstepm; h++){
                   5571:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5572:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5573:            } 
                   5574:            for(j=1; j<=nlstate+ndeath;j++) {
                   5575:              kk1=0.;kk2=0;
                   5576:              for(i=1; i<=nlstate;i++) {              
                   5577:                if (mobilav==1) 
                   5578:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5579:                else {
                   5580:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5581:                }
                   5582:              }
                   5583:              if (h==(int)(calagedatem+12*cpt)){
                   5584:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5585:                  /*fprintf(ficrespop," %.3f", kk1);
                   5586:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5587:              }
                   5588:            }
                   5589:            for(i=1; i<=nlstate;i++){
                   5590:              kk1=0.;
                   5591:                for(j=1; j<=nlstate;j++){
                   5592:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5593:                }
                   5594:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5595:            }
                   5596: 
                   5597:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5598:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5599:          }
                   5600:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5601:        }
                   5602:       }
                   5603:  
                   5604:   /******/
                   5605: 
                   5606:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5607:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5608:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5609:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5610:          nhstepm = nhstepm/hstepm; 
                   5611:          
                   5612:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5613:          oldm=oldms;savm=savms;
                   5614:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5615:          for (h=0; h<=nhstepm; h++){
                   5616:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5617:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5618:            } 
                   5619:            for(j=1; j<=nlstate+ndeath;j++) {
                   5620:              kk1=0.;kk2=0;
                   5621:              for(i=1; i<=nlstate;i++) {              
                   5622:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5623:              }
                   5624:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5625:            }
                   5626:          }
                   5627:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5628:        }
                   5629:       }
                   5630:    } 
                   5631:   }
                   5632:  
                   5633:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5634: 
                   5635:   if (popforecast==1) {
                   5636:     free_ivector(popage,0,AGESUP);
                   5637:     free_vector(popeffectif,0,AGESUP);
                   5638:     free_vector(popcount,0,AGESUP);
                   5639:   }
                   5640:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5641:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5642:   fclose(ficrespop);
                   5643: } /* End of popforecast */
                   5644: 
                   5645: int fileappend(FILE *fichier, char *optionfich)
                   5646: {
                   5647:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5648:     printf("Problem with file: %s\n", optionfich);
                   5649:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5650:     return (0);
                   5651:   }
                   5652:   fflush(fichier);
                   5653:   return (1);
                   5654: }
                   5655: 
                   5656: 
                   5657: /**************** function prwizard **********************/
                   5658: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5659: {
                   5660: 
                   5661:   /* Wizard to print covariance matrix template */
                   5662: 
1.164     brouard  5663:   char ca[32], cb[32];
                   5664:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5665:   int numlinepar;
                   5666: 
                   5667:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5668:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5669:   for(i=1; i <=nlstate; i++){
                   5670:     jj=0;
                   5671:     for(j=1; j <=nlstate+ndeath; j++){
                   5672:       if(j==i) continue;
                   5673:       jj++;
                   5674:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5675:       printf("%1d%1d",i,j);
                   5676:       fprintf(ficparo,"%1d%1d",i,j);
                   5677:       for(k=1; k<=ncovmodel;k++){
                   5678:        /*        printf(" %lf",param[i][j][k]); */
                   5679:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5680:        printf(" 0.");
                   5681:        fprintf(ficparo," 0.");
                   5682:       }
                   5683:       printf("\n");
                   5684:       fprintf(ficparo,"\n");
                   5685:     }
                   5686:   }
                   5687:   printf("# Scales (for hessian or gradient estimation)\n");
                   5688:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5689:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5690:   for(i=1; i <=nlstate; i++){
                   5691:     jj=0;
                   5692:     for(j=1; j <=nlstate+ndeath; j++){
                   5693:       if(j==i) continue;
                   5694:       jj++;
                   5695:       fprintf(ficparo,"%1d%1d",i,j);
                   5696:       printf("%1d%1d",i,j);
                   5697:       fflush(stdout);
                   5698:       for(k=1; k<=ncovmodel;k++){
                   5699:        /*      printf(" %le",delti3[i][j][k]); */
                   5700:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5701:        printf(" 0.");
                   5702:        fprintf(ficparo," 0.");
                   5703:       }
                   5704:       numlinepar++;
                   5705:       printf("\n");
                   5706:       fprintf(ficparo,"\n");
                   5707:     }
                   5708:   }
                   5709:   printf("# Covariance matrix\n");
                   5710: /* # 121 Var(a12)\n\ */
                   5711: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5712: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5713: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5714: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5715: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5716: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5717: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5718:   fflush(stdout);
                   5719:   fprintf(ficparo,"# Covariance matrix\n");
                   5720:   /* # 121 Var(a12)\n\ */
                   5721:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5722:   /* #   ...\n\ */
                   5723:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5724:   
                   5725:   for(itimes=1;itimes<=2;itimes++){
                   5726:     jj=0;
                   5727:     for(i=1; i <=nlstate; i++){
                   5728:       for(j=1; j <=nlstate+ndeath; j++){
                   5729:        if(j==i) continue;
                   5730:        for(k=1; k<=ncovmodel;k++){
                   5731:          jj++;
                   5732:          ca[0]= k+'a'-1;ca[1]='\0';
                   5733:          if(itimes==1){
                   5734:            printf("#%1d%1d%d",i,j,k);
                   5735:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5736:          }else{
                   5737:            printf("%1d%1d%d",i,j,k);
                   5738:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5739:            /*  printf(" %.5le",matcov[i][j]); */
                   5740:          }
                   5741:          ll=0;
                   5742:          for(li=1;li <=nlstate; li++){
                   5743:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5744:              if(lj==li) continue;
                   5745:              for(lk=1;lk<=ncovmodel;lk++){
                   5746:                ll++;
                   5747:                if(ll<=jj){
                   5748:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5749:                  if(ll<jj){
                   5750:                    if(itimes==1){
                   5751:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5752:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5753:                    }else{
                   5754:                      printf(" 0.");
                   5755:                      fprintf(ficparo," 0.");
                   5756:                    }
                   5757:                  }else{
                   5758:                    if(itimes==1){
                   5759:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5760:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5761:                    }else{
                   5762:                      printf(" 0.");
                   5763:                      fprintf(ficparo," 0.");
                   5764:                    }
                   5765:                  }
                   5766:                }
                   5767:              } /* end lk */
                   5768:            } /* end lj */
                   5769:          } /* end li */
                   5770:          printf("\n");
                   5771:          fprintf(ficparo,"\n");
                   5772:          numlinepar++;
                   5773:        } /* end k*/
                   5774:       } /*end j */
                   5775:     } /* end i */
                   5776:   } /* end itimes */
                   5777: 
                   5778: } /* end of prwizard */
                   5779: /******************* Gompertz Likelihood ******************************/
                   5780: double gompertz(double x[])
                   5781: { 
                   5782:   double A,B,L=0.0,sump=0.,num=0.;
                   5783:   int i,n=0; /* n is the size of the sample */
                   5784: 
                   5785:   for (i=0;i<=imx-1 ; i++) {
                   5786:     sump=sump+weight[i];
                   5787:     /*    sump=sump+1;*/
                   5788:     num=num+1;
                   5789:   }
                   5790:  
                   5791:  
                   5792:   /* for (i=0; i<=imx; i++) 
                   5793:      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]);*/
                   5794: 
                   5795:   for (i=1;i<=imx ; i++)
                   5796:     {
                   5797:       if (cens[i] == 1 && wav[i]>1)
                   5798:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5799:       
                   5800:       if (cens[i] == 0 && wav[i]>1)
                   5801:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5802:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5803:       
                   5804:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5805:       if (wav[i] > 1 ) { /* ??? */
                   5806:        L=L+A*weight[i];
                   5807:        /*      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]);*/
                   5808:       }
                   5809:     }
                   5810: 
                   5811:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5812:  
                   5813:   return -2*L*num/sump;
                   5814: }
                   5815: 
1.136     brouard  5816: #ifdef GSL
                   5817: /******************* Gompertz_f Likelihood ******************************/
                   5818: double gompertz_f(const gsl_vector *v, void *params)
                   5819: { 
                   5820:   double A,B,LL=0.0,sump=0.,num=0.;
                   5821:   double *x= (double *) v->data;
                   5822:   int i,n=0; /* n is the size of the sample */
                   5823: 
                   5824:   for (i=0;i<=imx-1 ; i++) {
                   5825:     sump=sump+weight[i];
                   5826:     /*    sump=sump+1;*/
                   5827:     num=num+1;
                   5828:   }
                   5829:  
                   5830:  
                   5831:   /* for (i=0; i<=imx; i++) 
                   5832:      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]);*/
                   5833:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5834:   for (i=1;i<=imx ; i++)
                   5835:     {
                   5836:       if (cens[i] == 1 && wav[i]>1)
                   5837:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5838:       
                   5839:       if (cens[i] == 0 && wav[i]>1)
                   5840:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5841:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5842:       
                   5843:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5844:       if (wav[i] > 1 ) { /* ??? */
                   5845:        LL=LL+A*weight[i];
                   5846:        /*      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]);*/
                   5847:       }
                   5848:     }
                   5849: 
                   5850:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5851:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5852:  
                   5853:   return -2*LL*num/sump;
                   5854: }
                   5855: #endif
                   5856: 
1.126     brouard  5857: /******************* Printing html file ***********/
1.201     brouard  5858: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5859:                  int lastpass, int stepm, int weightopt, char model[],\
                   5860:                  int imx,  double p[],double **matcov,double agemortsup){
                   5861:   int i,k;
                   5862: 
                   5863:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5864:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5865:   for (i=1;i<=2;i++) 
                   5866:     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  5867:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5868:   fprintf(fichtm,"</ul>");
                   5869: 
                   5870: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5871: 
                   5872:  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>");
                   5873: 
                   5874:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5875:    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]);
                   5876: 
                   5877:  
                   5878:   fflush(fichtm);
                   5879: }
                   5880: 
                   5881: /******************* Gnuplot file **************/
1.201     brouard  5882: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5883: 
                   5884:   char dirfileres[132],optfileres[132];
1.164     brouard  5885: 
1.126     brouard  5886:   int ng;
                   5887: 
                   5888: 
                   5889:   /*#ifdef windows */
                   5890:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5891:     /*#endif */
                   5892: 
                   5893: 
                   5894:   strcpy(dirfileres,optionfilefiname);
                   5895:   strcpy(optfileres,"vpl");
1.199     brouard  5896:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5897:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5898:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5899:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5900:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5901: 
                   5902: } 
                   5903: 
1.136     brouard  5904: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5905: {
1.126     brouard  5906: 
1.136     brouard  5907:   /*-------- data file ----------*/
                   5908:   FILE *fic;
                   5909:   char dummy[]="                         ";
1.164     brouard  5910:   int i=0, j=0, n=0;
1.136     brouard  5911:   int linei, month, year,iout;
                   5912:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5913:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5914:   char *stratrunc;
                   5915:   int lstra;
1.126     brouard  5916: 
                   5917: 
1.136     brouard  5918:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5919:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5920:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5921:   }
1.126     brouard  5922: 
1.136     brouard  5923:   i=1;
                   5924:   linei=0;
                   5925:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5926:     linei=linei+1;
                   5927:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5928:       if(line[j] == '\t')
                   5929:        line[j] = ' ';
                   5930:     }
                   5931:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5932:       ;
                   5933:     };
                   5934:     line[j+1]=0;  /* Trims blanks at end of line */
                   5935:     if(line[0]=='#'){
                   5936:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5937:       printf("Comment line\n%s\n",line);
                   5938:       continue;
                   5939:     }
                   5940:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5941:     strcpy(line, linetmp);
1.136     brouard  5942:   
1.126     brouard  5943: 
1.136     brouard  5944:     for (j=maxwav;j>=1;j--){
1.137     brouard  5945:       cutv(stra, strb, line, ' '); 
1.136     brouard  5946:       if(strb[0]=='.') { /* Missing status */
                   5947:        lval=-1;
                   5948:       }else{
                   5949:        errno=0;
                   5950:        lval=strtol(strb,&endptr,10); 
                   5951:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5952:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5953:          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);
                   5954:          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  5955:          return 1;
                   5956:        }
                   5957:       }
                   5958:       s[j][i]=lval;
                   5959:       
                   5960:       strcpy(line,stra);
                   5961:       cutv(stra, strb,line,' ');
1.169     brouard  5962:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5963:       }
1.169     brouard  5964:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5965:        month=99;
                   5966:        year=9999;
                   5967:       }else{
1.141     brouard  5968:        printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
                   5969:        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  5970:        return 1;
                   5971:       }
                   5972:       anint[j][i]= (double) year; 
                   5973:       mint[j][i]= (double)month; 
                   5974:       strcpy(line,stra);
                   5975:     } /* ENd Waves */
                   5976:     
                   5977:     cutv(stra, strb,line,' '); 
1.169     brouard  5978:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5979:     }
1.169     brouard  5980:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5981:       month=99;
                   5982:       year=9999;
                   5983:     }else{
1.141     brouard  5984:       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);
                   5985:        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  5986:        return 1;
                   5987:     }
                   5988:     andc[i]=(double) year; 
                   5989:     moisdc[i]=(double) month; 
                   5990:     strcpy(line,stra);
                   5991:     
                   5992:     cutv(stra, strb,line,' '); 
1.169     brouard  5993:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5994:     }
1.169     brouard  5995:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5996:       month=99;
                   5997:       year=9999;
                   5998:     }else{
1.141     brouard  5999:       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);
                   6000:       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  6001:        return 1;
                   6002:     }
                   6003:     if (year==9999) {
1.141     brouard  6004:       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);
                   6005:       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  6006:        return 1;
1.126     brouard  6007: 
1.136     brouard  6008:     }
                   6009:     annais[i]=(double)(year);
                   6010:     moisnais[i]=(double)(month); 
                   6011:     strcpy(line,stra);
                   6012:     
                   6013:     cutv(stra, strb,line,' '); 
                   6014:     errno=0;
                   6015:     dval=strtod(strb,&endptr); 
                   6016:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6017:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6018:       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  6019:       fflush(ficlog);
                   6020:       return 1;
                   6021:     }
                   6022:     weight[i]=dval; 
                   6023:     strcpy(line,stra);
                   6024:     
                   6025:     for (j=ncovcol;j>=1;j--){
                   6026:       cutv(stra, strb,line,' '); 
                   6027:       if(strb[0]=='.') { /* Missing status */
                   6028:        lval=-1;
                   6029:       }else{
                   6030:        errno=0;
                   6031:        lval=strtol(strb,&endptr,10); 
                   6032:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6033:          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);
                   6034:          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  6035:          return 1;
                   6036:        }
                   6037:       }
                   6038:       if(lval <-1 || lval >1){
1.141     brouard  6039:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6040:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6041:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6042:  For example, for multinomial values like 1, 2 and 3,\n \
                   6043:  build V1=0 V2=0 for the reference value (1),\n \
                   6044:         V1=1 V2=0 for (2) \n \
                   6045:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6046:  output of IMaCh is often meaningless.\n \
                   6047:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6048:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6049:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6050:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6051:  For example, for multinomial values like 1, 2 and 3,\n \
                   6052:  build V1=0 V2=0 for the reference value (1),\n \
                   6053:         V1=1 V2=0 for (2) \n \
                   6054:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6055:  output of IMaCh is often meaningless.\n \
                   6056:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6057:        return 1;
                   6058:       }
                   6059:       covar[j][i]=(double)(lval);
                   6060:       strcpy(line,stra);
                   6061:     }  
                   6062:     lstra=strlen(stra);
                   6063:      
                   6064:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6065:       stratrunc = &(stra[lstra-9]);
                   6066:       num[i]=atol(stratrunc);
                   6067:     }
                   6068:     else
                   6069:       num[i]=atol(stra);
                   6070:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6071:       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;}*/
                   6072:     
                   6073:     i=i+1;
                   6074:   } /* End loop reading  data */
1.126     brouard  6075: 
1.136     brouard  6076:   *imax=i-1; /* Number of individuals */
                   6077:   fclose(fic);
                   6078:  
                   6079:   return (0);
1.164     brouard  6080:   /* endread: */
1.136     brouard  6081:     printf("Exiting readdata: ");
                   6082:     fclose(fic);
                   6083:     return (1);
1.126     brouard  6084: 
                   6085: 
                   6086: 
1.136     brouard  6087: }
1.145     brouard  6088: void removespace(char *str) {
                   6089:   char *p1 = str, *p2 = str;
                   6090:   do
                   6091:     while (*p2 == ' ')
                   6092:       p2++;
1.169     brouard  6093:   while (*p1++ == *p2++);
1.145     brouard  6094: }
                   6095: 
                   6096: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6097:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6098:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6099:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6100:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6101:    * - cptcovage number of covariates with age*products =2
                   6102:    * - cptcovs number of simple covariates
                   6103:    * - 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
                   6104:    *     which is a new column after the 9 (ncovcol) variables. 
                   6105:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6106:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6107:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6108:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6109:  */
1.136     brouard  6110: {
1.145     brouard  6111:   int i, j, k, ks;
1.164     brouard  6112:   int  j1, k1, k2;
1.136     brouard  6113:   char modelsav[80];
1.145     brouard  6114:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6115:   char *strpt;
1.136     brouard  6116: 
1.145     brouard  6117:   /*removespace(model);*/
1.136     brouard  6118:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6119:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6120:     if (strstr(model,"AGE") !=0){
1.192     brouard  6121:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6122:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6123:       return 1;
                   6124:     }
1.141     brouard  6125:     if (strstr(model,"v") !=0){
                   6126:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6127:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6128:       return 1;
                   6129:     }
1.187     brouard  6130:     strcpy(modelsav,model); 
                   6131:     if ((strpt=strstr(model,"age*age")) !=0){
                   6132:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6133:       if(strpt != model){
                   6134:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6135:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6136:  corresponding column of parameters.\n",model);
                   6137:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6138:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6139:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6140:       return 1;
                   6141:     }
                   6142: 
                   6143:       nagesqr=1;
                   6144:       if (strstr(model,"+age*age") !=0)
                   6145:        substrchaine(modelsav, model, "+age*age");
                   6146:       else if (strstr(model,"age*age+") !=0)
                   6147:        substrchaine(modelsav, model, "age*age+");
                   6148:       else 
                   6149:        substrchaine(modelsav, model, "age*age");
                   6150:     }else
                   6151:       nagesqr=0;
                   6152:     if (strlen(modelsav) >1){
                   6153:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6154:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6155:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6156:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6157:                   * cst, age and age*age 
                   6158:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6159:                   /* including age products which are counted in cptcovage.
                   6160:                  * but the covariates which are products must be treated 
                   6161:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6162:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6163:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6164: 
                   6165:     
                   6166:       /*   Design
                   6167:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6168:        *  <          ncovcol=8                >
                   6169:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6170:        *   k=  1    2      3       4     5       6      7        8
                   6171:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6172:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6173:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6174:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6175:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6176:        *  Tage[++cptcovage]=k
                   6177:        *       if products, new covar are created after ncovcol with k1
                   6178:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6179:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6180:        *  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
                   6181:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6182:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6183:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6184:        *  <          ncovcol=8                >
                   6185:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6186:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6187:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6188:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6189:        * p Tprod[1]@2={                         6, 5}
                   6190:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6191:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6192:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6193:        *How to reorganize?
                   6194:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6195:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6196:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6197:        * Struct []
                   6198:        */
1.145     brouard  6199: 
1.187     brouard  6200:       /* This loop fills the array Tvar from the string 'model'.*/
                   6201:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6202:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6203:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6204:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6205:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6206:       /*       k=1 Tvar[1]=2 (from V2) */
                   6207:       /*       k=5 Tvar[5] */
                   6208:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6209:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6210:       /*       } */
1.198     brouard  6211:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6212:       /*
                   6213:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6214:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6215:         Tvar[k]=0;
1.187     brouard  6216:       cptcovage=0;
                   6217:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6218:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6219:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6220:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6221:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6222:        /*scanf("%d",i);*/
                   6223:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6224:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6225:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6226:            /* covar is not filled and then is empty */
                   6227:            cptcovprod--;
                   6228:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6229:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6230:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6231:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6232:            /*printf("stre=%s ", stre);*/
                   6233:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6234:            cptcovprod--;
                   6235:            cutl(stre,strb,strc,'V');
                   6236:            Tvar[k]=atoi(stre);
                   6237:            cptcovage++;
                   6238:            Tage[cptcovage]=k;
                   6239:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6240:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6241:            cptcovn++;
                   6242:            cptcovprodnoage++;k1++;
                   6243:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6244:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6245:                                   because this model-covariate is a construction we invent a new column
                   6246:                                   ncovcol + k1
                   6247:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6248:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6249:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6250:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6251:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6252:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6253:            k2=k2+2;
                   6254:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6255:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6256:            for (i=1; i<=lastobs;i++){
                   6257:              /* Computes the new covariate which is a product of
                   6258:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6259:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6260:            }
                   6261:          } /* End age is not in the model */
                   6262:        } /* End if model includes a product */
                   6263:        else { /* no more sum */
                   6264:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6265:          /*  scanf("%d",i);*/
                   6266:          cutl(strd,strc,strb,'V');
                   6267:          ks++; /**< Number of simple covariates */
1.145     brouard  6268:          cptcovn++;
1.187     brouard  6269:          Tvar[k]=atoi(strd);
                   6270:        }
                   6271:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6272:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6273:          scanf("%d",i);*/
                   6274:       } /* end of loop + on total covariates */
                   6275:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6276:   } /* end if strlen(model == 0) */
1.136     brouard  6277:   
                   6278:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6279:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6280: 
                   6281:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6282:   printf("cptcovprod=%d ", cptcovprod);
                   6283:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6284: 
                   6285:   scanf("%d ",i);*/
                   6286: 
                   6287: 
1.137     brouard  6288:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6289:   /*endread:*/
1.136     brouard  6290:     printf("Exiting decodemodel: ");
                   6291:     return (1);
                   6292: }
                   6293: 
1.169     brouard  6294: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6295: {
                   6296:   int i, m;
                   6297: 
                   6298:   for (i=1; i<=imx; i++) {
                   6299:     for(m=2; (m<= maxwav); m++) {
                   6300:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6301:        anint[m][i]=9999;
                   6302:        s[m][i]=-1;
                   6303:       }
                   6304:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6305:        *nberr = *nberr + 1;
                   6306:        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);
                   6307:        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  6308:        s[m][i]=-1;
                   6309:       }
                   6310:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6311:        (*nberr)++;
1.136     brouard  6312:        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]); 
                   6313:        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]); 
                   6314:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6315:       }
                   6316:     }
                   6317:   }
                   6318: 
                   6319:   for (i=1; i<=imx; i++)  {
                   6320:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6321:     for(m=firstpass; (m<= lastpass); m++){
                   6322:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6323:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6324:          if(agedc[i]>0){
                   6325:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6326:              agev[m][i]=agedc[i];
                   6327:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6328:            }else {
1.136     brouard  6329:              if ((int)andc[i]!=9999){
                   6330:                nbwarn++;
                   6331:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6332:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6333:                agev[m][i]=-1;
                   6334:              }
                   6335:            }
1.169     brouard  6336:          } /* agedc > 0 */
1.136     brouard  6337:        }
                   6338:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6339:                                 years but with the precision of a month */
                   6340:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6341:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6342:            agev[m][i]=1;
                   6343:          else if(agev[m][i] < *agemin){ 
                   6344:            *agemin=agev[m][i];
                   6345:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6346:          }
                   6347:          else if(agev[m][i] >*agemax){
                   6348:            *agemax=agev[m][i];
1.156     brouard  6349:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6350:          }
                   6351:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6352:          /*     agev[m][i] = age[i]+2*m;*/
                   6353:        }
                   6354:        else { /* =9 */
                   6355:          agev[m][i]=1;
                   6356:          s[m][i]=-1;
                   6357:        }
                   6358:       }
                   6359:       else /*= 0 Unknown */
                   6360:        agev[m][i]=1;
                   6361:     }
                   6362:     
                   6363:   }
                   6364:   for (i=1; i<=imx; i++)  {
                   6365:     for(m=firstpass; (m<=lastpass); m++){
                   6366:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6367:        (*nberr)++;
1.136     brouard  6368:        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);     
                   6369:        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);     
                   6370:        return 1;
                   6371:       }
                   6372:     }
                   6373:   }
                   6374: 
                   6375:   /*for (i=1; i<=imx; i++){
                   6376:   for (m=firstpass; (m<lastpass); m++){
                   6377:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6378: }
                   6379: 
                   6380: }*/
                   6381: 
                   6382: 
1.139     brouard  6383:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6384:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6385: 
                   6386:   return (0);
1.164     brouard  6387:  /* endread:*/
1.136     brouard  6388:     printf("Exiting calandcheckages: ");
                   6389:     return (1);
                   6390: }
                   6391: 
1.172     brouard  6392: #if defined(_MSC_VER)
                   6393: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6394: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6395: //#include "stdafx.h"
                   6396: //#include <stdio.h>
                   6397: //#include <tchar.h>
                   6398: //#include <windows.h>
                   6399: //#include <iostream>
                   6400: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6401: 
                   6402: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6403: 
                   6404: BOOL IsWow64()
                   6405: {
                   6406:        BOOL bIsWow64 = FALSE;
                   6407: 
                   6408:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6409:        //  (HANDLE, PBOOL);
                   6410: 
                   6411:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6412: 
                   6413:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6414:        const char funcName[] = "IsWow64Process";
                   6415:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6416:                GetProcAddress(module, funcName);
                   6417: 
                   6418:        if (NULL != fnIsWow64Process)
                   6419:        {
                   6420:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6421:                        &bIsWow64))
                   6422:                        //throw std::exception("Unknown error");
                   6423:                        printf("Unknown error\n");
                   6424:        }
                   6425:        return bIsWow64 != FALSE;
                   6426: }
                   6427: #endif
1.177     brouard  6428: 
1.191     brouard  6429: void syscompilerinfo(int logged)
1.167     brouard  6430:  {
                   6431:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6432:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6433:    /* /GS /W3 /Gy
                   6434:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6435:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6436:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6437:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6438:    */ 
                   6439:    /* 64 bits */
1.185     brouard  6440:    /*
                   6441:      /GS /W3 /Gy
                   6442:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6443:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6444:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6445:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6446:    /* Optimization are useless and O3 is slower than O2 */
                   6447:    /*
                   6448:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6449:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6450:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6451:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6452:    */
1.186     brouard  6453:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6454:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6455:       /PDB:"visual studio
                   6456:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6457:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6458:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6459:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6460:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6461:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6462:       uiAccess='false'"
                   6463:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6464:       /NOLOGO /TLBID:1
                   6465:    */
1.177     brouard  6466: #if defined __INTEL_COMPILER
1.178     brouard  6467: #if defined(__GNUC__)
                   6468:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6469: #endif
1.177     brouard  6470: #elif defined(__GNUC__) 
1.179     brouard  6471: #ifndef  __APPLE__
1.174     brouard  6472: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6473: #endif
1.177     brouard  6474:    struct utsname sysInfo;
1.178     brouard  6475:    int cross = CROSS;
                   6476:    if (cross){
                   6477:           printf("Cross-");
1.191     brouard  6478:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6479:    }
1.174     brouard  6480: #endif
                   6481: 
1.171     brouard  6482: #include <stdint.h>
1.178     brouard  6483: 
1.191     brouard  6484:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6485: #if defined(__clang__)
1.191     brouard  6486:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6487: #endif
                   6488: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6489:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6490: #endif
                   6491: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6492:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6493: #endif
                   6494: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6495:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6496: #endif
                   6497: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6498:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6499: #endif
                   6500: #if defined(_MSC_VER)
1.191     brouard  6501:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6502: #endif
                   6503: #if defined(__PGI)
1.191     brouard  6504:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6505: #endif
                   6506: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6507:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6508: #endif
1.191     brouard  6509:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6510:    
1.167     brouard  6511: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6512: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6513:     // Windows (x64 and x86)
1.191     brouard  6514:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6515: #elif __unix__ // all unices, not all compilers
                   6516:     // Unix
1.191     brouard  6517:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6518: #elif __linux__
                   6519:     // linux
1.191     brouard  6520:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6521: #elif __APPLE__
1.174     brouard  6522:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6523:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6524: #endif
                   6525: 
                   6526: /*  __MINGW32__          */
                   6527: /*  __CYGWIN__  */
                   6528: /* __MINGW64__  */
                   6529: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6530: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6531: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6532: /* _WIN64  // Defined for applications for Win64. */
                   6533: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6534: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6535: 
1.167     brouard  6536: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6537:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6538: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6539:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6540: #else
1.191     brouard  6541:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6542: #endif
                   6543: 
1.169     brouard  6544: #if defined(__GNUC__)
                   6545: # if defined(__GNUC_PATCHLEVEL__)
                   6546: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6547:                             + __GNUC_MINOR__ * 100 \
                   6548:                             + __GNUC_PATCHLEVEL__)
                   6549: # else
                   6550: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6551:                             + __GNUC_MINOR__ * 100)
                   6552: # endif
1.174     brouard  6553:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6554:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6555: 
                   6556:    if (uname(&sysInfo) != -1) {
                   6557:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6558:         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  6559:    }
                   6560:    else
                   6561:       perror("uname() error");
1.179     brouard  6562:    //#ifndef __INTEL_COMPILER 
                   6563: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6564:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6565:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6566: #endif
1.169     brouard  6567: #endif
1.172     brouard  6568: 
                   6569:    //   void main()
                   6570:    //   {
1.169     brouard  6571: #if defined(_MSC_VER)
1.174     brouard  6572:    if (IsWow64()){
1.191     brouard  6573:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6574:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6575:    }
                   6576:    else{
1.191     brouard  6577:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6578:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6579:    }
1.172     brouard  6580:    //     printf("\nPress Enter to continue...");
                   6581:    //     getchar();
                   6582:    //   }
                   6583: 
1.169     brouard  6584: #endif
                   6585:    
1.167     brouard  6586: 
                   6587:  }
1.136     brouard  6588: 
1.209     brouard  6589:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  6590:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6591:   int i, j, k, i1 ;
1.202     brouard  6592:   /* double ftolpl = 1.e-10; */
1.180     brouard  6593:   double age, agebase, agelim;
1.203     brouard  6594:   double tot;
1.180     brouard  6595: 
1.202     brouard  6596:   strcpy(filerespl,"PL_");
                   6597:   strcat(filerespl,fileresu);
                   6598:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6599:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6600:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6601:   }
                   6602:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6603:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6604:   pstamp(ficrespl);
1.203     brouard  6605:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6606:   fprintf(ficrespl,"#Age ");
                   6607:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6608:   fprintf(ficrespl,"\n");
1.180     brouard  6609:   
                   6610:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6611: 
                   6612:     agebase=ageminpar;
                   6613:     agelim=agemaxpar;
                   6614: 
                   6615:     i1=pow(2,cptcoveff);
                   6616:     if (cptcovn < 1){i1=1;}
                   6617: 
                   6618:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6619:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6620:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6621:        k=k+1;
                   6622:        /* to clean */
1.198     brouard  6623:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6624:        fprintf(ficrespl,"#******");
                   6625:        printf("#******");
                   6626:        fprintf(ficlog,"#******");
1.180     brouard  6627:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6628:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6629:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6630:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6631:        }
                   6632:        fprintf(ficrespl,"******\n");
                   6633:        printf("******\n");
                   6634:        fprintf(ficlog,"******\n");
                   6635: 
                   6636:        fprintf(ficrespl,"#Age ");
                   6637:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6638:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6639:        }
1.203     brouard  6640:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6641:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6642:        
                   6643:        for (age=agebase; age<=agelim; age++){
                   6644:        /* for (age=agebase; age<=agebase; age++){ */
1.209     brouard  6645:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  6646:          fprintf(ficrespl,"%.0f ",age );
                   6647:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6648:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6649:          tot=0.;
                   6650:          for(i=1; i<=nlstate;i++){
                   6651:            tot +=  prlim[i][i];
1.180     brouard  6652:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6653:          }
1.209     brouard  6654:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  6655:        } /* Age */
                   6656:        /* was end of cptcod */
                   6657:     } /* cptcov */
1.184     brouard  6658:        return 0;
1.180     brouard  6659: }
                   6660: 
                   6661: int hPijx(double *p, int bage, int fage){
                   6662:     /*------------- h Pij x at various ages ------------*/
                   6663: 
                   6664:   int stepsize;
                   6665:   int agelim;
                   6666:   int hstepm;
                   6667:   int nhstepm;
                   6668:   int h, i, i1, j, k;
                   6669: 
                   6670:   double agedeb;
                   6671:   double ***p3mat;
                   6672: 
1.201     brouard  6673:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6674:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6675:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6676:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6677:     }
                   6678:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6679:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6680:   
                   6681:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6682:     /*if (stepm<=24) stepsize=2;*/
                   6683: 
                   6684:     agelim=AGESUP;
                   6685:     hstepm=stepsize*YEARM; /* Every year of age */
                   6686:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6687: 
                   6688:     /* hstepm=1;   aff par mois*/
                   6689:     pstamp(ficrespij);
                   6690:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6691:     i1= pow(2,cptcoveff);
1.183     brouard  6692:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6693:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6694:    /*          k=k+1;  */
                   6695:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6696:       fprintf(ficrespij,"\n#****** ");
                   6697:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6698:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6699:       fprintf(ficrespij,"******\n");
                   6700:       
                   6701:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6702:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6703:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6704:        
                   6705:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6706:        
1.183     brouard  6707:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6708:        oldm=oldms;savm=savms;
                   6709:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6710:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6711:        for(i=1; i<=nlstate;i++)
                   6712:          for(j=1; j<=nlstate+ndeath;j++)
                   6713:            fprintf(ficrespij," %1d-%1d",i,j);
                   6714:        fprintf(ficrespij,"\n");
                   6715:        for (h=0; h<=nhstepm; h++){
                   6716:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6717:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6718:          for(i=1; i<=nlstate;i++)
                   6719:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6720:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6721:          fprintf(ficrespij,"\n");
                   6722:        }
1.183     brouard  6723:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6724:        fprintf(ficrespij,"\n");
                   6725:       }
1.180     brouard  6726:       /*}*/
                   6727:     }
1.184     brouard  6728:        return 0;
1.180     brouard  6729: }
                   6730: 
                   6731: 
1.136     brouard  6732: /***********************************************/
                   6733: /**************** Main Program *****************/
                   6734: /***********************************************/
                   6735: 
                   6736: int main(int argc, char *argv[])
                   6737: {
                   6738: #ifdef GSL
                   6739:   const gsl_multimin_fminimizer_type *T;
                   6740:   size_t iteri = 0, it;
                   6741:   int rval = GSL_CONTINUE;
                   6742:   int status = GSL_SUCCESS;
                   6743:   double ssval;
                   6744: #endif
                   6745:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6746:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  6747:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6748:   int jj, ll, li, lj, lk;
1.136     brouard  6749:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6750:   int num_filled;
1.136     brouard  6751:   int itimes;
                   6752:   int NDIM=2;
                   6753:   int vpopbased=0;
                   6754: 
1.164     brouard  6755:   char ca[32], cb[32];
1.136     brouard  6756:   /*  FILE *fichtm; *//* Html File */
                   6757:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6758:   struct stat info;
1.191     brouard  6759:   double agedeb=0.;
1.194     brouard  6760: 
                   6761:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6762: 
1.165     brouard  6763:   double fret;
1.191     brouard  6764:   double dum=0.; /* Dummy variable */
1.136     brouard  6765:   double ***p3mat;
                   6766:   double ***mobaverage;
1.164     brouard  6767: 
                   6768:   char line[MAXLINE];
1.197     brouard  6769:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6770: 
                   6771:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6772:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6773:   char *tok, *val; /* pathtot */
1.136     brouard  6774:   int firstobs=1, lastobs=10;
1.195     brouard  6775:   int c,  h , cpt, c2;
1.191     brouard  6776:   int jl=0;
                   6777:   int i1, j1, jk, stepsize=0;
1.194     brouard  6778:   int count=0;
                   6779: 
1.164     brouard  6780:   int *tab; 
1.136     brouard  6781:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6782:   int mobilav=0,popforecast=0;
1.191     brouard  6783:   int hstepm=0, nhstepm=0;
1.136     brouard  6784:   int agemortsup;
                   6785:   float  sumlpop=0.;
                   6786:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6787:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6788: 
1.191     brouard  6789:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6790:   double ftolpl=FTOL;
                   6791:   double **prlim;
                   6792:   double ***param; /* Matrix of parameters */
                   6793:   double  *p;
                   6794:   double **matcov; /* Matrix of covariance */
1.203     brouard  6795:   double **hess; /* Hessian matrix */
1.136     brouard  6796:   double ***delti3; /* Scale */
                   6797:   double *delti; /* Scale */
                   6798:   double ***eij, ***vareij;
                   6799:   double **varpl; /* Variances of prevalence limits by age */
                   6800:   double *epj, vepp;
1.164     brouard  6801: 
1.136     brouard  6802:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6803:   double **ximort;
1.145     brouard  6804:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6805:   int *dcwave;
                   6806: 
1.164     brouard  6807:   char z[1]="c";
1.136     brouard  6808: 
                   6809:   /*char  *strt;*/
                   6810:   char strtend[80];
1.126     brouard  6811: 
1.164     brouard  6812: 
1.126     brouard  6813: /*   setlocale (LC_ALL, ""); */
                   6814: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6815: /*   textdomain (PACKAGE); */
                   6816: /*   setlocale (LC_CTYPE, ""); */
                   6817: /*   setlocale (LC_MESSAGES, ""); */
                   6818: 
                   6819:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6820:   rstart_time = time(NULL);  
                   6821:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6822:   start_time = *localtime(&rstart_time);
1.126     brouard  6823:   curr_time=start_time;
1.157     brouard  6824:   /*tml = *localtime(&start_time.tm_sec);*/
                   6825:   /* strcpy(strstart,asctime(&tml)); */
                   6826:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6827: 
                   6828: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6829: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6830: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6831: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6832: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6833: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6834: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6835: /*   strt=asctime(&tmg); */
                   6836: /*   printf("Time(after) =%s",strstart);  */
                   6837: /*  (void) time (&time_value);
                   6838: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6839: *  tm = *localtime(&time_value);
                   6840: *  strstart=asctime(&tm);
                   6841: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6842: */
                   6843: 
                   6844:   nberr=0; /* Number of errors and warnings */
                   6845:   nbwarn=0;
1.184     brouard  6846: #ifdef WIN32
                   6847:   _getcwd(pathcd, size);
                   6848: #else
1.126     brouard  6849:   getcwd(pathcd, size);
1.184     brouard  6850: #endif
1.191     brouard  6851:   syscompilerinfo(0);
1.196     brouard  6852:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6853:   if(argc <=1){
                   6854:     printf("\nEnter the parameter file name: ");
1.205     brouard  6855:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   6856:       printf("ERROR Empty parameter file name\n");
                   6857:       goto end;
                   6858:     }
1.126     brouard  6859:     i=strlen(pathr);
                   6860:     if(pathr[i-1]=='\n')
                   6861:       pathr[i-1]='\0';
1.156     brouard  6862:     i=strlen(pathr);
1.205     brouard  6863:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  6864:       pathr[i-1]='\0';
1.205     brouard  6865:     }
                   6866:     i=strlen(pathr);
                   6867:     if( i==0 ){
                   6868:       printf("ERROR Empty parameter file name\n");
                   6869:       goto end;
                   6870:     }
                   6871:     for (tok = pathr; tok != NULL; ){
1.126     brouard  6872:       printf("Pathr |%s|\n",pathr);
                   6873:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6874:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6875:       strcpy (pathtot, val);
                   6876:       if(pathr[0] == '\0') break; /* Dirty */
                   6877:     }
                   6878:   }
                   6879:   else{
                   6880:     strcpy(pathtot,argv[1]);
                   6881:   }
                   6882:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6883:   /*cygwin_split_path(pathtot,path,optionfile);
                   6884:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6885:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6886: 
                   6887:   /* Split argv[0], imach program to get pathimach */
                   6888:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6889:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6890:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6891:  /*   strcpy(pathimach,argv[0]); */
                   6892:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6893:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6894:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6895: #ifdef WIN32
                   6896:   _chdir(path); /* Can be a relative path */
                   6897:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6898: #else
1.126     brouard  6899:   chdir(path); /* Can be a relative path */
1.184     brouard  6900:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6901: #endif
                   6902:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6903:   strcpy(command,"mkdir ");
                   6904:   strcat(command,optionfilefiname);
                   6905:   if((outcmd=system(command)) != 0){
1.169     brouard  6906:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6907:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6908:     /* fclose(ficlog); */
                   6909: /*     exit(1); */
                   6910:   }
                   6911: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6912: /*     perror("mkdir"); */
                   6913: /*   } */
                   6914: 
                   6915:   /*-------- arguments in the command line --------*/
                   6916: 
1.186     brouard  6917:   /* Main Log file */
1.126     brouard  6918:   strcat(filelog, optionfilefiname);
                   6919:   strcat(filelog,".log");    /* */
                   6920:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6921:     printf("Problem with logfile %s\n",filelog);
                   6922:     goto end;
                   6923:   }
                   6924:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6925:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6926:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6927:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6928:  path=%s \n\
                   6929:  optionfile=%s\n\
                   6930:  optionfilext=%s\n\
1.156     brouard  6931:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6932: 
1.197     brouard  6933:   syscompilerinfo(1);
1.167     brouard  6934: 
1.126     brouard  6935:   printf("Local time (at start):%s",strstart);
                   6936:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6937:   fflush(ficlog);
                   6938: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6939: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6940: 
                   6941:   /* */
                   6942:   strcpy(fileres,"r");
                   6943:   strcat(fileres, optionfilefiname);
1.201     brouard  6944:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6945:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6946:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6947: 
1.186     brouard  6948:   /* Main ---------arguments file --------*/
1.126     brouard  6949: 
                   6950:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6951:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6952:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6953:     fflush(ficlog);
1.149     brouard  6954:     /* goto end; */
                   6955:     exit(70); 
1.126     brouard  6956:   }
                   6957: 
                   6958: 
                   6959: 
                   6960:   strcpy(filereso,"o");
1.201     brouard  6961:   strcat(filereso,fileresu);
1.126     brouard  6962:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6963:     printf("Problem with Output resultfile: %s\n", filereso);
                   6964:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6965:     fflush(ficlog);
                   6966:     goto end;
                   6967:   }
                   6968: 
                   6969:   /* Reads comments: lines beginning with '#' */
                   6970:   numlinepar=0;
1.197     brouard  6971: 
                   6972:     /* First parameter line */
                   6973:   while(fgets(line, MAXLINE, ficpar)) {
                   6974:     /* If line starts with a # it is a comment */
                   6975:     if (line[0] == '#') {
                   6976:       numlinepar++;
                   6977:       fputs(line,stdout);
                   6978:       fputs(line,ficparo);
                   6979:       fputs(line,ficlog);
                   6980:       continue;
                   6981:     }else
                   6982:       break;
                   6983:   }
                   6984:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6985:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6986:     if (num_filled != 5) {
                   6987:       printf("Should be 5 parameters\n");
                   6988:     }
1.126     brouard  6989:     numlinepar++;
1.197     brouard  6990:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6991:   }
                   6992:   /* Second parameter line */
                   6993:   while(fgets(line, MAXLINE, ficpar)) {
                   6994:     /* If line starts with a # it is a comment */
                   6995:     if (line[0] == '#') {
                   6996:       numlinepar++;
                   6997:       fputs(line,stdout);
                   6998:       fputs(line,ficparo);
                   6999:       fputs(line,ficlog);
                   7000:       continue;
                   7001:     }else
                   7002:       break;
                   7003:   }
                   7004:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   7005:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   7006:     if (num_filled != 8) {
1.209     brouard  7007:       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");
                   7008:       printf("but line=%s\n",line);
1.197     brouard  7009:     }
                   7010:     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  7011:   }
1.203     brouard  7012:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  7013:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  7014:   /* Third parameter line */
                   7015:   while(fgets(line, MAXLINE, ficpar)) {
                   7016:     /* If line starts with a # it is a comment */
                   7017:     if (line[0] == '#') {
                   7018:       numlinepar++;
                   7019:       fputs(line,stdout);
                   7020:       fputs(line,ficparo);
                   7021:       fputs(line,ficlog);
                   7022:       continue;
                   7023:     }else
                   7024:       break;
                   7025:   }
1.201     brouard  7026:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7027:     if (num_filled == 0)
                   7028:             model[0]='\0';
                   7029:     else if (num_filled != 1){
1.197     brouard  7030:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7031:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7032:       model[0]='\0';
                   7033:       goto end;
                   7034:     }
                   7035:     else{
                   7036:       if (model[0]=='+'){
                   7037:        for(i=1; i<=strlen(model);i++)
                   7038:          modeltemp[i-1]=model[i];
1.201     brouard  7039:        strcpy(model,modeltemp); 
1.197     brouard  7040:       }
                   7041:     }
1.199     brouard  7042:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7043:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7044:   }
                   7045:   /* 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); */
                   7046:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7047:   /* 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  7048:   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);
                   7049:   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  7050:   fflush(ficlog);
1.190     brouard  7051:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7052:   if(model[0]=='#'){
1.187     brouard  7053:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7054:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7055:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7056:     if(mle != -1){
                   7057:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7058:       exit(1);
                   7059:     }
                   7060:   }
1.126     brouard  7061:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7062:     ungetc(c,ficpar);
                   7063:     fgets(line, MAXLINE, ficpar);
                   7064:     numlinepar++;
1.195     brouard  7065:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7066:       z[0]=line[1];
                   7067:     }
                   7068:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7069:     fputs(line, stdout);
                   7070:     //puts(line);
1.126     brouard  7071:     fputs(line,ficparo);
                   7072:     fputs(line,ficlog);
                   7073:   }
                   7074:   ungetc(c,ficpar);
                   7075: 
                   7076:    
1.145     brouard  7077:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7078:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7079:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7080:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7081:   */
                   7082:   if (strlen(model)>1) 
1.187     brouard  7083:     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  7084:   else
1.187     brouard  7085:     ncovmodel=2; /* Constant and age */
1.133     brouard  7086:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7087:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7088:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7089:     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);
                   7090:     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);
                   7091:     fflush(stdout);
                   7092:     fclose (ficlog);
                   7093:     goto end;
                   7094:   }
1.126     brouard  7095:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7096:   delti=delti3[1][1];
                   7097:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7098:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7099:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7100:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7101:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7102:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7103:     fclose (ficparo);
                   7104:     fclose (ficlog);
                   7105:     goto end;
                   7106:     exit(0);
                   7107:   }
1.186     brouard  7108:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7109:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7110:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7111:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7112:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7113:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7114:     hess=matrix(1,npar,1,npar);
1.126     brouard  7115:   }
                   7116:   else{
1.145     brouard  7117:     /* Read guessed parameters */
1.126     brouard  7118:     /* Reads comments: lines beginning with '#' */
                   7119:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7120:       ungetc(c,ficpar);
                   7121:       fgets(line, MAXLINE, ficpar);
                   7122:       numlinepar++;
1.141     brouard  7123:       fputs(line,stdout);
1.126     brouard  7124:       fputs(line,ficparo);
                   7125:       fputs(line,ficlog);
                   7126:     }
                   7127:     ungetc(c,ficpar);
                   7128:     
                   7129:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7130:     for(i=1; i <=nlstate; i++){
                   7131:       j=0;
                   7132:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7133:        if(jj==i) continue;
                   7134:        j++;
                   7135:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7136:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7137:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7138: It might be a problem of design; if ncovcol and the model are correct\n \
                   7139: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7140:          exit(1);
                   7141:        }
                   7142:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7143:        if(mle==1)
1.193     brouard  7144:          printf("%1d%1d",i,jj);
                   7145:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7146:        for(k=1; k<=ncovmodel;k++){
                   7147:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7148:          if(mle==1){
                   7149:            printf(" %lf",param[i][j][k]);
                   7150:            fprintf(ficlog," %lf",param[i][j][k]);
                   7151:          }
                   7152:          else
                   7153:            fprintf(ficlog," %lf",param[i][j][k]);
                   7154:          fprintf(ficparo," %lf",param[i][j][k]);
                   7155:        }
                   7156:        fscanf(ficpar,"\n");
                   7157:        numlinepar++;
                   7158:        if(mle==1)
                   7159:          printf("\n");
                   7160:        fprintf(ficlog,"\n");
                   7161:        fprintf(ficparo,"\n");
                   7162:       }
                   7163:     }  
                   7164:     fflush(ficlog);
                   7165: 
1.145     brouard  7166:     /* Reads scales values */
1.126     brouard  7167:     p=param[1][1];
                   7168:     
                   7169:     /* Reads comments: lines beginning with '#' */
                   7170:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7171:       ungetc(c,ficpar);
                   7172:       fgets(line, MAXLINE, ficpar);
                   7173:       numlinepar++;
1.141     brouard  7174:       fputs(line,stdout);
1.126     brouard  7175:       fputs(line,ficparo);
                   7176:       fputs(line,ficlog);
                   7177:     }
                   7178:     ungetc(c,ficpar);
                   7179: 
                   7180:     for(i=1; i <=nlstate; i++){
                   7181:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7182:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7183:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7184:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7185:          exit(1);
                   7186:        }
                   7187:        printf("%1d%1d",i,j);
                   7188:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7189:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7190:        for(k=1; k<=ncovmodel;k++){
                   7191:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7192:          printf(" %le",delti3[i][j][k]);
                   7193:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7194:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7195:        }
                   7196:        fscanf(ficpar,"\n");
                   7197:        numlinepar++;
                   7198:        printf("\n");
                   7199:        fprintf(ficparo,"\n");
                   7200:        fprintf(ficlog,"\n");
                   7201:       }
                   7202:     }
                   7203:     fflush(ficlog);
                   7204: 
1.145     brouard  7205:     /* Reads covariance matrix */
1.126     brouard  7206:     delti=delti3[1][1];
                   7207: 
                   7208: 
                   7209:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7210:   
                   7211:     /* Reads comments: lines beginning with '#' */
                   7212:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7213:       ungetc(c,ficpar);
                   7214:       fgets(line, MAXLINE, ficpar);
                   7215:       numlinepar++;
1.141     brouard  7216:       fputs(line,stdout);
1.126     brouard  7217:       fputs(line,ficparo);
                   7218:       fputs(line,ficlog);
                   7219:     }
                   7220:     ungetc(c,ficpar);
                   7221:   
                   7222:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7223:     hess=matrix(1,npar,1,npar);
1.131     brouard  7224:     for(i=1; i <=npar; i++)
                   7225:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7226:       
1.194     brouard  7227:     /* Scans npar lines */
1.126     brouard  7228:     for(i=1; i <=npar; i++){
1.194     brouard  7229:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7230:       if(count != 3){
                   7231:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7232: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7233: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7234:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7235: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7236: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7237:        exit(1);
                   7238:       }else
1.126     brouard  7239:       if(mle==1)
1.194     brouard  7240:        printf("%1d%1d%1d",i1,j1,jk);
                   7241:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7242:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7243:       for(j=1; j <=i; j++){
                   7244:        fscanf(ficpar," %le",&matcov[i][j]);
                   7245:        if(mle==1){
                   7246:          printf(" %.5le",matcov[i][j]);
                   7247:        }
                   7248:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7249:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7250:       }
                   7251:       fscanf(ficpar,"\n");
                   7252:       numlinepar++;
                   7253:       if(mle==1)
                   7254:        printf("\n");
                   7255:       fprintf(ficlog,"\n");
                   7256:       fprintf(ficparo,"\n");
                   7257:     }
1.194     brouard  7258:     /* End of read covariance matrix npar lines */
1.126     brouard  7259:     for(i=1; i <=npar; i++)
                   7260:       for(j=i+1;j<=npar;j++)
                   7261:        matcov[i][j]=matcov[j][i];
                   7262:     
                   7263:     if(mle==1)
                   7264:       printf("\n");
                   7265:     fprintf(ficlog,"\n");
                   7266:     
                   7267:     fflush(ficlog);
                   7268:     
                   7269:     /*-------- Rewriting parameter file ----------*/
                   7270:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7271:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7272:     strcat(rfileres,".");    /* */
                   7273:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7274:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7275:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7276:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7277:     }
                   7278:     fprintf(ficres,"#%s\n",version);
                   7279:   }    /* End of mle != -3 */
                   7280: 
1.186     brouard  7281:   /*  Main data
                   7282:    */
1.126     brouard  7283:   n= lastobs;
                   7284:   num=lvector(1,n);
                   7285:   moisnais=vector(1,n);
                   7286:   annais=vector(1,n);
                   7287:   moisdc=vector(1,n);
                   7288:   andc=vector(1,n);
                   7289:   agedc=vector(1,n);
                   7290:   cod=ivector(1,n);
                   7291:   weight=vector(1,n);
                   7292:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7293:   mint=matrix(1,maxwav,1,n);
                   7294:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7295:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7296:   tab=ivector(1,NCOVMAX);
1.144     brouard  7297:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7298:   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  7299: 
1.136     brouard  7300:   /* Reads data from file datafile */
                   7301:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7302:     goto end;
                   7303: 
                   7304:   /* Calculation of the number of parameters from char model */
1.137     brouard  7305:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7306:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7307:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7308:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7309:        k=1 Tvar[1]=2 (from V2)
                   7310:     */
                   7311:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7312:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7313:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7314:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7315:   */
                   7316:   /* For model-covariate k tells which data-covariate to use but
                   7317:     because this model-covariate is a construction we invent a new column
                   7318:     ncovcol + k1
                   7319:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7320:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7321:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7322:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7323:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7324:   */
1.145     brouard  7325:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7326:   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  7327:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7328:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7329:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7330:                         4 covariates (3 plus signs)
                   7331:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7332:                      */  
1.136     brouard  7333: 
1.186     brouard  7334: /* Main decodemodel */
                   7335: 
1.187     brouard  7336: 
1.136     brouard  7337:   if(decodemodel(model, lastobs) == 1)
                   7338:     goto end;
                   7339: 
1.137     brouard  7340:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7341:     nbwarn++;
                   7342:     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); 
                   7343:     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); 
                   7344:   }
1.136     brouard  7345:     /*  if(mle==1){*/
1.137     brouard  7346:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7347:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7348:   }
                   7349: 
                   7350:     /*-calculation of age at interview from date of interview and age at death -*/
                   7351:   agev=matrix(1,maxwav,1,imx);
                   7352: 
                   7353:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7354:     goto end;
                   7355: 
1.126     brouard  7356: 
1.136     brouard  7357:   agegomp=(int)agemin;
                   7358:   free_vector(moisnais,1,n);
                   7359:   free_vector(annais,1,n);
1.126     brouard  7360:   /* free_matrix(mint,1,maxwav,1,n);
                   7361:      free_matrix(anint,1,maxwav,1,n);*/
                   7362:   free_vector(moisdc,1,n);
                   7363:   free_vector(andc,1,n);
1.145     brouard  7364:   /* */
                   7365:   
1.126     brouard  7366:   wav=ivector(1,imx);
                   7367:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7368:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7369:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7370:    
                   7371:   /* Concatenates waves */
                   7372:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7373:   /* */
                   7374:  
1.126     brouard  7375:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7376: 
                   7377:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7378:   ncodemax[1]=1;
1.145     brouard  7379:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7380:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7381:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7382:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7383:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7384:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7385: 
1.200     brouard  7386:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7387:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7388:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7389:   h=0;
                   7390: 
                   7391: 
                   7392:   /*if (cptcovn > 0) */
1.126     brouard  7393:       
1.145     brouard  7394:  
1.126     brouard  7395:   m=pow(2,cptcoveff);
                   7396:  
1.144     brouard  7397:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7398:           * For k=4 covariates, h goes from 1 to 2**k
                   7399:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7400:           *     h\k   1     2     3     4
1.143     brouard  7401:           *______________________________  
                   7402:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7403:           *     2     2     1     1     1
                   7404:           *     3 i=2 1     2     1     1
                   7405:           *     4     2     2     1     1
                   7406:           *     5 i=3 1 i=2 1     2     1
                   7407:           *     6     2     1     2     1
                   7408:           *     7 i=4 1     2     2     1
                   7409:           *     8     2     2     2     1
1.197     brouard  7410:           *     9 i=5 1 i=3 1 i=2 1     2
                   7411:           *    10     2     1     1     2
                   7412:           *    11 i=6 1     2     1     2
                   7413:           *    12     2     2     1     2
                   7414:           *    13 i=7 1 i=4 1     2     2    
                   7415:           *    14     2     1     2     2
                   7416:           *    15 i=8 1     2     2     2
                   7417:           *    16     2     2     2     2
1.143     brouard  7418:           */
1.202     brouard  7419:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7420:   /*   /\* printf("h=%2d ", h); *\/ */
                   7421:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7422:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7423:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7424:   /*    /\* } *\/ */
                   7425:   /*    /\* printf("\n"); *\/ */
                   7426:   /* } */
1.197     brouard  7427:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7428:   /*   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 *\/  */
                   7429:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7430:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7431:   /*     h++; */
                   7432:   /*     if (h>m)  */
                   7433:   /*       h=1; */
                   7434:   /*     codtab[h][k]=j; */
                   7435:   /*     /\* codtab[12][3]=1; *\/ */
                   7436:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7437:   /*     /\* 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]]); *\/ */
                   7438:   /*   }  */
                   7439:   /*     } */
                   7440:   /*   } */
                   7441:   /* }  */
1.126     brouard  7442:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7443:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7444:   /* for(i=1; i <=m ;i++){  */
                   7445:   /*    for(k=1; k <=cptcovn; k++){ */
                   7446:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7447:   /*    } */
                   7448:   /*    printf("\n"); */
                   7449:   /* } */
                   7450:   /*   scanf("%d",i);*/
1.145     brouard  7451: 
                   7452:  free_ivector(Ndum,-1,NCOVMAX);
                   7453: 
                   7454: 
1.126     brouard  7455:     
1.186     brouard  7456:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7457:   strcpy(optionfilegnuplot,optionfilefiname);
                   7458:   if(mle==-3)
1.201     brouard  7459:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7460:   strcat(optionfilegnuplot,".gp");
                   7461: 
                   7462:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7463:     printf("Problem with file %s",optionfilegnuplot);
                   7464:   }
                   7465:   else{
1.204     brouard  7466:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7467:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7468:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7469:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7470:   }
                   7471:   /*  fclose(ficgp);*/
1.186     brouard  7472: 
                   7473: 
                   7474:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7475: 
                   7476:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7477:   if(mle==-3)
1.201     brouard  7478:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7479:   strcat(optionfilehtm,".htm");
                   7480:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7481:     printf("Problem with %s \n",optionfilehtm);
                   7482:     exit(0);
1.126     brouard  7483:   }
                   7484: 
                   7485:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7486:   strcat(optionfilehtmcov,"-cov.htm");
                   7487:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7488:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7489:   }
                   7490:   else{
                   7491:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7492: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7493: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7494:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7495:   }
                   7496: 
1.204     brouard  7497:   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>  \
                   7498: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7499: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7500: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7501: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7502: \n\
                   7503: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7504:  <ul><li><h4>Parameter files</h4>\n\
                   7505:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7506:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7507:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7508:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7509:  - Date and time at start: %s</ul>\n",\
                   7510:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7511:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7512:          fileres,fileres,\
                   7513:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7514:   fflush(fichtm);
                   7515: 
                   7516:   strcpy(pathr,path);
                   7517:   strcat(pathr,optionfilefiname);
1.184     brouard  7518: #ifdef WIN32
                   7519:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7520: #else
1.126     brouard  7521:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7522: #endif
                   7523:          
1.126     brouard  7524:   
                   7525:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7526:      and prints on file fileres'p'. */
                   7527:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7528: 
                   7529:   fprintf(fichtm,"\n");
                   7530:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7531: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7532: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7533:          imx,agemin,agemax,jmin,jmax,jmean);
                   7534:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7535:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7536:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7537:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7538:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7539:     
                   7540:    
                   7541:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7542:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7543:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7544: 
                   7545:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7546:   /* For mortality only */
1.126     brouard  7547:   if (mle==-3){
1.136     brouard  7548:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7549:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7550:     cens=ivector(1,n);
                   7551:     ageexmed=vector(1,n);
                   7552:     agecens=vector(1,n);
                   7553:     dcwave=ivector(1,n);
                   7554:  
                   7555:     for (i=1; i<=imx; i++){
                   7556:       dcwave[i]=-1;
                   7557:       for (m=firstpass; m<=lastpass; m++)
                   7558:        if (s[m][i]>nlstate) {
                   7559:          dcwave[i]=m;
                   7560:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7561:          break;
                   7562:        }
                   7563:     }
                   7564: 
                   7565:     for (i=1; i<=imx; i++) {
                   7566:       if (wav[i]>0){
                   7567:        ageexmed[i]=agev[mw[1][i]][i];
                   7568:        j=wav[i];
                   7569:        agecens[i]=1.; 
                   7570: 
                   7571:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7572:          agecens[i]=agev[mw[j][i]][i];
                   7573:          cens[i]= 1;
                   7574:        }else if (ageexmed[i]< 1) 
                   7575:          cens[i]= -1;
                   7576:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7577:          cens[i]=0 ;
                   7578:       }
                   7579:       else cens[i]=-1;
                   7580:     }
                   7581:     
                   7582:     for (i=1;i<=NDIM;i++) {
                   7583:       for (j=1;j<=NDIM;j++)
                   7584:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7585:     }
                   7586:     
1.145     brouard  7587:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7588:     /*printf("%lf %lf", p[1], p[2]);*/
                   7589:     
                   7590:     
1.136     brouard  7591: #ifdef GSL
                   7592:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7593: #else
1.126     brouard  7594:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7595: #endif
1.201     brouard  7596:     strcpy(filerespow,"POW-MORT_"); 
                   7597:     strcat(filerespow,fileresu);
1.126     brouard  7598:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7599:       printf("Problem with resultfile: %s\n", filerespow);
                   7600:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7601:     }
1.136     brouard  7602: #ifdef GSL
                   7603:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7604: #else
1.126     brouard  7605:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7606: #endif
1.126     brouard  7607:     /*  for (i=1;i<=nlstate;i++)
                   7608:        for(j=1;j<=nlstate+ndeath;j++)
                   7609:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7610:     */
                   7611:     fprintf(ficrespow,"\n");
1.136     brouard  7612: #ifdef GSL
                   7613:     /* gsl starts here */ 
                   7614:     T = gsl_multimin_fminimizer_nmsimplex;
                   7615:     gsl_multimin_fminimizer *sfm = NULL;
                   7616:     gsl_vector *ss, *x;
                   7617:     gsl_multimin_function minex_func;
                   7618: 
                   7619:     /* Initial vertex size vector */
                   7620:     ss = gsl_vector_alloc (NDIM);
                   7621:     
                   7622:     if (ss == NULL){
                   7623:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7624:     }
                   7625:     /* Set all step sizes to 1 */
                   7626:     gsl_vector_set_all (ss, 0.001);
                   7627: 
                   7628:     /* Starting point */
1.126     brouard  7629:     
1.136     brouard  7630:     x = gsl_vector_alloc (NDIM);
                   7631:     
                   7632:     if (x == NULL){
                   7633:       gsl_vector_free(ss);
                   7634:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7635:     }
                   7636:   
                   7637:     /* Initialize method and iterate */
                   7638:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7639:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7640:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7641:     gsl_vector_set(x, 0, p[1]);
                   7642:     gsl_vector_set(x, 1, p[2]);
                   7643: 
                   7644:     minex_func.f = &gompertz_f;
                   7645:     minex_func.n = NDIM;
                   7646:     minex_func.params = (void *)&p; /* ??? */
                   7647:     
                   7648:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7649:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7650:     
                   7651:     printf("Iterations beginning .....\n\n");
                   7652:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7653: 
                   7654:     iteri=0;
                   7655:     while (rval == GSL_CONTINUE){
                   7656:       iteri++;
                   7657:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7658:       
                   7659:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7660:       fflush(0);
                   7661:       
                   7662:       if (status) 
                   7663:         break;
                   7664:       
                   7665:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7666:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7667:       
                   7668:       if (rval == GSL_SUCCESS)
                   7669:         printf ("converged to a local maximum at\n");
                   7670:       
                   7671:       printf("%5d ", iteri);
                   7672:       for (it = 0; it < NDIM; it++){
                   7673:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7674:       }
                   7675:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7676:     }
                   7677:     
                   7678:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7679:     
                   7680:     gsl_vector_free(x); /* initial values */
                   7681:     gsl_vector_free(ss); /* inital step size */
                   7682:     for (it=0; it<NDIM; it++){
                   7683:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7684:       fprintf(ficrespow," %.12lf", p[it]);
                   7685:     }
                   7686:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7687: #endif
                   7688: #ifdef POWELL
                   7689:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7690: #endif  
1.126     brouard  7691:     fclose(ficrespow);
                   7692:     
1.203     brouard  7693:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7694: 
                   7695:     for(i=1; i <=NDIM; i++)
                   7696:       for(j=i+1;j<=NDIM;j++)
                   7697:        matcov[i][j]=matcov[j][i];
                   7698:     
                   7699:     printf("\nCovariance matrix\n ");
1.203     brouard  7700:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7701:     for(i=1; i <=NDIM; i++) {
                   7702:       for(j=1;j<=NDIM;j++){ 
                   7703:        printf("%f ",matcov[i][j]);
1.203     brouard  7704:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7705:       }
1.203     brouard  7706:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7707:     }
                   7708:     
                   7709:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7710:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7711:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7712:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7713:     }
1.126     brouard  7714:     lsurv=vector(1,AGESUP);
                   7715:     lpop=vector(1,AGESUP);
                   7716:     tpop=vector(1,AGESUP);
                   7717:     lsurv[agegomp]=100000;
                   7718:     
                   7719:     for (k=agegomp;k<=AGESUP;k++) {
                   7720:       agemortsup=k;
                   7721:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7722:     }
                   7723:     
                   7724:     for (k=agegomp;k<agemortsup;k++)
                   7725:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7726:     
                   7727:     for (k=agegomp;k<agemortsup;k++){
                   7728:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7729:       sumlpop=sumlpop+lpop[k];
                   7730:     }
                   7731:     
                   7732:     tpop[agegomp]=sumlpop;
                   7733:     for (k=agegomp;k<(agemortsup-3);k++){
                   7734:       /*  tpop[k+1]=2;*/
                   7735:       tpop[k+1]=tpop[k]-lpop[k];
                   7736:     }
                   7737:     
                   7738:     
                   7739:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7740:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7741:       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]);
                   7742:     
                   7743:     
                   7744:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7745:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7746:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7747: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7748: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7749:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7750: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7751: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7752:     }else
1.201     brouard  7753:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7754:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7755:                     stepm, weightopt,\
                   7756:                     model,imx,p,matcov,agemortsup);
                   7757:     
                   7758:     free_vector(lsurv,1,AGESUP);
                   7759:     free_vector(lpop,1,AGESUP);
                   7760:     free_vector(tpop,1,AGESUP);
1.136     brouard  7761: #ifdef GSL
                   7762:     free_ivector(cens,1,n);
                   7763:     free_vector(agecens,1,n);
                   7764:     free_ivector(dcwave,1,n);
                   7765:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7766: #endif
1.186     brouard  7767:   } /* Endof if mle==-3 mortality only */
1.205     brouard  7768:   /* Standard  */
                   7769:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   7770:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7771:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  7772:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7773:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7774:     for (k=1; k<=npar;k++)
                   7775:       printf(" %d %8.5f",k,p[k]);
                   7776:     printf("\n");
1.205     brouard  7777:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   7778:       /* mlikeli uses func not funcone */
                   7779:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7780:     }
                   7781:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   7782:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7783:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   7784:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7785:     }
                   7786:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  7787:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7788:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7789:     for (k=1; k<=npar;k++)
                   7790:       printf(" %d %8.5f",k,p[k]);
                   7791:     printf("\n");
                   7792:     
                   7793:     /*--------- results files --------------*/
1.192     brouard  7794:     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  7795:     
                   7796:     
                   7797:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7798:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7799:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7800:     for(i=1,jk=1; i <=nlstate; i++){
                   7801:       for(k=1; k <=(nlstate+ndeath); k++){
                   7802:        if (k != i) {
                   7803:          printf("%d%d ",i,k);
                   7804:          fprintf(ficlog,"%d%d ",i,k);
                   7805:          fprintf(ficres,"%1d%1d ",i,k);
                   7806:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7807:            printf("%12.7f ",p[jk]);
                   7808:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7809:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7810:            jk++; 
                   7811:          }
                   7812:          printf("\n");
                   7813:          fprintf(ficlog,"\n");
                   7814:          fprintf(ficres,"\n");
                   7815:        }
                   7816:       }
                   7817:     }
1.203     brouard  7818:     if(mle != 0){
                   7819:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  7820:       ftolhess=ftol; /* Usually correct */
1.203     brouard  7821:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   7822:       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");
                   7823:       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");
                   7824:       for(i=1,jk=1; i <=nlstate; i++){
                   7825:        for(k=1; k <=(nlstate+ndeath); k++){
                   7826:          if (k != i) {
                   7827:            printf("%d%d ",i,k);
                   7828:            fprintf(ficlog,"%d%d ",i,k);
                   7829:            for(j=1; j <=ncovmodel; j++){
                   7830:              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]));
                   7831:              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]));
                   7832:              jk++; 
                   7833:            }
                   7834:            printf("\n");
                   7835:            fprintf(ficlog,"\n");
1.193     brouard  7836:          }
                   7837:        }
                   7838:       }
1.203     brouard  7839:     } /* end of hesscov and Wald tests */
1.193     brouard  7840: 
1.203     brouard  7841:     /*  */
1.126     brouard  7842:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7843:     printf("# Scales (for hessian or gradient estimation)\n");
                   7844:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7845:     for(i=1,jk=1; i <=nlstate; i++){
                   7846:       for(j=1; j <=nlstate+ndeath; j++){
                   7847:        if (j!=i) {
                   7848:          fprintf(ficres,"%1d%1d",i,j);
                   7849:          printf("%1d%1d",i,j);
                   7850:          fprintf(ficlog,"%1d%1d",i,j);
                   7851:          for(k=1; k<=ncovmodel;k++){
                   7852:            printf(" %.5e",delti[jk]);
                   7853:            fprintf(ficlog," %.5e",delti[jk]);
                   7854:            fprintf(ficres," %.5e",delti[jk]);
                   7855:            jk++;
                   7856:          }
                   7857:          printf("\n");
                   7858:          fprintf(ficlog,"\n");
                   7859:          fprintf(ficres,"\n");
                   7860:        }
                   7861:       }
                   7862:     }
                   7863:     
                   7864:     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  7865:     if(mle >= 1) /* To big for the screen */
1.126     brouard  7866:       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");
                   7867:     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");
                   7868:     /* # 121 Var(a12)\n\ */
                   7869:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7870:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7871:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7872:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7873:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7874:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7875:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7876:     
                   7877:     
                   7878:     /* Just to have a covariance matrix which will be more understandable
                   7879:        even is we still don't want to manage dictionary of variables
                   7880:     */
                   7881:     for(itimes=1;itimes<=2;itimes++){
                   7882:       jj=0;
                   7883:       for(i=1; i <=nlstate; i++){
                   7884:        for(j=1; j <=nlstate+ndeath; j++){
                   7885:          if(j==i) continue;
                   7886:          for(k=1; k<=ncovmodel;k++){
                   7887:            jj++;
                   7888:            ca[0]= k+'a'-1;ca[1]='\0';
                   7889:            if(itimes==1){
                   7890:              if(mle>=1)
                   7891:                printf("#%1d%1d%d",i,j,k);
                   7892:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7893:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7894:            }else{
                   7895:              if(mle>=1)
                   7896:                printf("%1d%1d%d",i,j,k);
                   7897:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7898:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7899:            }
                   7900:            ll=0;
                   7901:            for(li=1;li <=nlstate; li++){
                   7902:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7903:                if(lj==li) continue;
                   7904:                for(lk=1;lk<=ncovmodel;lk++){
                   7905:                  ll++;
                   7906:                  if(ll<=jj){
                   7907:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7908:                    if(ll<jj){
                   7909:                      if(itimes==1){
                   7910:                        if(mle>=1)
                   7911:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7912:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7913:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7914:                      }else{
                   7915:                        if(mle>=1)
                   7916:                          printf(" %.5e",matcov[jj][ll]); 
                   7917:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7918:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7919:                      }
                   7920:                    }else{
                   7921:                      if(itimes==1){
                   7922:                        if(mle>=1)
                   7923:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7924:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7925:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7926:                      }else{
                   7927:                        if(mle>=1)
1.203     brouard  7928:                          printf(" %.7e",matcov[jj][ll]); 
                   7929:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   7930:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  7931:                      }
                   7932:                    }
                   7933:                  }
                   7934:                } /* end lk */
                   7935:              } /* end lj */
                   7936:            } /* end li */
                   7937:            if(mle>=1)
                   7938:              printf("\n");
                   7939:            fprintf(ficlog,"\n");
                   7940:            fprintf(ficres,"\n");
                   7941:            numlinepar++;
                   7942:          } /* end k*/
                   7943:        } /*end j */
                   7944:       } /* end i */
                   7945:     } /* end itimes */
                   7946:     
                   7947:     fflush(ficlog);
                   7948:     fflush(ficres);
1.209     brouard  7949:       while(fgets(line, MAXLINE, ficpar)) {
                   7950:     /* If line starts with a # it is a comment */
                   7951:     if (line[0] == '#') {
                   7952:       numlinepar++;
1.141     brouard  7953:       fputs(line,stdout);
1.126     brouard  7954:       fputs(line,ficparo);
1.209     brouard  7955:       fputs(line,ficlog);
                   7956:       continue;
                   7957:     }else
                   7958:       break;
                   7959:   }
                   7960: 
                   7961:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   7962:     /*   ungetc(c,ficpar); */
                   7963:     /*   fgets(line, MAXLINE, ficpar); */
                   7964:     /*   fputs(line,stdout); */
                   7965:     /*   fputs(line,ficparo); */
                   7966:     /* } */
                   7967:     /* ungetc(c,ficpar); */
1.126     brouard  7968:     
                   7969:     estepm=0;
1.209     brouard  7970:     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){
                   7971: 
                   7972:     if (num_filled != 6) {
                   7973:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
                   7974:       printf("but line=%s\n",line);
                   7975:       goto end;
                   7976:     }
                   7977:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   7978:   }
                   7979:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   7980:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   7981: 
                   7982:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  7983:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7984:     if (fage <= 2) {
                   7985:       bage = ageminpar;
                   7986:       fage = agemaxpar;
                   7987:     }
                   7988:     
                   7989:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7990:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7991:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7992: 
                   7993:     /* Other stuffs, more or less useful */    
1.126     brouard  7994:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7995:       ungetc(c,ficpar);
                   7996:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7997:       fputs(line,stdout);
1.126     brouard  7998:       fputs(line,ficparo);
                   7999:     }
                   8000:     ungetc(c,ficpar);
                   8001:     
                   8002:     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);
                   8003:     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);
                   8004:     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);
                   8005:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   8006:     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);
                   8007:     
                   8008:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8009:       ungetc(c,ficpar);
                   8010:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8011:       fputs(line,stdout);
1.126     brouard  8012:       fputs(line,ficparo);
                   8013:     }
                   8014:     ungetc(c,ficpar);
                   8015:     
                   8016:     
                   8017:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   8018:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   8019:     
                   8020:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  8021:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  8022:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   8023:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   8024:     
                   8025:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8026:       ungetc(c,ficpar);
                   8027:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8028:       fputs(line,stdout);
1.126     brouard  8029:       fputs(line,ficparo);
                   8030:     }
                   8031:     ungetc(c,ficpar);
                   8032:     
                   8033:     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);
                   8034:     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);
                   8035:     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);
                   8036:     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);
                   8037:     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);
                   8038:     /* day and month of proj2 are not used but only year anproj2.*/
                   8039:     
                   8040:     
                   8041:     
1.145     brouard  8042:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8043:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8044:     
                   8045:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8046:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8047:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8048: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8049: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8050:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8051: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8052: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8053:     }else
1.201     brouard  8054:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  8055:     
1.201     brouard  8056:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  8057:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   8058:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   8059:       
                   8060:    /*------------ free_vector  -------------*/
                   8061:    /*  chdir(path); */
                   8062:  
                   8063:     free_ivector(wav,1,imx);
                   8064:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   8065:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   8066:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   8067:     free_lvector(num,1,n);
                   8068:     free_vector(agedc,1,n);
                   8069:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8070:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8071:     fclose(ficparo);
                   8072:     fclose(ficres);
                   8073: 
                   8074: 
1.186     brouard  8075:     /* Other results (useful)*/
                   8076: 
                   8077: 
1.126     brouard  8078:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8079:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8080:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  8081:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  8082:     fclose(ficrespl);
                   8083: 
1.145     brouard  8084: #ifdef FREEEXIT2
                   8085: #include "freeexit2.h"
                   8086: #endif
                   8087: 
1.126     brouard  8088:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8089:     /*#include "hpijx.h"*/
                   8090:     hPijx(p, bage, fage);
1.145     brouard  8091:     fclose(ficrespij);
1.126     brouard  8092: 
1.145     brouard  8093:   /*-------------- Variance of one-step probabilities---*/
                   8094:     k=1;
1.126     brouard  8095:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8096: 
                   8097: 
                   8098:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8099:     for(i=1;i<=AGESUP;i++)
                   8100:       for(j=1;j<=NCOVMAX;j++)
                   8101:        for(k=1;k<=NCOVMAX;k++)
                   8102:          probs[i][j][k]=0.;
                   8103: 
                   8104:     /*---------- Forecasting ------------------*/
                   8105:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8106:     if(prevfcast==1){
                   8107:       /*    if(stepm ==1){*/
1.201     brouard  8108:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8109:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8110:       /*      }  */
                   8111:       /*      else{ */
                   8112:       /*        erreur=108; */
                   8113:       /*        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); */
                   8114:       /*        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); */
                   8115:       /*      } */
                   8116:     }
1.186     brouard  8117:  
                   8118:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8119: 
1.127     brouard  8120:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8121: 
                   8122:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8123:     /*  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",\
                   8124:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8125:     */
1.126     brouard  8126: 
1.127     brouard  8127:     if (mobilav!=0) {
                   8128:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8129:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8130:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8131:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8132:       }
1.126     brouard  8133:     }
                   8134: 
                   8135: 
1.127     brouard  8136:     /*---------- Health expectancies, no variances ------------*/
                   8137: 
1.201     brouard  8138:     strcpy(filerese,"E_");
                   8139:     strcat(filerese,fileresu);
1.126     brouard  8140:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8141:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8142:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8143:     }
1.208     brouard  8144:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   8145:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8146:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8147:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8148:           
                   8149:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8150:        fprintf(ficreseij,"\n#****** ");
                   8151:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8152:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8153:        }
                   8154:        fprintf(ficreseij,"******\n");
                   8155: 
                   8156:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8157:        oldm=oldms;savm=savms;
                   8158:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8159:       
                   8160:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8161:       /*}*/
1.127     brouard  8162:     }
                   8163:     fclose(ficreseij);
1.208     brouard  8164:     printf("done evsij\n");fflush(stdout);
                   8165:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8166: 
                   8167:     /*---------- Health expectancies and variances ------------*/
                   8168: 
                   8169: 
1.201     brouard  8170:     strcpy(filerest,"T_");
                   8171:     strcat(filerest,fileresu);
1.127     brouard  8172:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8173:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8174:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8175:     }
1.208     brouard  8176:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   8177:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8178: 
1.126     brouard  8179: 
1.201     brouard  8180:     strcpy(fileresstde,"STDE_");
                   8181:     strcat(fileresstde,fileresu);
1.126     brouard  8182:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8183:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8184:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8185:     }
1.208     brouard  8186:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8187:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8188: 
1.201     brouard  8189:     strcpy(filerescve,"CVE_");
                   8190:     strcat(filerescve,fileresu);
1.126     brouard  8191:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8192:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8193:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8194:     }
1.208     brouard  8195:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8196:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8197: 
1.201     brouard  8198:     strcpy(fileresv,"V_");
                   8199:     strcat(fileresv,fileresu);
1.126     brouard  8200:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8201:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8202:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8203:     }
1.208     brouard  8204:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   8205:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  8206: 
1.145     brouard  8207:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8208:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8209:           
                   8210:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  8211:       fprintf(ficrest,"\n#****** ");
                   8212:       for(j=1;j<=cptcoveff;j++) 
                   8213:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8214:       fprintf(ficrest,"******\n");
                   8215:       
                   8216:       fprintf(ficresstdeij,"\n#****** ");
                   8217:       fprintf(ficrescveij,"\n#****** ");
                   8218:       for(j=1;j<=cptcoveff;j++) {
                   8219:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8220:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8221:       }
                   8222:       fprintf(ficresstdeij,"******\n");
                   8223:       fprintf(ficrescveij,"******\n");
                   8224:       
                   8225:       fprintf(ficresvij,"\n#****** ");
                   8226:       for(j=1;j<=cptcoveff;j++) 
                   8227:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8228:       fprintf(ficresvij,"******\n");
                   8229:       
                   8230:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8231:       oldm=oldms;savm=savms;
                   8232:       printf(" cvevsij %d, ",k);
                   8233:       fprintf(ficlog, " cvevsij %d, ",k);
                   8234:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   8235:       printf(" end cvevsij \n ");
                   8236:       fprintf(ficlog, " end cvevsij \n ");
                   8237:       
                   8238:       /*
                   8239:        */
                   8240:       /* goto endfree; */
                   8241:       
                   8242:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8243:       pstamp(ficrest);
                   8244:       
                   8245:       
                   8246:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8247:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   8248:        cptcod= 0; /* To be deleted */
                   8249:        printf("varevsij %d \n",vpopbased);
                   8250:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209     brouard  8251:        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  8252:        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 ");
                   8253:        if(vpopbased==1)
                   8254:          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);
                   8255:        else
                   8256:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   8257:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   8258:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8259:        fprintf(ficrest,"\n");
                   8260:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   8261:        epj=vector(1,nlstate+1);
                   8262:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   8263:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   8264:        for(age=bage; age <=fage ;age++){
1.209     brouard  8265:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  8266:          if (vpopbased==1) {
                   8267:            if(mobilav ==0){
                   8268:              for(i=1; i<=nlstate;i++)
                   8269:                prlim[i][i]=probs[(int)age][i][k];
                   8270:            }else{ /* mobilav */ 
                   8271:              for(i=1; i<=nlstate;i++)
                   8272:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8273:            }
1.208     brouard  8274:          }
                   8275:          
                   8276:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   8277:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   8278:          /* printf(" age %4.0f ",age); */
                   8279:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8280:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8281:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   8282:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8283:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8284:            }
1.208     brouard  8285:            epj[nlstate+1] +=epj[j];
                   8286:          }
                   8287:          /* printf(" age %4.0f \n",age); */
                   8288:          
                   8289:          for(i=1, vepp=0.;i <=nlstate;i++)
                   8290:            for(j=1;j <=nlstate;j++)
                   8291:              vepp += vareij[i][j][(int)age];
                   8292:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8293:          for(j=1;j <=nlstate;j++){
                   8294:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8295:          }
1.208     brouard  8296:          fprintf(ficrest,"\n");
1.126     brouard  8297:        }
1.208     brouard  8298:       } /* End vpopbased */
                   8299:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8300:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8301:       free_vector(epj,1,nlstate+1);
                   8302:       printf("done \n");fflush(stdout);
                   8303:       fprintf(ficlog,"done\n");fflush(ficlog);
                   8304:       
1.145     brouard  8305:       /*}*/
1.208     brouard  8306:     } /* End k */
1.126     brouard  8307:     free_vector(weight,1,n);
1.145     brouard  8308:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8309:     free_imatrix(s,1,maxwav+1,1,n);
                   8310:     free_matrix(anint,1,maxwav,1,n); 
                   8311:     free_matrix(mint,1,maxwav,1,n);
                   8312:     free_ivector(cod,1,n);
                   8313:     free_ivector(tab,1,NCOVMAX);
                   8314:     fclose(ficresstdeij);
                   8315:     fclose(ficrescveij);
                   8316:     fclose(ficresvij);
                   8317:     fclose(ficrest);
1.208     brouard  8318:     printf("done Health expectancies\n");fflush(stdout);
                   8319:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8320:     fclose(ficpar);
                   8321:   
                   8322:     /*------- Variance of period (stable) prevalence------*/   
                   8323: 
1.201     brouard  8324:     strcpy(fileresvpl,"VPL_");
                   8325:     strcat(fileresvpl,fileresu);
1.126     brouard  8326:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8327:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8328:       exit(0);
                   8329:     }
1.208     brouard  8330:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8331:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8332: 
1.145     brouard  8333:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8334:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8335:           
                   8336:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8337:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8338:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8339:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8340:        fprintf(ficresvpl,"******\n");
                   8341:       
                   8342:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8343:        oldm=oldms;savm=savms;
1.209     brouard  8344:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  8345:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8346:       /*}*/
1.126     brouard  8347:     }
                   8348: 
                   8349:     fclose(ficresvpl);
1.208     brouard  8350:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   8351:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8352: 
                   8353:     /*---------- End : free ----------------*/
                   8354:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8355:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8356:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8357:  /* endfree:*/
1.141     brouard  8358:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8359:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8360:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8361:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8362:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8363:     free_matrix(covar,0,NCOVMAX,1,n);
                   8364:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8365:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8366:     /*free_vector(delti,1,npar);*/
                   8367:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8368:     free_matrix(agev,1,maxwav,1,imx);
                   8369:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8370: 
1.145     brouard  8371:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8372:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8373:     free_ivector(Tvar,1,NCOVMAX);
                   8374:     free_ivector(Tprod,1,NCOVMAX);
                   8375:     free_ivector(Tvaraff,1,NCOVMAX);
                   8376:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8377: 
                   8378:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8379:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8380:   fflush(fichtm);
                   8381:   fflush(ficgp);
                   8382:   
                   8383: 
                   8384:   if((nberr >0) || (nbwarn>0)){
                   8385:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8386:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8387:   }else{
                   8388:     printf("End of Imach\n");
                   8389:     fprintf(ficlog,"End of Imach\n");
                   8390:   }
                   8391:   printf("See log file on %s\n",filelog);
                   8392:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8393:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8394:   rend_time = time(NULL);  
                   8395:   end_time = *localtime(&rend_time);
                   8396:   /* tml = *localtime(&end_time.tm_sec); */
                   8397:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8398:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8399:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8400:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8401: 
1.157     brouard  8402:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8403:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8404:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8405:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8406: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8407:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8408:   fclose(fichtm);
                   8409:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8410:   fclose(fichtmcov);
                   8411:   fclose(ficgp);
                   8412:   fclose(ficlog);
                   8413:   /*------ End -----------*/
                   8414: 
                   8415: 
                   8416:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8417: #ifdef WIN32
                   8418:    if (_chdir(pathcd) != 0)
                   8419:           printf("Can't move to directory %s!\n",path);
                   8420:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8421: #else
1.126     brouard  8422:    if(chdir(pathcd) != 0)
1.184     brouard  8423:           printf("Can't move to directory %s!\n", path);
                   8424:    if (getcwd(pathcd, MAXLINE) > 0)
                   8425: #endif 
1.126     brouard  8426:     printf("Current directory %s!\n",pathcd);
                   8427:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8428:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8429: #ifdef _WIN32
1.126     brouard  8430:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8431: #endif
                   8432:   if(!stat(plotcmd,&info)){
1.158     brouard  8433:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8434:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8435:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8436:     }else
                   8437:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8438: #ifdef __unix
1.126     brouard  8439:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8440:     if(!stat(plotcmd,&info)){
1.158     brouard  8441:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8442:     }else
                   8443:       strcpy(pplotcmd,plotcmd);
                   8444: #endif
                   8445:   }else
                   8446:     strcpy(pplotcmd,plotcmd);
                   8447:   
                   8448:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8449:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8450: 
                   8451:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8452:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8453:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8454:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8455:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8456:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8457:   }
1.158     brouard  8458:   printf(" Successful, please wait...");
1.126     brouard  8459:   while (z[0] != 'q') {
                   8460:     /* chdir(path); */
1.154     brouard  8461:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8462:     scanf("%s",z);
                   8463: /*     if (z[0] == 'c') system("./imach"); */
                   8464:     if (z[0] == 'e') {
1.158     brouard  8465: #ifdef __APPLE__
1.152     brouard  8466:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8467: #elif __linux
                   8468:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8469: #else
1.152     brouard  8470:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8471: #endif
                   8472:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8473:       system(pplotcmd);
1.126     brouard  8474:     }
                   8475:     else if (z[0] == 'g') system(plotcmd);
                   8476:     else if (z[0] == 'q') exit(0);
                   8477:   }
                   8478:   end:
                   8479:   while (z[0] != 'q') {
1.195     brouard  8480:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8481:     scanf("%s",z);
                   8482:   }
                   8483: }

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