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

1.204   ! brouard     1: /* $Id: imach.c,v 1.203 2015/09/30 17:45:14 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.204   ! brouard     4:   Revision 1.203  2015/09/30 17:45:14  brouard
        !             5:   Summary: looking at better estimation of the hessian
        !             6: 
        !             7:   Also a better criteria for convergence to the period prevalence And
        !             8:   therefore adding the number of years needed to converge. (The
        !             9:   prevalence in any alive state shold sum to one
        !            10: 
1.203     brouard    11:   Revision 1.202  2015/09/22 19:45:16  brouard
                     12:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     13: 
1.202     brouard    14:   Revision 1.201  2015/09/15 17:34:58  brouard
                     15:   Summary: 0.98r0
                     16: 
                     17:   - Some new graphs like suvival functions
                     18:   - Some bugs fixed like model=1+age+V2.
                     19: 
1.201     brouard    20:   Revision 1.200  2015/09/09 16:53:55  brouard
                     21:   Summary: Big bug thanks to Flavia
                     22: 
                     23:   Even model=1+age+V2. did not work anymore
                     24: 
1.200     brouard    25:   Revision 1.199  2015/09/07 14:09:23  brouard
                     26:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     27: 
1.199     brouard    28:   Revision 1.198  2015/09/03 07:14:39  brouard
                     29:   Summary: 0.98q5 Flavia
                     30: 
1.198     brouard    31:   Revision 1.197  2015/09/01 18:24:39  brouard
                     32:   *** empty log message ***
                     33: 
1.197     brouard    34:   Revision 1.196  2015/08/18 23:17:52  brouard
                     35:   Summary: 0.98q5
                     36: 
1.196     brouard    37:   Revision 1.195  2015/08/18 16:28:39  brouard
                     38:   Summary: Adding a hack for testing purpose
                     39: 
                     40:   After reading the title, ftol and model lines, if the comment line has
                     41:   a q, starting with #q, the answer at the end of the run is quit. It
                     42:   permits to run test files in batch with ctest. The former workaround was
                     43:   $ echo q | imach foo.imach
                     44: 
1.195     brouard    45:   Revision 1.194  2015/08/18 13:32:00  brouard
                     46:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     47: 
1.194     brouard    48:   Revision 1.193  2015/08/04 07:17:42  brouard
                     49:   Summary: 0.98q4
                     50: 
1.193     brouard    51:   Revision 1.192  2015/07/16 16:49:02  brouard
                     52:   Summary: Fixing some outputs
                     53: 
1.192     brouard    54:   Revision 1.191  2015/07/14 10:00:33  brouard
                     55:   Summary: Some fixes
                     56: 
1.191     brouard    57:   Revision 1.190  2015/05/05 08:51:13  brouard
                     58:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     59: 
                     60:   Fix 1+age+.
                     61: 
1.190     brouard    62:   Revision 1.189  2015/04/30 14:45:16  brouard
                     63:   Summary: 0.98q2
                     64: 
1.189     brouard    65:   Revision 1.188  2015/04/30 08:27:53  brouard
                     66:   *** empty log message ***
                     67: 
1.188     brouard    68:   Revision 1.187  2015/04/29 09:11:15  brouard
                     69:   *** empty log message ***
                     70: 
1.187     brouard    71:   Revision 1.186  2015/04/23 12:01:52  brouard
                     72:   Summary: V1*age is working now, version 0.98q1
                     73: 
                     74:   Some codes had been disabled in order to simplify and Vn*age was
                     75:   working in the optimization phase, ie, giving correct MLE parameters,
                     76:   but, as usual, outputs were not correct and program core dumped.
                     77: 
1.186     brouard    78:   Revision 1.185  2015/03/11 13:26:42  brouard
                     79:   Summary: Inclusion of compile and links command line for Intel Compiler
                     80: 
1.185     brouard    81:   Revision 1.184  2015/03/11 11:52:39  brouard
                     82:   Summary: Back from Windows 8. Intel Compiler
                     83: 
1.184     brouard    84:   Revision 1.183  2015/03/10 20:34:32  brouard
                     85:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     86: 
                     87:   We use directest instead of original Powell test; probably no
                     88:   incidence on the results, but better justifications;
                     89:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     90:   wrong results.
                     91: 
1.183     brouard    92:   Revision 1.182  2015/02/12 08:19:57  brouard
                     93:   Summary: Trying to keep directest which seems simpler and more general
                     94:   Author: Nicolas Brouard
                     95: 
1.182     brouard    96:   Revision 1.181  2015/02/11 23:22:24  brouard
                     97:   Summary: Comments on Powell added
                     98: 
                     99:   Author:
                    100: 
1.181     brouard   101:   Revision 1.180  2015/02/11 17:33:45  brouard
                    102:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    103: 
1.180     brouard   104:   Revision 1.179  2015/01/04 09:57:06  brouard
                    105:   Summary: back to OS/X
                    106: 
1.179     brouard   107:   Revision 1.178  2015/01/04 09:35:48  brouard
                    108:   *** empty log message ***
                    109: 
1.178     brouard   110:   Revision 1.177  2015/01/03 18:40:56  brouard
                    111:   Summary: Still testing ilc32 on OSX
                    112: 
1.177     brouard   113:   Revision 1.176  2015/01/03 16:45:04  brouard
                    114:   *** empty log message ***
                    115: 
1.176     brouard   116:   Revision 1.175  2015/01/03 16:33:42  brouard
                    117:   *** empty log message ***
                    118: 
1.175     brouard   119:   Revision 1.174  2015/01/03 16:15:49  brouard
                    120:   Summary: Still in cross-compilation
                    121: 
1.174     brouard   122:   Revision 1.173  2015/01/03 12:06:26  brouard
                    123:   Summary: trying to detect cross-compilation
                    124: 
1.173     brouard   125:   Revision 1.172  2014/12/27 12:07:47  brouard
                    126:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    127: 
1.172     brouard   128:   Revision 1.171  2014/12/23 13:26:59  brouard
                    129:   Summary: Back from Visual C
                    130: 
                    131:   Still problem with utsname.h on Windows
                    132: 
1.171     brouard   133:   Revision 1.170  2014/12/23 11:17:12  brouard
                    134:   Summary: Cleaning some \%% back to %%
                    135: 
                    136:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    137: 
1.170     brouard   138:   Revision 1.169  2014/12/22 23:08:31  brouard
                    139:   Summary: 0.98p
                    140: 
                    141:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    142: 
1.169     brouard   143:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   144:   Summary: update
1.169     brouard   145: 
1.168     brouard   146:   Revision 1.167  2014/12/22 13:50:56  brouard
                    147:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    148: 
                    149:   Testing on Linux 64
                    150: 
1.167     brouard   151:   Revision 1.166  2014/12/22 11:40:47  brouard
                    152:   *** empty log message ***
                    153: 
1.166     brouard   154:   Revision 1.165  2014/12/16 11:20:36  brouard
                    155:   Summary: After compiling on Visual C
                    156: 
                    157:   * imach.c (Module): Merging 1.61 to 1.162
                    158: 
1.165     brouard   159:   Revision 1.164  2014/12/16 10:52:11  brouard
                    160:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    161: 
                    162:   * imach.c (Module): Merging 1.61 to 1.162
                    163: 
1.164     brouard   164:   Revision 1.163  2014/12/16 10:30:11  brouard
                    165:   * imach.c (Module): Merging 1.61 to 1.162
                    166: 
1.163     brouard   167:   Revision 1.162  2014/09/25 11:43:39  brouard
                    168:   Summary: temporary backup 0.99!
                    169: 
1.162     brouard   170:   Revision 1.1  2014/09/16 11:06:58  brouard
                    171:   Summary: With some code (wrong) for nlopt
                    172: 
                    173:   Author:
                    174: 
                    175:   Revision 1.161  2014/09/15 20:41:41  brouard
                    176:   Summary: Problem with macro SQR on Intel compiler
                    177: 
1.161     brouard   178:   Revision 1.160  2014/09/02 09:24:05  brouard
                    179:   *** empty log message ***
                    180: 
1.160     brouard   181:   Revision 1.159  2014/09/01 10:34:10  brouard
                    182:   Summary: WIN32
                    183:   Author: Brouard
                    184: 
1.159     brouard   185:   Revision 1.158  2014/08/27 17:11:51  brouard
                    186:   *** empty log message ***
                    187: 
1.158     brouard   188:   Revision 1.157  2014/08/27 16:26:55  brouard
                    189:   Summary: Preparing windows Visual studio version
                    190:   Author: Brouard
                    191: 
                    192:   In order to compile on Visual studio, time.h is now correct and time_t
                    193:   and tm struct should be used. difftime should be used but sometimes I
                    194:   just make the differences in raw time format (time(&now).
                    195:   Trying to suppress #ifdef LINUX
                    196:   Add xdg-open for __linux in order to open default browser.
                    197: 
1.157     brouard   198:   Revision 1.156  2014/08/25 20:10:10  brouard
                    199:   *** empty log message ***
                    200: 
1.156     brouard   201:   Revision 1.155  2014/08/25 18:32:34  brouard
                    202:   Summary: New compile, minor changes
                    203:   Author: Brouard
                    204: 
1.155     brouard   205:   Revision 1.154  2014/06/20 17:32:08  brouard
                    206:   Summary: Outputs now all graphs of convergence to period prevalence
                    207: 
1.154     brouard   208:   Revision 1.153  2014/06/20 16:45:46  brouard
                    209:   Summary: If 3 live state, convergence to period prevalence on same graph
                    210:   Author: Brouard
                    211: 
1.153     brouard   212:   Revision 1.152  2014/06/18 17:54:09  brouard
                    213:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    214: 
1.152     brouard   215:   Revision 1.151  2014/06/18 16:43:30  brouard
                    216:   *** empty log message ***
                    217: 
1.151     brouard   218:   Revision 1.150  2014/06/18 16:42:35  brouard
                    219:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    220:   Author: brouard
                    221: 
1.150     brouard   222:   Revision 1.149  2014/06/18 15:51:14  brouard
                    223:   Summary: Some fixes in parameter files errors
                    224:   Author: Nicolas Brouard
                    225: 
1.149     brouard   226:   Revision 1.148  2014/06/17 17:38:48  brouard
                    227:   Summary: Nothing new
                    228:   Author: Brouard
                    229: 
                    230:   Just a new packaging for OS/X version 0.98nS
                    231: 
1.148     brouard   232:   Revision 1.147  2014/06/16 10:33:11  brouard
                    233:   *** empty log message ***
                    234: 
1.147     brouard   235:   Revision 1.146  2014/06/16 10:20:28  brouard
                    236:   Summary: Merge
                    237:   Author: Brouard
                    238: 
                    239:   Merge, before building revised version.
                    240: 
1.146     brouard   241:   Revision 1.145  2014/06/10 21:23:15  brouard
                    242:   Summary: Debugging with valgrind
                    243:   Author: Nicolas Brouard
                    244: 
                    245:   Lot of changes in order to output the results with some covariates
                    246:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    247:   improve the code.
                    248:   No more memory valgrind error but a lot has to be done in order to
                    249:   continue the work of splitting the code into subroutines.
                    250:   Also, decodemodel has been improved. Tricode is still not
                    251:   optimal. nbcode should be improved. Documentation has been added in
                    252:   the source code.
                    253: 
1.144     brouard   254:   Revision 1.143  2014/01/26 09:45:38  brouard
                    255:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    256: 
                    257:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    258:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    259: 
1.143     brouard   260:   Revision 1.142  2014/01/26 03:57:36  brouard
                    261:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    262: 
                    263:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    264: 
1.142     brouard   265:   Revision 1.141  2014/01/26 02:42:01  brouard
                    266:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    267: 
1.141     brouard   268:   Revision 1.140  2011/09/02 10:37:54  brouard
                    269:   Summary: times.h is ok with mingw32 now.
                    270: 
1.140     brouard   271:   Revision 1.139  2010/06/14 07:50:17  brouard
                    272:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    273:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    274: 
1.139     brouard   275:   Revision 1.138  2010/04/30 18:19:40  brouard
                    276:   *** empty log message ***
                    277: 
1.138     brouard   278:   Revision 1.137  2010/04/29 18:11:38  brouard
                    279:   (Module): Checking covariates for more complex models
                    280:   than V1+V2. A lot of change to be done. Unstable.
                    281: 
1.137     brouard   282:   Revision 1.136  2010/04/26 20:30:53  brouard
                    283:   (Module): merging some libgsl code. Fixing computation
                    284:   of likelione (using inter/intrapolation if mle = 0) in order to
                    285:   get same likelihood as if mle=1.
                    286:   Some cleaning of code and comments added.
                    287: 
1.136     brouard   288:   Revision 1.135  2009/10/29 15:33:14  brouard
                    289:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    290: 
1.135     brouard   291:   Revision 1.134  2009/10/29 13:18:53  brouard
                    292:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    293: 
1.134     brouard   294:   Revision 1.133  2009/07/06 10:21:25  brouard
                    295:   just nforces
                    296: 
1.133     brouard   297:   Revision 1.132  2009/07/06 08:22:05  brouard
                    298:   Many tings
                    299: 
1.132     brouard   300:   Revision 1.131  2009/06/20 16:22:47  brouard
                    301:   Some dimensions resccaled
                    302: 
1.131     brouard   303:   Revision 1.130  2009/05/26 06:44:34  brouard
                    304:   (Module): Max Covariate is now set to 20 instead of 8. A
                    305:   lot of cleaning with variables initialized to 0. Trying to make
                    306:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    307: 
1.130     brouard   308:   Revision 1.129  2007/08/31 13:49:27  lievre
                    309:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    310: 
1.129     lievre    311:   Revision 1.128  2006/06/30 13:02:05  brouard
                    312:   (Module): Clarifications on computing e.j
                    313: 
1.128     brouard   314:   Revision 1.127  2006/04/28 18:11:50  brouard
                    315:   (Module): Yes the sum of survivors was wrong since
                    316:   imach-114 because nhstepm was no more computed in the age
                    317:   loop. Now we define nhstepma in the age loop.
                    318:   (Module): In order to speed up (in case of numerous covariates) we
                    319:   compute health expectancies (without variances) in a first step
                    320:   and then all the health expectancies with variances or standard
                    321:   deviation (needs data from the Hessian matrices) which slows the
                    322:   computation.
                    323:   In the future we should be able to stop the program is only health
                    324:   expectancies and graph are needed without standard deviations.
                    325: 
1.127     brouard   326:   Revision 1.126  2006/04/28 17:23:28  brouard
                    327:   (Module): Yes the sum of survivors was wrong since
                    328:   imach-114 because nhstepm was no more computed in the age
                    329:   loop. Now we define nhstepma in the age loop.
                    330:   Version 0.98h
                    331: 
1.126     brouard   332:   Revision 1.125  2006/04/04 15:20:31  lievre
                    333:   Errors in calculation of health expectancies. Age was not initialized.
                    334:   Forecasting file added.
                    335: 
                    336:   Revision 1.124  2006/03/22 17:13:53  lievre
                    337:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    338:   The log-likelihood is printed in the log file
                    339: 
                    340:   Revision 1.123  2006/03/20 10:52:43  brouard
                    341:   * imach.c (Module): <title> changed, corresponds to .htm file
                    342:   name. <head> headers where missing.
                    343: 
                    344:   * imach.c (Module): Weights can have a decimal point as for
                    345:   English (a comma might work with a correct LC_NUMERIC environment,
                    346:   otherwise the weight is truncated).
                    347:   Modification of warning when the covariates values are not 0 or
                    348:   1.
                    349:   Version 0.98g
                    350: 
                    351:   Revision 1.122  2006/03/20 09:45:41  brouard
                    352:   (Module): Weights can have a decimal point as for
                    353:   English (a comma might work with a correct LC_NUMERIC environment,
                    354:   otherwise the weight is truncated).
                    355:   Modification of warning when the covariates values are not 0 or
                    356:   1.
                    357:   Version 0.98g
                    358: 
                    359:   Revision 1.121  2006/03/16 17:45:01  lievre
                    360:   * imach.c (Module): Comments concerning covariates added
                    361: 
                    362:   * imach.c (Module): refinements in the computation of lli if
                    363:   status=-2 in order to have more reliable computation if stepm is
                    364:   not 1 month. Version 0.98f
                    365: 
                    366:   Revision 1.120  2006/03/16 15:10:38  lievre
                    367:   (Module): refinements in the computation of lli if
                    368:   status=-2 in order to have more reliable computation if stepm is
                    369:   not 1 month. Version 0.98f
                    370: 
                    371:   Revision 1.119  2006/03/15 17:42:26  brouard
                    372:   (Module): Bug if status = -2, the loglikelihood was
                    373:   computed as likelihood omitting the logarithm. Version O.98e
                    374: 
                    375:   Revision 1.118  2006/03/14 18:20:07  brouard
                    376:   (Module): varevsij Comments added explaining the second
                    377:   table of variances if popbased=1 .
                    378:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    379:   (Module): Function pstamp added
                    380:   (Module): Version 0.98d
                    381: 
                    382:   Revision 1.117  2006/03/14 17:16:22  brouard
                    383:   (Module): varevsij Comments added explaining the second
                    384:   table of variances if popbased=1 .
                    385:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    386:   (Module): Function pstamp added
                    387:   (Module): Version 0.98d
                    388: 
                    389:   Revision 1.116  2006/03/06 10:29:27  brouard
                    390:   (Module): Variance-covariance wrong links and
                    391:   varian-covariance of ej. is needed (Saito).
                    392: 
                    393:   Revision 1.115  2006/02/27 12:17:45  brouard
                    394:   (Module): One freematrix added in mlikeli! 0.98c
                    395: 
                    396:   Revision 1.114  2006/02/26 12:57:58  brouard
                    397:   (Module): Some improvements in processing parameter
                    398:   filename with strsep.
                    399: 
                    400:   Revision 1.113  2006/02/24 14:20:24  brouard
                    401:   (Module): Memory leaks checks with valgrind and:
                    402:   datafile was not closed, some imatrix were not freed and on matrix
                    403:   allocation too.
                    404: 
                    405:   Revision 1.112  2006/01/30 09:55:26  brouard
                    406:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    407: 
                    408:   Revision 1.111  2006/01/25 20:38:18  brouard
                    409:   (Module): Lots of cleaning and bugs added (Gompertz)
                    410:   (Module): Comments can be added in data file. Missing date values
                    411:   can be a simple dot '.'.
                    412: 
                    413:   Revision 1.110  2006/01/25 00:51:50  brouard
                    414:   (Module): Lots of cleaning and bugs added (Gompertz)
                    415: 
                    416:   Revision 1.109  2006/01/24 19:37:15  brouard
                    417:   (Module): Comments (lines starting with a #) are allowed in data.
                    418: 
                    419:   Revision 1.108  2006/01/19 18:05:42  lievre
                    420:   Gnuplot problem appeared...
                    421:   To be fixed
                    422: 
                    423:   Revision 1.107  2006/01/19 16:20:37  brouard
                    424:   Test existence of gnuplot in imach path
                    425: 
                    426:   Revision 1.106  2006/01/19 13:24:36  brouard
                    427:   Some cleaning and links added in html output
                    428: 
                    429:   Revision 1.105  2006/01/05 20:23:19  lievre
                    430:   *** empty log message ***
                    431: 
                    432:   Revision 1.104  2005/09/30 16:11:43  lievre
                    433:   (Module): sump fixed, loop imx fixed, and simplifications.
                    434:   (Module): If the status is missing at the last wave but we know
                    435:   that the person is alive, then we can code his/her status as -2
                    436:   (instead of missing=-1 in earlier versions) and his/her
                    437:   contributions to the likelihood is 1 - Prob of dying from last
                    438:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    439:   the healthy state at last known wave). Version is 0.98
                    440: 
                    441:   Revision 1.103  2005/09/30 15:54:49  lievre
                    442:   (Module): sump fixed, loop imx fixed, and simplifications.
                    443: 
                    444:   Revision 1.102  2004/09/15 17:31:30  brouard
                    445:   Add the possibility to read data file including tab characters.
                    446: 
                    447:   Revision 1.101  2004/09/15 10:38:38  brouard
                    448:   Fix on curr_time
                    449: 
                    450:   Revision 1.100  2004/07/12 18:29:06  brouard
                    451:   Add version for Mac OS X. Just define UNIX in Makefile
                    452: 
                    453:   Revision 1.99  2004/06/05 08:57:40  brouard
                    454:   *** empty log message ***
                    455: 
                    456:   Revision 1.98  2004/05/16 15:05:56  brouard
                    457:   New version 0.97 . First attempt to estimate force of mortality
                    458:   directly from the data i.e. without the need of knowing the health
                    459:   state at each age, but using a Gompertz model: log u =a + b*age .
                    460:   This is the basic analysis of mortality and should be done before any
                    461:   other analysis, in order to test if the mortality estimated from the
                    462:   cross-longitudinal survey is different from the mortality estimated
                    463:   from other sources like vital statistic data.
                    464: 
                    465:   The same imach parameter file can be used but the option for mle should be -3.
                    466: 
1.133     brouard   467:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   468:   former routines in order to include the new code within the former code.
                    469: 
                    470:   The output is very simple: only an estimate of the intercept and of
                    471:   the slope with 95% confident intervals.
                    472: 
                    473:   Current limitations:
                    474:   A) Even if you enter covariates, i.e. with the
                    475:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    476:   B) There is no computation of Life Expectancy nor Life Table.
                    477: 
                    478:   Revision 1.97  2004/02/20 13:25:42  lievre
                    479:   Version 0.96d. Population forecasting command line is (temporarily)
                    480:   suppressed.
                    481: 
                    482:   Revision 1.96  2003/07/15 15:38:55  brouard
                    483:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    484:   rewritten within the same printf. Workaround: many printfs.
                    485: 
                    486:   Revision 1.95  2003/07/08 07:54:34  brouard
                    487:   * imach.c (Repository):
                    488:   (Repository): Using imachwizard code to output a more meaningful covariance
                    489:   matrix (cov(a12,c31) instead of numbers.
                    490: 
                    491:   Revision 1.94  2003/06/27 13:00:02  brouard
                    492:   Just cleaning
                    493: 
                    494:   Revision 1.93  2003/06/25 16:33:55  brouard
                    495:   (Module): On windows (cygwin) function asctime_r doesn't
                    496:   exist so I changed back to asctime which exists.
                    497:   (Module): Version 0.96b
                    498: 
                    499:   Revision 1.92  2003/06/25 16:30:45  brouard
                    500:   (Module): On windows (cygwin) function asctime_r doesn't
                    501:   exist so I changed back to asctime which exists.
                    502: 
                    503:   Revision 1.91  2003/06/25 15:30:29  brouard
                    504:   * imach.c (Repository): Duplicated warning errors corrected.
                    505:   (Repository): Elapsed time after each iteration is now output. It
                    506:   helps to forecast when convergence will be reached. Elapsed time
                    507:   is stamped in powell.  We created a new html file for the graphs
                    508:   concerning matrix of covariance. It has extension -cov.htm.
                    509: 
                    510:   Revision 1.90  2003/06/24 12:34:15  brouard
                    511:   (Module): Some bugs corrected for windows. Also, when
                    512:   mle=-1 a template is output in file "or"mypar.txt with the design
                    513:   of the covariance matrix to be input.
                    514: 
                    515:   Revision 1.89  2003/06/24 12:30:52  brouard
                    516:   (Module): Some bugs corrected for windows. Also, when
                    517:   mle=-1 a template is output in file "or"mypar.txt with the design
                    518:   of the covariance matrix to be input.
                    519: 
                    520:   Revision 1.88  2003/06/23 17:54:56  brouard
                    521:   * 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.
                    522: 
                    523:   Revision 1.87  2003/06/18 12:26:01  brouard
                    524:   Version 0.96
                    525: 
                    526:   Revision 1.86  2003/06/17 20:04:08  brouard
                    527:   (Module): Change position of html and gnuplot routines and added
                    528:   routine fileappend.
                    529: 
                    530:   Revision 1.85  2003/06/17 13:12:43  brouard
                    531:   * imach.c (Repository): Check when date of death was earlier that
                    532:   current date of interview. It may happen when the death was just
                    533:   prior to the death. In this case, dh was negative and likelihood
                    534:   was wrong (infinity). We still send an "Error" but patch by
                    535:   assuming that the date of death was just one stepm after the
                    536:   interview.
                    537:   (Repository): Because some people have very long ID (first column)
                    538:   we changed int to long in num[] and we added a new lvector for
                    539:   memory allocation. But we also truncated to 8 characters (left
                    540:   truncation)
                    541:   (Repository): No more line truncation errors.
                    542: 
                    543:   Revision 1.84  2003/06/13 21:44:43  brouard
                    544:   * imach.c (Repository): Replace "freqsummary" at a correct
                    545:   place. It differs from routine "prevalence" which may be called
                    546:   many times. Probs is memory consuming and must be used with
                    547:   parcimony.
                    548:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    549: 
                    550:   Revision 1.83  2003/06/10 13:39:11  lievre
                    551:   *** empty log message ***
                    552: 
                    553:   Revision 1.82  2003/06/05 15:57:20  brouard
                    554:   Add log in  imach.c and  fullversion number is now printed.
                    555: 
                    556: */
                    557: /*
                    558:    Interpolated Markov Chain
                    559: 
                    560:   Short summary of the programme:
                    561:   
                    562:   This program computes Healthy Life Expectancies from
                    563:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    564:   first survey ("cross") where individuals from different ages are
                    565:   interviewed on their health status or degree of disability (in the
                    566:   case of a health survey which is our main interest) -2- at least a
                    567:   second wave of interviews ("longitudinal") which measure each change
                    568:   (if any) in individual health status.  Health expectancies are
                    569:   computed from the time spent in each health state according to a
                    570:   model. More health states you consider, more time is necessary to reach the
                    571:   Maximum Likelihood of the parameters involved in the model.  The
                    572:   simplest model is the multinomial logistic model where pij is the
                    573:   probability to be observed in state j at the second wave
                    574:   conditional to be observed in state i at the first wave. Therefore
                    575:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    576:   'age' is age and 'sex' is a covariate. If you want to have a more
                    577:   complex model than "constant and age", you should modify the program
                    578:   where the markup *Covariates have to be included here again* invites
                    579:   you to do it.  More covariates you add, slower the
                    580:   convergence.
                    581: 
                    582:   The advantage of this computer programme, compared to a simple
                    583:   multinomial logistic model, is clear when the delay between waves is not
                    584:   identical for each individual. Also, if a individual missed an
                    585:   intermediate interview, the information is lost, but taken into
                    586:   account using an interpolation or extrapolation.  
                    587: 
                    588:   hPijx is the probability to be observed in state i at age x+h
                    589:   conditional to the observed state i at age x. The delay 'h' can be
                    590:   split into an exact number (nh*stepm) of unobserved intermediate
                    591:   states. This elementary transition (by month, quarter,
                    592:   semester or year) is modelled as a multinomial logistic.  The hPx
                    593:   matrix is simply the matrix product of nh*stepm elementary matrices
                    594:   and the contribution of each individual to the likelihood is simply
                    595:   hPijx.
                    596: 
                    597:   Also this programme outputs the covariance matrix of the parameters but also
                    598:   of the life expectancies. It also computes the period (stable) prevalence. 
                    599:   
1.133     brouard   600:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    601:            Institut national d'études démographiques, Paris.
1.126     brouard   602:   This software have been partly granted by Euro-REVES, a concerted action
                    603:   from the European Union.
                    604:   It is copyrighted identically to a GNU software product, ie programme and
                    605:   software can be distributed freely for non commercial use. Latest version
                    606:   can be accessed at http://euroreves.ined.fr/imach .
                    607: 
                    608:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    609:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    610:   
                    611:   **********************************************************************/
                    612: /*
                    613:   main
                    614:   read parameterfile
                    615:   read datafile
                    616:   concatwav
                    617:   freqsummary
                    618:   if (mle >= 1)
                    619:     mlikeli
                    620:   print results files
                    621:   if mle==1 
                    622:      computes hessian
                    623:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    624:       begin-prev-date,...
                    625:   open gnuplot file
                    626:   open html file
1.145     brouard   627:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    628:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    629:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    630:     freexexit2 possible for memory heap.
                    631: 
                    632:   h Pij x                         | pij_nom  ficrestpij
                    633:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    634:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    635:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    636: 
                    637:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    638:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    639:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    640:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    641:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    642: 
1.126     brouard   643:   forecasting if prevfcast==1 prevforecast call prevalence()
                    644:   health expectancies
                    645:   Variance-covariance of DFLE
                    646:   prevalence()
                    647:    movingaverage()
                    648:   varevsij() 
                    649:   if popbased==1 varevsij(,popbased)
                    650:   total life expectancies
                    651:   Variance of period (stable) prevalence
                    652:  end
                    653: */
                    654: 
1.187     brouard   655: /* #define DEBUG */
                    656: /* #define DEBUGBRENT */
1.203     brouard   657: /* #define DEBUGLINMIN */
                    658: /* #define DEBUGHESS */
                    659: #define DEBUGHESSIJ
                    660: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   661: #define POWELL /* Instead of NLOPT */
1.192     brouard   662: #define POWELLF1F3 /* Skip test */
1.186     brouard   663: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    664: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   665: 
                    666: #include <math.h>
                    667: #include <stdio.h>
                    668: #include <stdlib.h>
                    669: #include <string.h>
1.159     brouard   670: 
                    671: #ifdef _WIN32
                    672: #include <io.h>
1.172     brouard   673: #include <windows.h>
                    674: #include <tchar.h>
1.159     brouard   675: #else
1.126     brouard   676: #include <unistd.h>
1.159     brouard   677: #endif
1.126     brouard   678: 
                    679: #include <limits.h>
                    680: #include <sys/types.h>
1.171     brouard   681: 
                    682: #if defined(__GNUC__)
                    683: #include <sys/utsname.h> /* Doesn't work on Windows */
                    684: #endif
                    685: 
1.126     brouard   686: #include <sys/stat.h>
                    687: #include <errno.h>
1.159     brouard   688: /* extern int errno; */
1.126     brouard   689: 
1.157     brouard   690: /* #ifdef LINUX */
                    691: /* #include <time.h> */
                    692: /* #include "timeval.h" */
                    693: /* #else */
                    694: /* #include <sys/time.h> */
                    695: /* #endif */
                    696: 
1.126     brouard   697: #include <time.h>
                    698: 
1.136     brouard   699: #ifdef GSL
                    700: #include <gsl/gsl_errno.h>
                    701: #include <gsl/gsl_multimin.h>
                    702: #endif
                    703: 
1.167     brouard   704: 
1.162     brouard   705: #ifdef NLOPT
                    706: #include <nlopt.h>
                    707: typedef struct {
                    708:   double (* function)(double [] );
                    709: } myfunc_data ;
                    710: #endif
                    711: 
1.126     brouard   712: /* #include <libintl.h> */
                    713: /* #define _(String) gettext (String) */
                    714: 
1.141     brouard   715: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   716: 
                    717: #define GNUPLOTPROGRAM "gnuplot"
                    718: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    719: #define FILENAMELENGTH 132
                    720: 
                    721: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    722: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    723: 
1.144     brouard   724: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    725: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   726: 
                    727: #define NINTERVMAX 8
1.144     brouard   728: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    729: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    730: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   731: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   732: #define MAXN 20000
1.144     brouard   733: #define YEARM 12. /**< Number of months per year */
1.126     brouard   734: #define AGESUP 130
                    735: #define AGEBASE 40
1.194     brouard   736: #define AGEOVERFLOW 1.e20
1.164     brouard   737: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   738: #ifdef _WIN32
                    739: #define DIRSEPARATOR '\\'
                    740: #define CHARSEPARATOR "\\"
                    741: #define ODIRSEPARATOR '/'
                    742: #else
1.126     brouard   743: #define DIRSEPARATOR '/'
                    744: #define CHARSEPARATOR "/"
                    745: #define ODIRSEPARATOR '\\'
                    746: #endif
                    747: 
1.204   ! brouard   748: /* $Id: imach.c,v 1.203 2015/09/30 17:45:14 brouard Exp $ */
1.126     brouard   749: /* $State: Exp $ */
1.196     brouard   750: #include "version.h"
                    751: char version[]=__IMACH_VERSION__;
1.204   ! brouard   752: 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";
        !           753: char fullversion[]="$Revision: 1.203 $ $Date: 2015/09/30 17:45:14 $"; 
1.126     brouard   754: char strstart[80];
                    755: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   756: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   757: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   758: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    759: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    760: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    761: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    762: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    763: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    764: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    765: int cptcov=0; /* Working variable */
1.126     brouard   766: int npar=NPARMAX;
                    767: int nlstate=2; /* Number of live states */
                    768: int ndeath=1; /* Number of dead states */
1.130     brouard   769: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   770: int popbased=0;
                    771: 
                    772: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   773: int maxwav=0; /* Maxim number of waves */
                    774: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    775: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    776: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   777:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   778: int mle=1, weightopt=0;
1.126     brouard   779: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    780: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    781: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    782:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   783: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   784: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   785: double **matprod2(); /* test */
1.126     brouard   786: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    787: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   788: /*FILE *fic ; */ /* Used in readdata only */
                    789: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   790: FILE *ficlog, *ficrespow;
1.130     brouard   791: int globpr=0; /* Global variable for printing or not */
1.126     brouard   792: double fretone; /* Only one call to likelihood */
1.130     brouard   793: long ipmx=0; /* Number of contributions */
1.126     brouard   794: double sw; /* Sum of weights */
                    795: char filerespow[FILENAMELENGTH];
                    796: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    797: FILE *ficresilk;
                    798: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    799: FILE *ficresprobmorprev;
                    800: FILE *fichtm, *fichtmcov; /* Html File */
                    801: FILE *ficreseij;
                    802: char filerese[FILENAMELENGTH];
                    803: FILE *ficresstdeij;
                    804: char fileresstde[FILENAMELENGTH];
                    805: FILE *ficrescveij;
                    806: char filerescve[FILENAMELENGTH];
                    807: FILE  *ficresvij;
                    808: char fileresv[FILENAMELENGTH];
                    809: FILE  *ficresvpl;
                    810: char fileresvpl[FILENAMELENGTH];
                    811: char title[MAXLINE];
                    812: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    813: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    814: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    815: char command[FILENAMELENGTH];
                    816: int  outcmd=0;
                    817: 
                    818: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   819: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   820: char filelog[FILENAMELENGTH]; /* Log file */
                    821: char filerest[FILENAMELENGTH];
                    822: char fileregp[FILENAMELENGTH];
                    823: char popfile[FILENAMELENGTH];
                    824: 
                    825: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    826: 
1.157     brouard   827: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    828: /* struct timezone tzp; */
                    829: /* extern int gettimeofday(); */
                    830: struct tm tml, *gmtime(), *localtime();
                    831: 
                    832: extern time_t time();
                    833: 
                    834: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    835: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    836: struct tm tm;
                    837: 
1.126     brouard   838: char strcurr[80], strfor[80];
                    839: 
                    840: char *endptr;
                    841: long lval;
                    842: double dval;
                    843: 
                    844: #define NR_END 1
                    845: #define FREE_ARG char*
                    846: #define FTOL 1.0e-10
                    847: 
                    848: #define NRANSI 
                    849: #define ITMAX 200 
                    850: 
                    851: #define TOL 2.0e-4 
                    852: 
                    853: #define CGOLD 0.3819660 
                    854: #define ZEPS 1.0e-10 
                    855: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    856: 
                    857: #define GOLD 1.618034 
                    858: #define GLIMIT 100.0 
                    859: #define TINY 1.0e-20 
                    860: 
                    861: static double maxarg1,maxarg2;
                    862: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    863: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    864:   
                    865: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    866: #define rint(a) floor(a+0.5)
1.166     brouard   867: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   868: #define mytinydouble 1.0e-16
1.166     brouard   869: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    870: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    871: /* static double dsqrarg; */
                    872: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   873: static double sqrarg;
                    874: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    875: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    876: int agegomp= AGEGOMP;
                    877: 
                    878: int imx; 
                    879: int stepm=1;
                    880: /* Stepm, step in month: minimum step interpolation*/
                    881: 
                    882: int estepm;
                    883: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    884: 
                    885: int m,nb;
                    886: long *num;
1.197     brouard   887: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   888: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    889:                   covariate for which somebody answered excluding 
                    890:                   undefined. Usually 2: 0 and 1. */
                    891: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    892:                             covariate for which somebody answered including 
                    893:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   894: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    895: double **pmmij, ***probs;
                    896: double *ageexmed,*agecens;
                    897: double dateintmean=0;
                    898: 
                    899: double *weight;
                    900: int **s; /* Status */
1.141     brouard   901: double *agedc;
1.145     brouard   902: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   903:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   904:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   905: double  idx; 
                    906: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   907: int *Tage;
1.145     brouard   908: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   909: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   910: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   911: double *lsurv, *lpop, *tpop;
                    912: 
1.143     brouard   913: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    914: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   915: 
                    916: /**************** split *************************/
                    917: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    918: {
                    919:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    920:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    921:   */ 
                    922:   char *ss;                            /* pointer */
1.186     brouard   923:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   924: 
                    925:   l1 = strlen(path );                  /* length of path */
                    926:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    927:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    928:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    929:     strcpy( name, path );              /* we got the fullname name because no directory */
                    930:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    931:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    932:     /* get current working directory */
                    933:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   934: #ifdef WIN32
                    935:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    936: #else
                    937:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    938: #endif
1.126     brouard   939:       return( GLOCK_ERROR_GETCWD );
                    940:     }
                    941:     /* got dirc from getcwd*/
                    942:     printf(" DIRC = %s \n",dirc);
                    943:   } else {                             /* strip direcotry from path */
                    944:     ss++;                              /* after this, the filename */
                    945:     l2 = strlen( ss );                 /* length of filename */
                    946:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    947:     strcpy( name, ss );                /* save file name */
                    948:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   949:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   950:     printf(" DIRC2 = %s \n",dirc);
                    951:   }
                    952:   /* We add a separator at the end of dirc if not exists */
                    953:   l1 = strlen( dirc );                 /* length of directory */
                    954:   if( dirc[l1-1] != DIRSEPARATOR ){
                    955:     dirc[l1] =  DIRSEPARATOR;
                    956:     dirc[l1+1] = 0; 
                    957:     printf(" DIRC3 = %s \n",dirc);
                    958:   }
                    959:   ss = strrchr( name, '.' );           /* find last / */
                    960:   if (ss >0){
                    961:     ss++;
                    962:     strcpy(ext,ss);                    /* save extension */
                    963:     l1= strlen( name);
                    964:     l2= strlen(ss)+1;
                    965:     strncpy( finame, name, l1-l2);
                    966:     finame[l1-l2]= 0;
                    967:   }
                    968: 
                    969:   return( 0 );                         /* we're done */
                    970: }
                    971: 
                    972: 
                    973: /******************************************/
                    974: 
                    975: void replace_back_to_slash(char *s, char*t)
                    976: {
                    977:   int i;
                    978:   int lg=0;
                    979:   i=0;
                    980:   lg=strlen(t);
                    981:   for(i=0; i<= lg; i++) {
                    982:     (s[i] = t[i]);
                    983:     if (t[i]== '\\') s[i]='/';
                    984:   }
                    985: }
                    986: 
1.132     brouard   987: char *trimbb(char *out, char *in)
1.137     brouard   988: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   989:   char *s;
                    990:   s=out;
                    991:   while (*in != '\0'){
1.137     brouard   992:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   993:       in++;
                    994:     }
                    995:     *out++ = *in++;
                    996:   }
                    997:   *out='\0';
                    998:   return s;
                    999: }
                   1000: 
1.187     brouard  1001: /* char *substrchaine(char *out, char *in, char *chain) */
                   1002: /* { */
                   1003: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1004: /*   char *s, *t; */
                   1005: /*   t=in;s=out; */
                   1006: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1007: /*     *out++ = *in++; */
                   1008: /*   } */
                   1009: 
                   1010: /*   /\* *in matches *chain *\/ */
                   1011: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1012: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1013: /*   } */
                   1014: /*   in--; chain--; */
                   1015: /*   while ( (*in != '\0')){ */
                   1016: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1017: /*     *out++ = *in++; */
                   1018: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1019: /*   } */
                   1020: /*   *out='\0'; */
                   1021: /*   out=s; */
                   1022: /*   return out; */
                   1023: /* } */
                   1024: char *substrchaine(char *out, char *in, char *chain)
                   1025: {
                   1026:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1027:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1028: 
                   1029:   char *strloc;
                   1030: 
                   1031:   strcpy (out, in); 
                   1032:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1033:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1034:   if(strloc != NULL){ 
                   1035:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1036:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1037:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1038:   }
                   1039:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1040:   return out;
                   1041: }
                   1042: 
                   1043: 
1.145     brouard  1044: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1045: {
1.187     brouard  1046:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1047:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1048:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1049:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1050:   */
1.160     brouard  1051:   char *s, *t;
1.145     brouard  1052:   t=in;s=in;
                   1053:   while ((*in != occ) && (*in != '\0')){
                   1054:     *alocc++ = *in++;
                   1055:   }
                   1056:   if( *in == occ){
                   1057:     *(alocc)='\0';
                   1058:     s=++in;
                   1059:   }
                   1060:  
                   1061:   if (s == t) {/* occ not found */
                   1062:     *(alocc-(in-s))='\0';
                   1063:     in=s;
                   1064:   }
                   1065:   while ( *in != '\0'){
                   1066:     *blocc++ = *in++;
                   1067:   }
                   1068: 
                   1069:   *blocc='\0';
                   1070:   return t;
                   1071: }
1.137     brouard  1072: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1073: {
1.187     brouard  1074:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1075:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1076:      gives blocc="abcdef2ghi" and alocc="j".
                   1077:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1078:   */
                   1079:   char *s, *t;
                   1080:   t=in;s=in;
                   1081:   while (*in != '\0'){
                   1082:     while( *in == occ){
                   1083:       *blocc++ = *in++;
                   1084:       s=in;
                   1085:     }
                   1086:     *blocc++ = *in++;
                   1087:   }
                   1088:   if (s == t) /* occ not found */
                   1089:     *(blocc-(in-s))='\0';
                   1090:   else
                   1091:     *(blocc-(in-s)-1)='\0';
                   1092:   in=s;
                   1093:   while ( *in != '\0'){
                   1094:     *alocc++ = *in++;
                   1095:   }
                   1096: 
                   1097:   *alocc='\0';
                   1098:   return s;
                   1099: }
                   1100: 
1.126     brouard  1101: int nbocc(char *s, char occ)
                   1102: {
                   1103:   int i,j=0;
                   1104:   int lg=20;
                   1105:   i=0;
                   1106:   lg=strlen(s);
                   1107:   for(i=0; i<= lg; i++) {
                   1108:   if  (s[i] == occ ) j++;
                   1109:   }
                   1110:   return j;
                   1111: }
                   1112: 
1.137     brouard  1113: /* void cutv(char *u,char *v, char*t, char occ) */
                   1114: /* { */
                   1115: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1116: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1117: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1118: /*   int i,lg,j,p=0; */
                   1119: /*   i=0; */
                   1120: /*   lg=strlen(t); */
                   1121: /*   for(j=0; j<=lg-1; j++) { */
                   1122: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1123: /*   } */
1.126     brouard  1124: 
1.137     brouard  1125: /*   for(j=0; j<p; j++) { */
                   1126: /*     (u[j] = t[j]); */
                   1127: /*   } */
                   1128: /*      u[p]='\0'; */
1.126     brouard  1129: 
1.137     brouard  1130: /*    for(j=0; j<= lg; j++) { */
                   1131: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1132: /*   } */
                   1133: /* } */
1.126     brouard  1134: 
1.160     brouard  1135: #ifdef _WIN32
                   1136: char * strsep(char **pp, const char *delim)
                   1137: {
                   1138:   char *p, *q;
                   1139:          
                   1140:   if ((p = *pp) == NULL)
                   1141:     return 0;
                   1142:   if ((q = strpbrk (p, delim)) != NULL)
                   1143:   {
                   1144:     *pp = q + 1;
                   1145:     *q = '\0';
                   1146:   }
                   1147:   else
                   1148:     *pp = 0;
                   1149:   return p;
                   1150: }
                   1151: #endif
                   1152: 
1.126     brouard  1153: /********************** nrerror ********************/
                   1154: 
                   1155: void nrerror(char error_text[])
                   1156: {
                   1157:   fprintf(stderr,"ERREUR ...\n");
                   1158:   fprintf(stderr,"%s\n",error_text);
                   1159:   exit(EXIT_FAILURE);
                   1160: }
                   1161: /*********************** vector *******************/
                   1162: double *vector(int nl, int nh)
                   1163: {
                   1164:   double *v;
                   1165:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1166:   if (!v) nrerror("allocation failure in vector");
                   1167:   return v-nl+NR_END;
                   1168: }
                   1169: 
                   1170: /************************ free vector ******************/
                   1171: void free_vector(double*v, int nl, int nh)
                   1172: {
                   1173:   free((FREE_ARG)(v+nl-NR_END));
                   1174: }
                   1175: 
                   1176: /************************ivector *******************************/
                   1177: int *ivector(long nl,long nh)
                   1178: {
                   1179:   int *v;
                   1180:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1181:   if (!v) nrerror("allocation failure in ivector");
                   1182:   return v-nl+NR_END;
                   1183: }
                   1184: 
                   1185: /******************free ivector **************************/
                   1186: void free_ivector(int *v, long nl, long nh)
                   1187: {
                   1188:   free((FREE_ARG)(v+nl-NR_END));
                   1189: }
                   1190: 
                   1191: /************************lvector *******************************/
                   1192: long *lvector(long nl,long nh)
                   1193: {
                   1194:   long *v;
                   1195:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1196:   if (!v) nrerror("allocation failure in ivector");
                   1197:   return v-nl+NR_END;
                   1198: }
                   1199: 
                   1200: /******************free lvector **************************/
                   1201: void free_lvector(long *v, long nl, long nh)
                   1202: {
                   1203:   free((FREE_ARG)(v+nl-NR_END));
                   1204: }
                   1205: 
                   1206: /******************* imatrix *******************************/
                   1207: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1208:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1209: { 
                   1210:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1211:   int **m; 
                   1212:   
                   1213:   /* allocate pointers to rows */ 
                   1214:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1215:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1216:   m += NR_END; 
                   1217:   m -= nrl; 
                   1218:   
                   1219:   
                   1220:   /* allocate rows and set pointers to them */ 
                   1221:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1222:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1223:   m[nrl] += NR_END; 
                   1224:   m[nrl] -= ncl; 
                   1225:   
                   1226:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1227:   
                   1228:   /* return pointer to array of pointers to rows */ 
                   1229:   return m; 
                   1230: } 
                   1231: 
                   1232: /****************** free_imatrix *************************/
                   1233: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1234:       int **m;
                   1235:       long nch,ncl,nrh,nrl; 
                   1236:      /* free an int matrix allocated by imatrix() */ 
                   1237: { 
                   1238:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1239:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1240: } 
                   1241: 
                   1242: /******************* matrix *******************************/
                   1243: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1244: {
                   1245:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1246:   double **m;
                   1247: 
                   1248:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1249:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1250:   m += NR_END;
                   1251:   m -= nrl;
                   1252: 
                   1253:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1254:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1255:   m[nrl] += NR_END;
                   1256:   m[nrl] -= ncl;
                   1257: 
                   1258:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1259:   return m;
1.145     brouard  1260:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1261: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1262: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1263:    */
                   1264: }
                   1265: 
                   1266: /*************************free matrix ************************/
                   1267: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1268: {
                   1269:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1270:   free((FREE_ARG)(m+nrl-NR_END));
                   1271: }
                   1272: 
                   1273: /******************* ma3x *******************************/
                   1274: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1275: {
                   1276:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1277:   double ***m;
                   1278: 
                   1279:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1280:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1281:   m += NR_END;
                   1282:   m -= nrl;
                   1283: 
                   1284:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1285:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1286:   m[nrl] += NR_END;
                   1287:   m[nrl] -= ncl;
                   1288: 
                   1289:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1290: 
                   1291:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1292:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1293:   m[nrl][ncl] += NR_END;
                   1294:   m[nrl][ncl] -= nll;
                   1295:   for (j=ncl+1; j<=nch; j++) 
                   1296:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1297:   
                   1298:   for (i=nrl+1; i<=nrh; i++) {
                   1299:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1300:     for (j=ncl+1; j<=nch; j++) 
                   1301:       m[i][j]=m[i][j-1]+nlay;
                   1302:   }
                   1303:   return m; 
                   1304:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1305:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1306:   */
                   1307: }
                   1308: 
                   1309: /*************************free ma3x ************************/
                   1310: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1311: {
                   1312:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1313:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1314:   free((FREE_ARG)(m+nrl-NR_END));
                   1315: }
                   1316: 
                   1317: /*************** function subdirf ***********/
                   1318: char *subdirf(char fileres[])
                   1319: {
                   1320:   /* Caution optionfilefiname is hidden */
                   1321:   strcpy(tmpout,optionfilefiname);
                   1322:   strcat(tmpout,"/"); /* Add to the right */
                   1323:   strcat(tmpout,fileres);
                   1324:   return tmpout;
                   1325: }
                   1326: 
                   1327: /*************** function subdirf2 ***********/
                   1328: char *subdirf2(char fileres[], char *preop)
                   1329: {
                   1330:   
                   1331:   /* Caution optionfilefiname is hidden */
                   1332:   strcpy(tmpout,optionfilefiname);
                   1333:   strcat(tmpout,"/");
                   1334:   strcat(tmpout,preop);
                   1335:   strcat(tmpout,fileres);
                   1336:   return tmpout;
                   1337: }
                   1338: 
                   1339: /*************** function subdirf3 ***********/
                   1340: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1341: {
                   1342:   
                   1343:   /* Caution optionfilefiname is hidden */
                   1344:   strcpy(tmpout,optionfilefiname);
                   1345:   strcat(tmpout,"/");
                   1346:   strcat(tmpout,preop);
                   1347:   strcat(tmpout,preop2);
                   1348:   strcat(tmpout,fileres);
                   1349:   return tmpout;
                   1350: }
                   1351: 
1.162     brouard  1352: char *asc_diff_time(long time_sec, char ascdiff[])
                   1353: {
                   1354:   long sec_left, days, hours, minutes;
                   1355:   days = (time_sec) / (60*60*24);
                   1356:   sec_left = (time_sec) % (60*60*24);
                   1357:   hours = (sec_left) / (60*60) ;
                   1358:   sec_left = (sec_left) %(60*60);
                   1359:   minutes = (sec_left) /60;
                   1360:   sec_left = (sec_left) % (60);
                   1361:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1362:   return ascdiff;
                   1363: }
                   1364: 
1.126     brouard  1365: /***************** f1dim *************************/
                   1366: extern int ncom; 
                   1367: extern double *pcom,*xicom;
                   1368: extern double (*nrfunc)(double []); 
                   1369:  
                   1370: double f1dim(double x) 
                   1371: { 
                   1372:   int j; 
                   1373:   double f;
                   1374:   double *xt; 
                   1375:  
                   1376:   xt=vector(1,ncom); 
                   1377:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1378:   f=(*nrfunc)(xt); 
                   1379:   free_vector(xt,1,ncom); 
                   1380:   return f; 
                   1381: } 
                   1382: 
                   1383: /*****************brent *************************/
                   1384: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1385: {
                   1386:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1387:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1388:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1389:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1390:    * returned function value. 
                   1391:   */
1.126     brouard  1392:   int iter; 
                   1393:   double a,b,d,etemp;
1.159     brouard  1394:   double fu=0,fv,fw,fx;
1.164     brouard  1395:   double ftemp=0.;
1.126     brouard  1396:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1397:   double e=0.0; 
                   1398:  
                   1399:   a=(ax < cx ? ax : cx); 
                   1400:   b=(ax > cx ? ax : cx); 
                   1401:   x=w=v=bx; 
                   1402:   fw=fv=fx=(*f)(x); 
                   1403:   for (iter=1;iter<=ITMAX;iter++) { 
                   1404:     xm=0.5*(a+b); 
                   1405:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1406:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1407:     printf(".");fflush(stdout);
                   1408:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1409: #ifdef DEBUGBRENT
1.126     brouard  1410:     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);
                   1411:     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);
                   1412:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1413: #endif
                   1414:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1415:       *xmin=x; 
                   1416:       return fx; 
                   1417:     } 
                   1418:     ftemp=fu;
                   1419:     if (fabs(e) > tol1) { 
                   1420:       r=(x-w)*(fx-fv); 
                   1421:       q=(x-v)*(fx-fw); 
                   1422:       p=(x-v)*q-(x-w)*r; 
                   1423:       q=2.0*(q-r); 
                   1424:       if (q > 0.0) p = -p; 
                   1425:       q=fabs(q); 
                   1426:       etemp=e; 
                   1427:       e=d; 
                   1428:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1429:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1430:       else { 
                   1431:        d=p/q; 
                   1432:        u=x+d; 
                   1433:        if (u-a < tol2 || b-u < tol2) 
                   1434:          d=SIGN(tol1,xm-x); 
                   1435:       } 
                   1436:     } else { 
                   1437:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1438:     } 
                   1439:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1440:     fu=(*f)(u); 
                   1441:     if (fu <= fx) { 
                   1442:       if (u >= x) a=x; else b=x; 
                   1443:       SHFT(v,w,x,u) 
1.183     brouard  1444:       SHFT(fv,fw,fx,fu) 
                   1445:     } else { 
                   1446:       if (u < x) a=u; else b=u; 
                   1447:       if (fu <= fw || w == x) { 
                   1448:        v=w; 
                   1449:        w=u; 
                   1450:        fv=fw; 
                   1451:        fw=fu; 
                   1452:       } else if (fu <= fv || v == x || v == w) { 
                   1453:        v=u; 
                   1454:        fv=fu; 
                   1455:       } 
                   1456:     } 
1.126     brouard  1457:   } 
                   1458:   nrerror("Too many iterations in brent"); 
                   1459:   *xmin=x; 
                   1460:   return fx; 
                   1461: } 
                   1462: 
                   1463: /****************** mnbrak ***********************/
                   1464: 
                   1465: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1466:            double (*func)(double)) 
1.183     brouard  1467: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1468: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1469: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1470: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1471:    */
1.126     brouard  1472:   double ulim,u,r,q, dum;
                   1473:   double fu; 
1.187     brouard  1474: 
                   1475:   double scale=10.;
                   1476:   int iterscale=0;
                   1477: 
                   1478:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1479:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1480: 
                   1481: 
                   1482:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1483:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1484:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1485:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1486:   /* } */
                   1487: 
1.126     brouard  1488:   if (*fb > *fa) { 
                   1489:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1490:     SHFT(dum,*fb,*fa,dum) 
                   1491:   } 
1.126     brouard  1492:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1493:   *fc=(*func)(*cx); 
1.183     brouard  1494: #ifdef DEBUG
                   1495:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1496:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1497: #endif
                   1498:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1499:     r=(*bx-*ax)*(*fb-*fc); 
                   1500:     q=(*bx-*cx)*(*fb-*fa); 
                   1501:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1502:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1503:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1504:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1505:       fu=(*func)(u); 
1.163     brouard  1506: #ifdef DEBUG
                   1507:       /* f(x)=A(x-u)**2+f(u) */
                   1508:       double A, fparabu; 
                   1509:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1510:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1511:       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);
                   1512:       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  1513:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1514:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1515:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1516:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1517: #endif 
1.184     brouard  1518: #ifdef MNBRAKORIGINAL
1.183     brouard  1519: #else
1.191     brouard  1520: /*       if (fu > *fc) { */
                   1521: /* #ifdef DEBUG */
                   1522: /*       printf("mnbrak4  fu > fc \n"); */
                   1523: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1524: /* #endif */
                   1525: /*     /\* 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 *\\/  *\/ */
                   1526: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1527: /*     dum=u; /\* Shifting c and u *\/ */
                   1528: /*     u = *cx; */
                   1529: /*     *cx = dum; */
                   1530: /*     dum = fu; */
                   1531: /*     fu = *fc; */
                   1532: /*     *fc =dum; */
                   1533: /*       } else { /\* end *\/ */
                   1534: /* #ifdef DEBUG */
                   1535: /*       printf("mnbrak3  fu < fc \n"); */
                   1536: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1537: /* #endif */
                   1538: /*     dum=u; /\* Shifting c and u *\/ */
                   1539: /*     u = *cx; */
                   1540: /*     *cx = dum; */
                   1541: /*     dum = fu; */
                   1542: /*     fu = *fc; */
                   1543: /*     *fc =dum; */
                   1544: /*       } */
1.183     brouard  1545: #ifdef DEBUG
1.191     brouard  1546:       printf("mnbrak34  fu < or >= fc \n");
                   1547:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1548: #endif
1.191     brouard  1549:       dum=u; /* Shifting c and u */
                   1550:       u = *cx;
                   1551:       *cx = dum;
                   1552:       dum = fu;
                   1553:       fu = *fc;
                   1554:       *fc =dum;
1.183     brouard  1555: #endif
1.162     brouard  1556:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1557: #ifdef DEBUG
                   1558:       printf("mnbrak2  u after c but before ulim\n");
                   1559:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1560: #endif
1.126     brouard  1561:       fu=(*func)(u); 
                   1562:       if (fu < *fc) { 
1.183     brouard  1563: #ifdef DEBUG
                   1564:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1565:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1566: #endif
1.126     brouard  1567:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1568:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1569:       } 
1.162     brouard  1570:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1571: #ifdef DEBUG
                   1572:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1573:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1574: #endif
1.126     brouard  1575:       u=ulim; 
                   1576:       fu=(*func)(u); 
1.183     brouard  1577:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1578: #ifdef DEBUG
                   1579:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1580:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1581: #endif
1.126     brouard  1582:       u=(*cx)+GOLD*(*cx-*bx); 
                   1583:       fu=(*func)(u); 
1.183     brouard  1584:     } /* end tests */
1.126     brouard  1585:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1586:     SHFT(*fa,*fb,*fc,fu) 
                   1587: #ifdef DEBUG
                   1588:       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);
                   1589:       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);
                   1590: #endif
                   1591:   } /* 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  1592: } 
                   1593: 
                   1594: /*************** linmin ************************/
1.162     brouard  1595: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1596: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1597: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1598: the value of func at the returned location p . This is actually all accomplished by calling the
                   1599: routines mnbrak and brent .*/
1.126     brouard  1600: int ncom; 
                   1601: double *pcom,*xicom;
                   1602: double (*nrfunc)(double []); 
                   1603:  
                   1604: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1605: { 
                   1606:   double brent(double ax, double bx, double cx, 
                   1607:               double (*f)(double), double tol, double *xmin); 
                   1608:   double f1dim(double x); 
                   1609:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1610:              double *fc, double (*func)(double)); 
                   1611:   int j; 
                   1612:   double xx,xmin,bx,ax; 
                   1613:   double fx,fb,fa;
1.187     brouard  1614: 
1.203     brouard  1615: #ifdef LINMINORIGINAL
                   1616: #else
                   1617:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1618: #endif
                   1619:   
1.126     brouard  1620:   ncom=n; 
                   1621:   pcom=vector(1,n); 
                   1622:   xicom=vector(1,n); 
                   1623:   nrfunc=func; 
                   1624:   for (j=1;j<=n;j++) { 
                   1625:     pcom[j]=p[j]; 
1.202     brouard  1626:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1627:   } 
1.187     brouard  1628: 
1.203     brouard  1629: #ifdef LINMINORIGINAL
                   1630:   xx=1.;
                   1631: #else
                   1632:   axs=0.0;
                   1633:   xxs=1.;
                   1634:   do{
                   1635:     xx= xxs;
                   1636: #endif
1.187     brouard  1637:     ax=0.;
                   1638:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1639:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1640:     /* 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))   */
                   1641:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1642:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1643:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1644:     /* 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  1645: #ifdef LINMINORIGINAL
                   1646: #else
                   1647:     if (fx != fx){
                   1648:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1649:        printf("|");
                   1650:        fprintf(ficlog,"|");
                   1651: #ifdef DEBUGLINMIN
                   1652:        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);
                   1653: #endif
                   1654:     }
                   1655:   }while(fx != fx);
                   1656: #endif
                   1657:   
1.191     brouard  1658: #ifdef DEBUGLINMIN
                   1659:   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  1660:   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  1661: #endif
1.187     brouard  1662:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1663:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1664:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1665:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1666:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1667: #ifdef DEBUG
                   1668:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1669:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1670: #endif
1.191     brouard  1671: #ifdef DEBUGLINMIN
                   1672:   printf("linmin end ");
1.202     brouard  1673:   fprintf(ficlog,"linmin end ");
1.191     brouard  1674: #endif
1.126     brouard  1675:   for (j=1;j<=n;j++) { 
1.203     brouard  1676: #ifdef LINMINORIGINAL
                   1677:     xi[j] *= xmin; 
                   1678: #else
                   1679: #ifdef DEBUGLINMIN
                   1680:     if(xxs <1.0)
                   1681:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1682: #endif
                   1683:     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) */
                   1684: #ifdef DEBUGLINMIN
                   1685:     if(xxs <1.0)
                   1686:       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 );
                   1687: #endif
                   1688: #endif
1.187     brouard  1689:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1690:   } 
1.191     brouard  1691: #ifdef DEBUGLINMIN
1.203     brouard  1692:   printf("\n");
1.191     brouard  1693:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1694:   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  1695:   for (j=1;j<=n;j++) { 
1.202     brouard  1696:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1697:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1698:     if(j % ncovmodel == 0){
1.191     brouard  1699:       printf("\n");
1.202     brouard  1700:       fprintf(ficlog,"\n");
                   1701:     }
1.191     brouard  1702:   }
1.203     brouard  1703: #else
1.191     brouard  1704: #endif
1.126     brouard  1705:   free_vector(xicom,1,n); 
                   1706:   free_vector(pcom,1,n); 
                   1707: } 
                   1708: 
                   1709: 
                   1710: /*************** powell ************************/
1.162     brouard  1711: /*
                   1712: Minimization of a function func of n variables. Input consists of an initial starting point
                   1713: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1714: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1715: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1716: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1717: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1718:  */
1.126     brouard  1719: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1720:            double (*func)(double [])) 
                   1721: { 
                   1722:   void linmin(double p[], double xi[], int n, double *fret, 
                   1723:              double (*func)(double [])); 
                   1724:   int i,ibig,j; 
                   1725:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1726:   double directest;
1.126     brouard  1727:   double fp,fptt;
                   1728:   double *xits;
                   1729:   int niterf, itmp;
                   1730: 
                   1731:   pt=vector(1,n); 
                   1732:   ptt=vector(1,n); 
                   1733:   xit=vector(1,n); 
                   1734:   xits=vector(1,n); 
                   1735:   *fret=(*func)(p); 
                   1736:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1737:   rcurr_time = time(NULL);  
1.126     brouard  1738:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1739:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1740:     ibig=0; 
                   1741:     del=0.0; 
1.157     brouard  1742:     rlast_time=rcurr_time;
                   1743:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1744:     rcurr_time = time(NULL);  
                   1745:     curr_time = *localtime(&rcurr_time);
                   1746:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1747:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1748: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1749:     for (i=1;i<=n;i++) {
1.126     brouard  1750:       printf(" %d %.12f",i, p[i]);
                   1751:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1752:       fprintf(ficrespow," %.12lf", p[i]);
                   1753:     }
                   1754:     printf("\n");
                   1755:     fprintf(ficlog,"\n");
                   1756:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1757:     if(*iter <=3){
1.157     brouard  1758:       tml = *localtime(&rcurr_time);
                   1759:       strcpy(strcurr,asctime(&tml));
                   1760:       rforecast_time=rcurr_time; 
1.126     brouard  1761:       itmp = strlen(strcurr);
                   1762:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1763:        strcurr[itmp-1]='\0';
1.162     brouard  1764:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1765:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1766:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1767:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1768:        forecast_time = *localtime(&rforecast_time);
                   1769:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1770:        itmp = strlen(strfor);
                   1771:        if(strfor[itmp-1]=='\n')
                   1772:        strfor[itmp-1]='\0';
1.157     brouard  1773:        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);
                   1774:        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  1775:       }
                   1776:     }
1.187     brouard  1777:     for (i=1;i<=n;i++) { /* For each direction i */
                   1778:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1779:       fptt=(*fret); 
                   1780: #ifdef DEBUG
1.203     brouard  1781:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1782:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1783: #endif
1.203     brouard  1784:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1785:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1786:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1787:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1788:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1789:        /* because that direction will be replaced unless the gain del is small */
                   1790:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1791:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1792:        /* with the new direction. */
1.126     brouard  1793:        del=fabs(fptt-(*fret)); 
                   1794:        ibig=i; 
                   1795:       } 
                   1796: #ifdef DEBUG
                   1797:       printf("%d %.12e",i,(*fret));
                   1798:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1799:       for (j=1;j<=n;j++) {
                   1800:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1801:        printf(" x(%d)=%.12e",j,xit[j]);
                   1802:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1803:       }
                   1804:       for(j=1;j<=n;j++) {
1.162     brouard  1805:        printf(" p(%d)=%.12e",j,p[j]);
                   1806:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1807:       }
                   1808:       printf("\n");
                   1809:       fprintf(ficlog,"\n");
                   1810: #endif
1.187     brouard  1811:     } /* end loop on each direction i */
                   1812:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1813:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1814:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1815:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1816:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1817:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1818:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1819:       /* decreased of more than 3.84  */
                   1820:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1821:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1822:       /* By adding 10 parameters more the gain should be 18.31 */
                   1823: 
                   1824:       /* Starting the program with initial values given by a former maximization will simply change */
                   1825:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1826:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1827:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1828: #ifdef DEBUG
                   1829:       int k[2],l;
                   1830:       k[0]=1;
                   1831:       k[1]=-1;
                   1832:       printf("Max: %.12e",(*func)(p));
                   1833:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1834:       for (j=1;j<=n;j++) {
                   1835:        printf(" %.12e",p[j]);
                   1836:        fprintf(ficlog," %.12e",p[j]);
                   1837:       }
                   1838:       printf("\n");
                   1839:       fprintf(ficlog,"\n");
                   1840:       for(l=0;l<=1;l++) {
                   1841:        for (j=1;j<=n;j++) {
                   1842:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1843:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1844:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1845:        }
                   1846:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1847:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1848:       }
                   1849: #endif
                   1850: 
                   1851: 
                   1852:       free_vector(xit,1,n); 
                   1853:       free_vector(xits,1,n); 
                   1854:       free_vector(ptt,1,n); 
                   1855:       free_vector(pt,1,n); 
                   1856:       return; 
1.192     brouard  1857:     } /* enough precision */ 
1.126     brouard  1858:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1859:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1860:       ptt[j]=2.0*p[j]-pt[j]; 
                   1861:       xit[j]=p[j]-pt[j]; 
                   1862:       pt[j]=p[j]; 
                   1863:     } 
1.181     brouard  1864:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1865: #ifdef POWELLF1F3
                   1866: #else
1.161     brouard  1867:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1868: #endif
1.162     brouard  1869:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1870:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1871:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1872:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1873:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1874:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1875:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1876: #ifdef NRCORIGINAL
                   1877:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1878: #else
                   1879:       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  1880:       t= t- del*SQR(fp-fptt);
1.183     brouard  1881: #endif
1.202     brouard  1882:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1883: #ifdef DEBUG
1.181     brouard  1884:       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);
                   1885:       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  1886:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1887:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1888:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1889:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1890:       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);
                   1891:       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);
                   1892: #endif
1.183     brouard  1893: #ifdef POWELLORIGINAL
                   1894:       if (t < 0.0) { /* Then we use it for new direction */
                   1895: #else
1.182     brouard  1896:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1897:        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  1898:         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  1899:         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  1900:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1901:       } 
1.181     brouard  1902:       if (directest < 0.0) { /* Then we use it for new direction */
                   1903: #endif
1.191     brouard  1904: #ifdef DEBUGLINMIN
                   1905:        printf("Before linmin in direction P%d-P0\n",n);
                   1906:        for (j=1;j<=n;j++) { 
1.202     brouard  1907:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1908:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1909:          if(j % ncovmodel == 0){
1.191     brouard  1910:            printf("\n");
1.202     brouard  1911:            fprintf(ficlog,"\n");
                   1912:          }
1.191     brouard  1913:        }
                   1914: #endif
1.187     brouard  1915:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1916: #ifdef DEBUGLINMIN
                   1917:        for (j=1;j<=n;j++) { 
                   1918:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1919:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1920:          if(j % ncovmodel == 0){
1.191     brouard  1921:            printf("\n");
1.202     brouard  1922:            fprintf(ficlog,"\n");
                   1923:          }
1.191     brouard  1924:        }
                   1925: #endif
1.126     brouard  1926:        for (j=1;j<=n;j++) { 
1.181     brouard  1927:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1928:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1929:        }
1.181     brouard  1930:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1931:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1932: 
1.126     brouard  1933: #ifdef DEBUG
1.164     brouard  1934:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1935:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1936:        for(j=1;j<=n;j++){
                   1937:          printf(" %.12e",xit[j]);
                   1938:          fprintf(ficlog," %.12e",xit[j]);
                   1939:        }
                   1940:        printf("\n");
                   1941:        fprintf(ficlog,"\n");
                   1942: #endif
1.192     brouard  1943:       } /* end of t or directest negative */
                   1944: #ifdef POWELLF1F3
                   1945: #else
1.162     brouard  1946:     } /* end if (fptt < fp)  */
1.192     brouard  1947: #endif
                   1948:   } /* loop iteration */ 
1.126     brouard  1949: } 
                   1950: 
                   1951: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1952: 
1.203     brouard  1953: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1954: {
                   1955:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  1956:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.169     brouard  1957:   
1.126     brouard  1958:   int i, ii,j,k;
                   1959:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1960:   /* double **matprod2(); */ /* test */
1.131     brouard  1961:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1962:   double **newm;
1.202     brouard  1963:   double agefin, delaymax=100 ; /* Max number of years to converge */
1.203     brouard  1964:   int ncvloop=0;
1.169     brouard  1965:   
1.126     brouard  1966:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1967:     for (j=1;j<=nlstate+ndeath;j++){
                   1968:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1969:     }
1.169     brouard  1970:   
                   1971:   cov[1]=1.;
                   1972:   
                   1973:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  1974:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  1975:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  1976:     ncvloop++;
1.126     brouard  1977:     newm=savm;
                   1978:     /* Covariates have to be included here again */
1.138     brouard  1979:     cov[2]=agefin;
1.187     brouard  1980:     if(nagesqr==1)
                   1981:       cov[3]= agefin*agefin;;
1.138     brouard  1982:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  1983:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   1984:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  1985:       /* 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  1986:     }
1.186     brouard  1987:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  1988:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   1989:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  1990:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  1991:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   1992:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  1993:     
                   1994:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1995:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1996:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1997:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1998:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1999:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2000:     
1.126     brouard  2001:     savm=oldm;
                   2002:     oldm=newm;
                   2003:     maxmax=0.;
                   2004:     for(j=1;j<=nlstate;j++){
                   2005:       min=1.;
                   2006:       max=0.;
                   2007:       for(i=1; i<=nlstate; i++) {
                   2008:        sumnew=0;
                   2009:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2010:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2011:        max=FMAX(max,prlim[i][j]);
                   2012:        min=FMIN(min,prlim[i][j]);
1.202     brouard  2013:         /* printf(" age= %d prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d max=%f min=%f\n", (int)age, i, j, i, j, prlim[i][j],(int)agefin, max, min); */
1.126     brouard  2014:       }
1.203     brouard  2015:       maxmin=(max-min)/(max+min)*2;
1.126     brouard  2016:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  2017:     } /* j loop */
1.203     brouard  2018:     *ncvyear= (int)age- (int)agefin;
                   2019:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2020:     if(maxmax < ftolpl){
1.203     brouard  2021:       /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2022:       return prlim;
                   2023:     }
1.169     brouard  2024:   } /* age loop */
1.203     brouard  2025:   printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g. \n\
                   2026: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   2027: /* 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); */
1.169     brouard  2028:   return prlim; /* should not reach here */
1.126     brouard  2029: }
                   2030: 
                   2031: /*************** transition probabilities ***************/ 
                   2032: 
                   2033: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2034: {
1.138     brouard  2035:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2036:      computes the probability to be observed in state j being in state i by appying the
                   2037:      model to the ncovmodel covariates (including constant and age).
                   2038:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2039:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2040:      ncth covariate in the global vector x is given by the formula:
                   2041:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2042:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2043:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2044:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2045:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2046:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2047:   */
                   2048:   double s1, lnpijopii;
1.126     brouard  2049:   /*double t34;*/
1.164     brouard  2050:   int i,j, nc, ii, jj;
1.126     brouard  2051: 
                   2052:     for(i=1; i<= nlstate; i++){
                   2053:       for(j=1; j<i;j++){
1.138     brouard  2054:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2055:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2056:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2057: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2058:        }
1.138     brouard  2059:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2060: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2061:       }
                   2062:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2063:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2064:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2065:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2066: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2067:        }
1.138     brouard  2068:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2069:       }
                   2070:     }
                   2071:     
                   2072:     for(i=1; i<= nlstate; i++){
                   2073:       s1=0;
1.131     brouard  2074:       for(j=1; j<i; j++){
1.138     brouard  2075:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2076:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2077:       }
                   2078:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2079:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2080:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2081:       }
1.138     brouard  2082:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2083:       ps[i][i]=1./(s1+1.);
1.138     brouard  2084:       /* Computing other pijs */
1.126     brouard  2085:       for(j=1; j<i; j++)
                   2086:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2087:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2088:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2089:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2090:     } /* end i */
                   2091:     
                   2092:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2093:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2094:        ps[ii][jj]=0;
                   2095:        ps[ii][ii]=1;
                   2096:       }
                   2097:     }
                   2098:     
1.145     brouard  2099:     
                   2100:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2101:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2102:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2103:     /*   } */
                   2104:     /*   printf("\n "); */
                   2105:     /* } */
                   2106:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2107:     /*
1.126     brouard  2108:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2109:       goto end;*/
                   2110:     return ps;
                   2111: }
                   2112: 
                   2113: /**************** Product of 2 matrices ******************/
                   2114: 
1.145     brouard  2115: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2116: {
                   2117:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2118:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2119:   /* in, b, out are matrice of pointers which should have been initialized 
                   2120:      before: only the contents of out is modified. The function returns
                   2121:      a pointer to pointers identical to out */
1.145     brouard  2122:   int i, j, k;
1.126     brouard  2123:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2124:     for(k=ncolol; k<=ncoloh; k++){
                   2125:       out[i][k]=0.;
                   2126:       for(j=ncl; j<=nch; j++)
                   2127:        out[i][k] +=in[i][j]*b[j][k];
                   2128:     }
1.126     brouard  2129:   return out;
                   2130: }
                   2131: 
                   2132: 
                   2133: /************* Higher Matrix Product ***************/
                   2134: 
                   2135: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2136: {
                   2137:   /* Computes the transition matrix starting at age 'age' over 
                   2138:      'nhstepm*hstepm*stepm' months (i.e. until
                   2139:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2140:      nhstepm*hstepm matrices. 
                   2141:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2142:      (typically every 2 years instead of every month which is too big 
                   2143:      for the memory).
                   2144:      Model is determined by parameters x and covariates have to be 
                   2145:      included manually here. 
                   2146: 
                   2147:      */
                   2148: 
                   2149:   int i, j, d, h, k;
1.131     brouard  2150:   double **out, cov[NCOVMAX+1];
1.126     brouard  2151:   double **newm;
1.187     brouard  2152:   double agexact;
1.126     brouard  2153: 
                   2154:   /* Hstepm could be zero and should return the unit matrix */
                   2155:   for (i=1;i<=nlstate+ndeath;i++)
                   2156:     for (j=1;j<=nlstate+ndeath;j++){
                   2157:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2158:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2159:     }
                   2160:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2161:   for(h=1; h <=nhstepm; h++){
                   2162:     for(d=1; d <=hstepm; d++){
                   2163:       newm=savm;
                   2164:       /* Covariates have to be included here again */
                   2165:       cov[1]=1.;
1.187     brouard  2166:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2167:       cov[2]=agexact;
                   2168:       if(nagesqr==1)
                   2169:        cov[3]= agexact*agexact;
1.131     brouard  2170:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2171:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2172:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2173:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2174:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2175:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2176:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2177:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2178:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2179:        /* 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  2180: 
                   2181: 
                   2182:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2183:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2184:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2185:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2186:       savm=oldm;
                   2187:       oldm=newm;
                   2188:     }
                   2189:     for(i=1; i<=nlstate+ndeath; i++)
                   2190:       for(j=1;j<=nlstate+ndeath;j++) {
                   2191:        po[i][j][h]=newm[i][j];
1.128     brouard  2192:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2193:       }
1.128     brouard  2194:     /*printf("h=%d ",h);*/
1.126     brouard  2195:   } /* end h */
1.128     brouard  2196: /*     printf("\n H=%d \n",h); */
1.126     brouard  2197:   return po;
                   2198: }
                   2199: 
1.162     brouard  2200: #ifdef NLOPT
                   2201:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2202:   double fret;
                   2203:   double *xt;
                   2204:   int j;
                   2205:   myfunc_data *d2 = (myfunc_data *) pd;
                   2206: /* xt = (p1-1); */
                   2207:   xt=vector(1,n); 
                   2208:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2209: 
                   2210:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2211:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2212:   printf("Function = %.12lf ",fret);
                   2213:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2214:   printf("\n");
                   2215:  free_vector(xt,1,n);
                   2216:   return fret;
                   2217: }
                   2218: #endif
1.126     brouard  2219: 
                   2220: /*************** log-likelihood *************/
                   2221: double func( double *x)
                   2222: {
                   2223:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2224:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2225:   double **out;
                   2226:   double sw; /* Sum of weights */
                   2227:   double lli; /* Individual log likelihood */
                   2228:   int s1, s2;
                   2229:   double bbh, survp;
                   2230:   long ipmx;
1.187     brouard  2231:   double agexact;
1.126     brouard  2232:   /*extern weight */
                   2233:   /* We are differentiating ll according to initial status */
                   2234:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2235:   /*for(i=1;i<imx;i++) 
                   2236:     printf(" %d\n",s[4][i]);
                   2237:   */
1.162     brouard  2238: 
                   2239:   ++countcallfunc;
                   2240: 
1.126     brouard  2241:   cov[1]=1.;
                   2242: 
                   2243:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2244: 
                   2245:   if(mle==1){
                   2246:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2247:       /* Computes the values of the ncovmodel covariates of the model
                   2248:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2249:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2250:         to be observed in j being in i according to the model.
                   2251:        */
1.145     brouard  2252:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2253:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2254:       }
1.137     brouard  2255:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2256:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2257:         has been calculated etc */
1.126     brouard  2258:       for(mi=1; mi<= wav[i]-1; mi++){
                   2259:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2260:          for (j=1;j<=nlstate+ndeath;j++){
                   2261:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2262:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2263:          }
                   2264:        for(d=0; d<dh[mi][i]; d++){
                   2265:          newm=savm;
1.187     brouard  2266:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2267:          cov[2]=agexact;
                   2268:          if(nagesqr==1)
                   2269:            cov[3]= agexact*agexact;
1.126     brouard  2270:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2271:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2272:          }
                   2273:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2274:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2275:          savm=oldm;
                   2276:          oldm=newm;
                   2277:        } /* end mult */
                   2278:       
                   2279:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2280:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2281:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2282:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2283:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2284:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2285:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2286:         * probability in order to take into account the bias as a fraction of the way
                   2287:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2288:         * -stepm/2 to stepm/2 .
                   2289:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2290:         * For stepm > 1 the results are less biased than in previous versions. 
                   2291:         */
                   2292:        s1=s[mw[mi][i]][i];
                   2293:        s2=s[mw[mi+1][i]][i];
                   2294:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2295:        /* bias bh is positive if real duration
                   2296:         * is higher than the multiple of stepm and negative otherwise.
                   2297:         */
                   2298:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2299:        if( s2 > nlstate){ 
                   2300:          /* i.e. if s2 is a death state and if the date of death is known 
                   2301:             then the contribution to the likelihood is the probability to 
                   2302:             die between last step unit time and current  step unit time, 
                   2303:             which is also equal to probability to die before dh 
                   2304:             minus probability to die before dh-stepm . 
                   2305:             In version up to 0.92 likelihood was computed
                   2306:        as if date of death was unknown. Death was treated as any other
                   2307:        health state: the date of the interview describes the actual state
                   2308:        and not the date of a change in health state. The former idea was
                   2309:        to consider that at each interview the state was recorded
                   2310:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2311:        introduced the exact date of death then we should have modified
                   2312:        the contribution of an exact death to the likelihood. This new
                   2313:        contribution is smaller and very dependent of the step unit
                   2314:        stepm. It is no more the probability to die between last interview
                   2315:        and month of death but the probability to survive from last
                   2316:        interview up to one month before death multiplied by the
                   2317:        probability to die within a month. Thanks to Chris
                   2318:        Jackson for correcting this bug.  Former versions increased
                   2319:        mortality artificially. The bad side is that we add another loop
                   2320:        which slows down the processing. The difference can be up to 10%
                   2321:        lower mortality.
                   2322:          */
1.183     brouard  2323:        /* If, at the beginning of the maximization mostly, the
                   2324:           cumulative probability or probability to be dead is
                   2325:           constant (ie = 1) over time d, the difference is equal to
                   2326:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2327:           s1 at precedent wave, to be dead a month before current
                   2328:           wave is equal to probability, being at state s1 at
                   2329:           precedent wave, to be dead at mont of the current
                   2330:           wave. Then the observed probability (that this person died)
                   2331:           is null according to current estimated parameter. In fact,
                   2332:           it should be very low but not zero otherwise the log go to
                   2333:           infinity.
                   2334:        */
                   2335: /* #ifdef INFINITYORIGINAL */
                   2336: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2337: /* #else */
                   2338: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2339: /*         lli=log(mytinydouble); */
                   2340: /*       else */
                   2341: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2342: /* #endif */
                   2343:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2344: 
                   2345:        } else if  (s2==-2) {
                   2346:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2347:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2348:          /*survp += out[s1][j]; */
                   2349:          lli= log(survp);
                   2350:        }
                   2351:        
                   2352:        else if  (s2==-4) { 
                   2353:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2354:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2355:          lli= log(survp); 
                   2356:        } 
                   2357: 
                   2358:        else if  (s2==-5) { 
                   2359:          for (j=1,survp=0. ; j<=2; j++)  
                   2360:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2361:          lli= log(survp); 
                   2362:        } 
                   2363:        
                   2364:        else{
                   2365:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2366:          /*  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 */
                   2367:        } 
                   2368:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2369:        /*if(lli ==000.0)*/
                   2370:        /*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); */
                   2371:        ipmx +=1;
                   2372:        sw += weight[i];
                   2373:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2374:        /* if (lli < log(mytinydouble)){ */
                   2375:        /*   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); */
                   2376:        /*   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]); */
                   2377:        /* } */
1.126     brouard  2378:       } /* end of wave */
                   2379:     } /* end of individual */
                   2380:   }  else if(mle==2){
                   2381:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2382:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2383:       for(mi=1; mi<= wav[i]-1; mi++){
                   2384:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2385:          for (j=1;j<=nlstate+ndeath;j++){
                   2386:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2387:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2388:          }
                   2389:        for(d=0; d<=dh[mi][i]; d++){
                   2390:          newm=savm;
1.187     brouard  2391:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2392:          cov[2]=agexact;
                   2393:          if(nagesqr==1)
                   2394:            cov[3]= agexact*agexact;
1.126     brouard  2395:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2396:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2397:          }
                   2398:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2399:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2400:          savm=oldm;
                   2401:          oldm=newm;
                   2402:        } /* end mult */
                   2403:       
                   2404:        s1=s[mw[mi][i]][i];
                   2405:        s2=s[mw[mi+1][i]][i];
                   2406:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2407:        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 */
                   2408:        ipmx +=1;
                   2409:        sw += weight[i];
                   2410:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2411:       } /* end of wave */
                   2412:     } /* end of individual */
                   2413:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2414:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2415:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2416:       for(mi=1; mi<= wav[i]-1; mi++){
                   2417:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2418:          for (j=1;j<=nlstate+ndeath;j++){
                   2419:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2420:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2421:          }
                   2422:        for(d=0; d<dh[mi][i]; d++){
                   2423:          newm=savm;
1.187     brouard  2424:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2425:          cov[2]=agexact;
                   2426:          if(nagesqr==1)
                   2427:            cov[3]= agexact*agexact;
1.126     brouard  2428:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2429:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2430:          }
                   2431:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2432:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2433:          savm=oldm;
                   2434:          oldm=newm;
                   2435:        } /* end mult */
                   2436:       
                   2437:        s1=s[mw[mi][i]][i];
                   2438:        s2=s[mw[mi+1][i]][i];
                   2439:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2440:        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 */
                   2441:        ipmx +=1;
                   2442:        sw += weight[i];
                   2443:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2444:       } /* end of wave */
                   2445:     } /* end of individual */
                   2446:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2447:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2448:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2449:       for(mi=1; mi<= wav[i]-1; mi++){
                   2450:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2451:          for (j=1;j<=nlstate+ndeath;j++){
                   2452:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2453:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2454:          }
                   2455:        for(d=0; d<dh[mi][i]; d++){
                   2456:          newm=savm;
1.187     brouard  2457:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2458:          cov[2]=agexact;
                   2459:          if(nagesqr==1)
                   2460:            cov[3]= agexact*agexact;
1.126     brouard  2461:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2462:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2463:          }
                   2464:        
                   2465:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2466:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2467:          savm=oldm;
                   2468:          oldm=newm;
                   2469:        } /* end mult */
                   2470:       
                   2471:        s1=s[mw[mi][i]][i];
                   2472:        s2=s[mw[mi+1][i]][i];
                   2473:        if( s2 > nlstate){ 
                   2474:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2475:        }else{
                   2476:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2477:        }
                   2478:        ipmx +=1;
                   2479:        sw += weight[i];
                   2480:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2481: /*     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]); */
                   2482:       } /* end of wave */
                   2483:     } /* end of individual */
                   2484:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2485:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2486:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2487:       for(mi=1; mi<= wav[i]-1; mi++){
                   2488:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2489:          for (j=1;j<=nlstate+ndeath;j++){
                   2490:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2491:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2492:          }
                   2493:        for(d=0; d<dh[mi][i]; d++){
                   2494:          newm=savm;
1.187     brouard  2495:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2496:          cov[2]=agexact;
                   2497:          if(nagesqr==1)
                   2498:            cov[3]= agexact*agexact;
1.126     brouard  2499:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2500:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2501:          }
                   2502:        
                   2503:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2504:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2505:          savm=oldm;
                   2506:          oldm=newm;
                   2507:        } /* end mult */
                   2508:       
                   2509:        s1=s[mw[mi][i]][i];
                   2510:        s2=s[mw[mi+1][i]][i];
                   2511:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2512:        ipmx +=1;
                   2513:        sw += weight[i];
                   2514:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2515:        /*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]);*/
                   2516:       } /* end of wave */
                   2517:     } /* end of individual */
                   2518:   } /* End of if */
                   2519:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2520:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2521:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2522:   return -l;
                   2523: }
                   2524: 
                   2525: /*************** log-likelihood *************/
                   2526: double funcone( double *x)
                   2527: {
                   2528:   /* Same as likeli but slower because of a lot of printf and if */
                   2529:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2530:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2531:   double **out;
                   2532:   double lli; /* Individual log likelihood */
                   2533:   double llt;
                   2534:   int s1, s2;
                   2535:   double bbh, survp;
1.187     brouard  2536:   double agexact;
1.126     brouard  2537:   /*extern weight */
                   2538:   /* We are differentiating ll according to initial status */
                   2539:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2540:   /*for(i=1;i<imx;i++) 
                   2541:     printf(" %d\n",s[4][i]);
                   2542:   */
                   2543:   cov[1]=1.;
                   2544: 
                   2545:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2546: 
                   2547:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2548:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2549:     for(mi=1; mi<= wav[i]-1; mi++){
                   2550:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2551:        for (j=1;j<=nlstate+ndeath;j++){
                   2552:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2553:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2554:        }
                   2555:       for(d=0; d<dh[mi][i]; d++){
                   2556:        newm=savm;
1.187     brouard  2557:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2558:        cov[2]=agexact;
                   2559:        if(nagesqr==1)
                   2560:          cov[3]= agexact*agexact;
1.126     brouard  2561:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2562:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2563:        }
1.187     brouard  2564: 
1.145     brouard  2565:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2566:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2567:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2568:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2569:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2570:        savm=oldm;
                   2571:        oldm=newm;
                   2572:       } /* end mult */
                   2573:       
                   2574:       s1=s[mw[mi][i]][i];
                   2575:       s2=s[mw[mi+1][i]][i];
                   2576:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2577:       /* bias is positive if real duration
                   2578:        * is higher than the multiple of stepm and negative otherwise.
                   2579:        */
                   2580:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2581:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2582:       } else if  (s2==-2) {
                   2583:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2584:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2585:        lli= log(survp);
                   2586:       }else if (mle==1){
                   2587:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2588:       } else if(mle==2){
                   2589:        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 */
                   2590:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2591:        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 */
                   2592:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2593:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2594:       } else{  /* mle=0 back to 1 */
                   2595:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2596:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2597:       } /* End of if */
                   2598:       ipmx +=1;
                   2599:       sw += weight[i];
                   2600:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2601:       /*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  2602:       if(globpr){
1.202     brouard  2603:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f\
1.126     brouard  2604:  %11.6f %11.6f %11.6f ", \
1.202     brouard  2605:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1.126     brouard  2606:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2607:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2608:          llt +=ll[k]*gipmx/gsw;
                   2609:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2610:        }
                   2611:        fprintf(ficresilk," %10.6f\n", -llt);
                   2612:       }
                   2613:     } /* end of wave */
                   2614:   } /* end of individual */
                   2615:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2616:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2617:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2618:   if(globpr==0){ /* First time we count the contributions and weights */
                   2619:     gipmx=ipmx;
                   2620:     gsw=sw;
                   2621:   }
                   2622:   return -l;
                   2623: }
                   2624: 
                   2625: 
                   2626: /*************** function likelione ***********/
                   2627: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2628: {
                   2629:   /* This routine should help understanding what is done with 
                   2630:      the selection of individuals/waves and
                   2631:      to check the exact contribution to the likelihood.
                   2632:      Plotting could be done.
                   2633:    */
                   2634:   int k;
                   2635: 
                   2636:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2637:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2638:     strcat(fileresilk,fileresu);
1.126     brouard  2639:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2640:       printf("Problem with resultfile: %s\n", fileresilk);
                   2641:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2642:     }
                   2643:     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
1.202     brouard  2644:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight 2wlli out sav ");
1.126     brouard  2645:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2646:     for(k=1; k<=nlstate; k++) 
                   2647:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2648:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2649:   }
                   2650: 
                   2651:   *fretone=(*funcone)(p);
                   2652:   if(*globpri !=0){
                   2653:     fclose(ficresilk);
1.202     brouard  2654:     fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle >= 1. You should at least run with mle >= 1 and 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.204   ! brouard  2655:     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> \
        !          2656: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
        !          2657:    fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
        !          2658: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.202     brouard  2659:     fflush(fichtm);
1.204   ! brouard  2660: 
        !          2661:     for (k=1; k<= nlstate ; k++) {
        !          2662:       fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
        !          2663: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
        !          2664: 
        !          2665:     }
1.126     brouard  2666:   } 
                   2667:   return;
                   2668: }
                   2669: 
                   2670: 
                   2671: /*********** Maximum Likelihood Estimation ***************/
                   2672: 
                   2673: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2674: {
1.165     brouard  2675:   int i,j, iter=0;
1.126     brouard  2676:   double **xi;
                   2677:   double fret;
                   2678:   double fretone; /* Only one call to likelihood */
                   2679:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2680: 
                   2681: #ifdef NLOPT
                   2682:   int creturn;
                   2683:   nlopt_opt opt;
                   2684:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2685:   double *lb;
                   2686:   double minf; /* the minimum objective value, upon return */
                   2687:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2688:   myfunc_data dinst, *d = &dinst;
                   2689: #endif
                   2690: 
                   2691: 
1.126     brouard  2692:   xi=matrix(1,npar,1,npar);
                   2693:   for (i=1;i<=npar;i++)
                   2694:     for (j=1;j<=npar;j++)
                   2695:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2696:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2697:   strcpy(filerespow,"POW_"); 
1.126     brouard  2698:   strcat(filerespow,fileres);
                   2699:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2700:     printf("Problem with resultfile: %s\n", filerespow);
                   2701:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2702:   }
                   2703:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2704:   for (i=1;i<=nlstate;i++)
                   2705:     for(j=1;j<=nlstate+ndeath;j++)
                   2706:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2707:   fprintf(ficrespow,"\n");
1.162     brouard  2708: #ifdef POWELL
1.126     brouard  2709:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2710: #endif
1.126     brouard  2711: 
1.162     brouard  2712: #ifdef NLOPT
                   2713: #ifdef NEWUOA
                   2714:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2715: #else
                   2716:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2717: #endif
                   2718:   lb=vector(0,npar-1);
                   2719:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2720:   nlopt_set_lower_bounds(opt, lb);
                   2721:   nlopt_set_initial_step1(opt, 0.1);
                   2722:   
                   2723:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2724:   d->function = func;
                   2725:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2726:   nlopt_set_min_objective(opt, myfunc, d);
                   2727:   nlopt_set_xtol_rel(opt, ftol);
                   2728:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2729:     printf("nlopt failed! %d\n",creturn); 
                   2730:   }
                   2731:   else {
                   2732:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2733:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2734:     iter=1; /* not equal */
                   2735:   }
                   2736:   nlopt_destroy(opt);
                   2737: #endif
1.126     brouard  2738:   free_matrix(xi,1,npar,1,npar);
                   2739:   fclose(ficrespow);
1.203     brouard  2740:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2741:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2742:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2743: 
                   2744: }
                   2745: 
                   2746: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2747: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2748: {
                   2749:   double  **a,**y,*x,pd;
1.203     brouard  2750:   /* double **hess; */
1.164     brouard  2751:   int i, j;
1.126     brouard  2752:   int *indx;
                   2753: 
                   2754:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2755:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2756:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2757:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2758:   double gompertz(double p[]);
1.203     brouard  2759:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2760: 
                   2761:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2762:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2763:   for (i=1;i<=npar;i++){
1.203     brouard  2764:     printf("%d-",i);fflush(stdout);
                   2765:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2766:    
                   2767:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2768:     
                   2769:     /*  printf(" %f ",p[i]);
                   2770:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2771:   }
                   2772:   
                   2773:   for (i=1;i<=npar;i++) {
                   2774:     for (j=1;j<=npar;j++)  {
                   2775:       if (j>i) { 
1.203     brouard  2776:        printf(".%d-%d",i,j);fflush(stdout);
                   2777:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2778:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2779:        
                   2780:        hess[j][i]=hess[i][j];    
                   2781:        /*printf(" %lf ",hess[i][j]);*/
                   2782:       }
                   2783:     }
                   2784:   }
                   2785:   printf("\n");
                   2786:   fprintf(ficlog,"\n");
                   2787: 
                   2788:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2789:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2790:   
                   2791:   a=matrix(1,npar,1,npar);
                   2792:   y=matrix(1,npar,1,npar);
                   2793:   x=vector(1,npar);
                   2794:   indx=ivector(1,npar);
                   2795:   for (i=1;i<=npar;i++)
                   2796:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2797:   ludcmp(a,npar,indx,&pd);
                   2798: 
                   2799:   for (j=1;j<=npar;j++) {
                   2800:     for (i=1;i<=npar;i++) x[i]=0;
                   2801:     x[j]=1;
                   2802:     lubksb(a,npar,indx,x);
                   2803:     for (i=1;i<=npar;i++){ 
                   2804:       matcov[i][j]=x[i];
                   2805:     }
                   2806:   }
                   2807: 
                   2808:   printf("\n#Hessian matrix#\n");
                   2809:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2810:   for (i=1;i<=npar;i++) { 
                   2811:     for (j=1;j<=npar;j++) { 
1.203     brouard  2812:       printf("%.6e ",hess[i][j]);
                   2813:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2814:     }
                   2815:     printf("\n");
                   2816:     fprintf(ficlog,"\n");
                   2817:   }
                   2818: 
1.203     brouard  2819:   /* printf("\n#Covariance matrix#\n"); */
                   2820:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2821:   /* for (i=1;i<=npar;i++) {  */
                   2822:   /*   for (j=1;j<=npar;j++) {  */
                   2823:   /*     printf("%.6e ",matcov[i][j]); */
                   2824:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2825:   /*   } */
                   2826:   /*   printf("\n"); */
                   2827:   /*   fprintf(ficlog,"\n"); */
                   2828:   /* } */
                   2829: 
1.126     brouard  2830:   /* Recompute Inverse */
1.203     brouard  2831:   /* for (i=1;i<=npar;i++) */
                   2832:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2833:   /* ludcmp(a,npar,indx,&pd); */
                   2834: 
                   2835:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2836: 
                   2837:   /* for (j=1;j<=npar;j++) { */
                   2838:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2839:   /*   x[j]=1; */
                   2840:   /*   lubksb(a,npar,indx,x); */
                   2841:   /*   for (i=1;i<=npar;i++){  */
                   2842:   /*     y[i][j]=x[i]; */
                   2843:   /*     printf("%.3e ",y[i][j]); */
                   2844:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2845:   /*   } */
                   2846:   /*   printf("\n"); */
                   2847:   /*   fprintf(ficlog,"\n"); */
                   2848:   /* } */
                   2849: 
                   2850:   /* Verifying the inverse matrix */
                   2851: #ifdef DEBUGHESS
                   2852:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2853: 
1.203     brouard  2854:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2855:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2856: 
                   2857:   for (j=1;j<=npar;j++) {
                   2858:     for (i=1;i<=npar;i++){ 
1.203     brouard  2859:       printf("%.2f ",y[i][j]);
                   2860:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2861:     }
                   2862:     printf("\n");
                   2863:     fprintf(ficlog,"\n");
                   2864:   }
1.203     brouard  2865: #endif
1.126     brouard  2866: 
                   2867:   free_matrix(a,1,npar,1,npar);
                   2868:   free_matrix(y,1,npar,1,npar);
                   2869:   free_vector(x,1,npar);
                   2870:   free_ivector(indx,1,npar);
1.203     brouard  2871:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2872: 
                   2873: 
                   2874: }
                   2875: 
                   2876: /*************** hessian matrix ****************/
                   2877: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2878: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2879:   int i;
                   2880:   int l=1, lmax=20;
1.203     brouard  2881:   double k1,k2, res, fx;
1.132     brouard  2882:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2883:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2884:   int k=0,kmax=10;
                   2885:   double l1;
                   2886: 
                   2887:   fx=func(x);
                   2888:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2889:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2890:     l1=pow(10,l);
                   2891:     delts=delt;
                   2892:     for(k=1 ; k <kmax; k=k+1){
                   2893:       delt = delta*(l1*k);
                   2894:       p2[theta]=x[theta] +delt;
1.145     brouard  2895:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2896:       p2[theta]=x[theta]-delt;
                   2897:       k2=func(p2)-fx;
                   2898:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  2899:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2900:       
1.203     brouard  2901: #ifdef DEBUGHESSII
1.126     brouard  2902:       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);
                   2903:       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);
                   2904: #endif
                   2905:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2906:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2907:        k=kmax;
                   2908:       }
                   2909:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2910:        k=kmax; l=lmax*10;
1.126     brouard  2911:       }
                   2912:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2913:        delts=delt;
                   2914:       }
1.203     brouard  2915:     } /* End loop k */
1.126     brouard  2916:   }
                   2917:   delti[theta]=delts;
                   2918:   return res; 
                   2919:   
                   2920: }
                   2921: 
1.203     brouard  2922: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2923: {
                   2924:   int i;
1.164     brouard  2925:   int l=1, lmax=20;
1.126     brouard  2926:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2927:   double p2[MAXPARM+1];
1.203     brouard  2928:   int k, kmax=1;
                   2929:   double v1, v2, cv12, lc1, lc2;
                   2930:   
1.126     brouard  2931:   fx=func(x);
1.203     brouard  2932:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  2933:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  2934:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2935:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2936:     k1=func(p2)-fx;
                   2937:   
1.203     brouard  2938:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2939:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2940:     k2=func(p2)-fx;
                   2941:   
1.203     brouard  2942:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   2943:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2944:     k3=func(p2)-fx;
                   2945:   
1.203     brouard  2946:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   2947:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2948:     k4=func(p2)-fx;
1.203     brouard  2949:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   2950:     if(k1*k2*k3*k4 <0.){
                   2951:       kmax=kmax+10;
                   2952:       if(kmax >=10){
                   2953:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   2954:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   2955:       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);
                   2956:       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);
                   2957:       }
                   2958:     }
                   2959: #ifdef DEBUGHESSIJ
                   2960:     v1=hess[thetai][thetai];
                   2961:     v2=hess[thetaj][thetaj];
                   2962:     cv12=res;
                   2963:     /* Computing eigen value of Hessian matrix */
                   2964:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   2965:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   2966:     if ((lc2 <0) || (lc1 <0) ){
                   2967:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   2968:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   2969:       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);
                   2970:       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);
                   2971:     }
1.126     brouard  2972: #endif
                   2973:   }
                   2974:   return res;
                   2975: }
                   2976: 
1.203     brouard  2977:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   2978: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   2979: /* { */
                   2980: /*   int i; */
                   2981: /*   int l=1, lmax=20; */
                   2982: /*   double k1,k2,k3,k4,res,fx; */
                   2983: /*   double p2[MAXPARM+1]; */
                   2984: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   2985: /*   int k=0,kmax=10; */
                   2986: /*   double l1; */
                   2987:   
                   2988: /*   fx=func(x); */
                   2989: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   2990: /*     l1=pow(10,l); */
                   2991: /*     delts=delt; */
                   2992: /*     for(k=1 ; k <kmax; k=k+1){ */
                   2993: /*       delt = delti*(l1*k); */
                   2994: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   2995: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   2996: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   2997: /*       k1=func(p2)-fx; */
                   2998:       
                   2999: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3000: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3001: /*       k2=func(p2)-fx; */
                   3002:       
                   3003: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3004: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3005: /*       k3=func(p2)-fx; */
                   3006:       
                   3007: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3008: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3009: /*       k4=func(p2)-fx; */
                   3010: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3011: /* #ifdef DEBUGHESSIJ */
                   3012: /*       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); */
                   3013: /*       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); */
                   3014: /* #endif */
                   3015: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3016: /*     k=kmax; */
                   3017: /*       } */
                   3018: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3019: /*     k=kmax; l=lmax*10; */
                   3020: /*       } */
                   3021: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3022: /*     delts=delt; */
                   3023: /*       } */
                   3024: /*     } /\* End loop k *\/ */
                   3025: /*   } */
                   3026: /*   delti[theta]=delts; */
                   3027: /*   return res;  */
                   3028: /* } */
                   3029: 
                   3030: 
1.126     brouard  3031: /************** Inverse of matrix **************/
                   3032: void ludcmp(double **a, int n, int *indx, double *d) 
                   3033: { 
                   3034:   int i,imax,j,k; 
                   3035:   double big,dum,sum,temp; 
                   3036:   double *vv; 
                   3037:  
                   3038:   vv=vector(1,n); 
                   3039:   *d=1.0; 
                   3040:   for (i=1;i<=n;i++) { 
                   3041:     big=0.0; 
                   3042:     for (j=1;j<=n;j++) 
                   3043:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3044:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3045:     vv[i]=1.0/big; 
                   3046:   } 
                   3047:   for (j=1;j<=n;j++) { 
                   3048:     for (i=1;i<j;i++) { 
                   3049:       sum=a[i][j]; 
                   3050:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3051:       a[i][j]=sum; 
                   3052:     } 
                   3053:     big=0.0; 
                   3054:     for (i=j;i<=n;i++) { 
                   3055:       sum=a[i][j]; 
                   3056:       for (k=1;k<j;k++) 
                   3057:        sum -= a[i][k]*a[k][j]; 
                   3058:       a[i][j]=sum; 
                   3059:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3060:        big=dum; 
                   3061:        imax=i; 
                   3062:       } 
                   3063:     } 
                   3064:     if (j != imax) { 
                   3065:       for (k=1;k<=n;k++) { 
                   3066:        dum=a[imax][k]; 
                   3067:        a[imax][k]=a[j][k]; 
                   3068:        a[j][k]=dum; 
                   3069:       } 
                   3070:       *d = -(*d); 
                   3071:       vv[imax]=vv[j]; 
                   3072:     } 
                   3073:     indx[j]=imax; 
                   3074:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3075:     if (j != n) { 
                   3076:       dum=1.0/(a[j][j]); 
                   3077:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3078:     } 
                   3079:   } 
                   3080:   free_vector(vv,1,n);  /* Doesn't work */
                   3081: ;
                   3082: } 
                   3083: 
                   3084: void lubksb(double **a, int n, int *indx, double b[]) 
                   3085: { 
                   3086:   int i,ii=0,ip,j; 
                   3087:   double sum; 
                   3088:  
                   3089:   for (i=1;i<=n;i++) { 
                   3090:     ip=indx[i]; 
                   3091:     sum=b[ip]; 
                   3092:     b[ip]=b[i]; 
                   3093:     if (ii) 
                   3094:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3095:     else if (sum) ii=i; 
                   3096:     b[i]=sum; 
                   3097:   } 
                   3098:   for (i=n;i>=1;i--) { 
                   3099:     sum=b[i]; 
                   3100:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3101:     b[i]=sum/a[i][i]; 
                   3102:   } 
                   3103: } 
                   3104: 
                   3105: void pstamp(FILE *fichier)
                   3106: {
1.196     brouard  3107:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3108: }
                   3109: 
                   3110: /************ Frequencies ********************/
                   3111: 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[])
                   3112: {  /* Some frequencies */
                   3113:   
1.164     brouard  3114:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3115:   int first;
                   3116:   double ***freq; /* Frequencies */
                   3117:   double *pp, **prop;
                   3118:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3119:   char fileresp[FILENAMELENGTH];
                   3120:   
                   3121:   pp=vector(1,nlstate);
                   3122:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3123:   strcpy(fileresp,"P_");
                   3124:   strcat(fileresp,fileresu);
1.126     brouard  3125:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3126:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3127:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3128:     exit(0);
                   3129:   }
                   3130:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3131:   j1=0;
                   3132:   
                   3133:   j=cptcoveff;
                   3134:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3135: 
                   3136:   first=1;
                   3137: 
1.169     brouard  3138:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3139:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3140:   /*    j1++; */
1.145     brouard  3141:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3142:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3143:        scanf("%d", i);*/
                   3144:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3145:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3146:          for(m=iagemin; m <= iagemax+3; m++)
                   3147:            freq[i][jk][m]=0;
1.143     brouard  3148:       
                   3149:       for (i=1; i<=nlstate; i++)  
                   3150:        for(m=iagemin; m <= iagemax+3; m++)
                   3151:          prop[i][m]=0;
1.126     brouard  3152:       
                   3153:       dateintsum=0;
                   3154:       k2cpt=0;
                   3155:       for (i=1; i<=imx; i++) {
                   3156:        bool=1;
1.144     brouard  3157:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3158:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3159:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3160:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3161:               bool=0;
1.198     brouard  3162:               /* 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", 
                   3163:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3164:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3165:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3166:             } 
1.126     brouard  3167:        }
1.144     brouard  3168:  
1.126     brouard  3169:        if (bool==1){
                   3170:          for(m=firstpass; m<=lastpass; m++){
                   3171:            k2=anint[m][i]+(mint[m][i]/12.);
                   3172:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3173:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3174:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3175:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3176:              if (m<lastpass) {
                   3177:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3178:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3179:              }
                   3180:              
                   3181:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3182:                dateintsum=dateintsum+k2;
                   3183:                k2cpt++;
                   3184:              }
                   3185:              /*}*/
                   3186:          }
                   3187:        }
1.145     brouard  3188:       } /* end i */
1.126     brouard  3189:        
                   3190:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3191:       pstamp(ficresp);
                   3192:       if  (cptcovn>0) {
                   3193:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3194:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3195:        fprintf(ficresp, "**********\n#");
1.143     brouard  3196:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3197:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3198:        fprintf(ficlog, "**********\n#");
1.126     brouard  3199:       }
                   3200:       for(i=1; i<=nlstate;i++) 
                   3201:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3202:       fprintf(ficresp, "\n");
                   3203:       
                   3204:       for(i=iagemin; i <= iagemax+3; i++){
                   3205:        if(i==iagemax+3){
                   3206:          fprintf(ficlog,"Total");
                   3207:        }else{
                   3208:          if(first==1){
                   3209:            first=0;
                   3210:            printf("See log file for details...\n");
                   3211:          }
                   3212:          fprintf(ficlog,"Age %d", i);
                   3213:        }
                   3214:        for(jk=1; jk <=nlstate ; jk++){
                   3215:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3216:            pp[jk] += freq[jk][m][i]; 
                   3217:        }
                   3218:        for(jk=1; jk <=nlstate ; jk++){
                   3219:          for(m=-1, pos=0; m <=0 ; m++)
                   3220:            pos += freq[jk][m][i];
                   3221:          if(pp[jk]>=1.e-10){
                   3222:            if(first==1){
1.132     brouard  3223:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3224:            }
                   3225:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3226:          }else{
                   3227:            if(first==1)
                   3228:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3229:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3230:          }
                   3231:        }
                   3232: 
                   3233:        for(jk=1; jk <=nlstate ; jk++){
                   3234:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3235:            pp[jk] += freq[jk][m][i];
                   3236:        }       
                   3237:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3238:          pos += pp[jk];
                   3239:          posprop += prop[jk][i];
                   3240:        }
                   3241:        for(jk=1; jk <=nlstate ; jk++){
                   3242:          if(pos>=1.e-5){
                   3243:            if(first==1)
                   3244:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3245:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3246:          }else{
                   3247:            if(first==1)
                   3248:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3249:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3250:          }
                   3251:          if( i <= iagemax){
                   3252:            if(pos>=1.e-5){
                   3253:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3254:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3255:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3256:            }
                   3257:            else
                   3258:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3259:          }
                   3260:        }
                   3261:        
                   3262:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3263:          for(m=-1; m <=nlstate+ndeath; m++)
                   3264:            if(freq[jk][m][i] !=0 ) {
                   3265:            if(first==1)
                   3266:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3267:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3268:            }
                   3269:        if(i <= iagemax)
                   3270:          fprintf(ficresp,"\n");
                   3271:        if(first==1)
                   3272:          printf("Others in log...\n");
                   3273:        fprintf(ficlog,"\n");
                   3274:       }
1.145     brouard  3275:       /*}*/
1.126     brouard  3276:   }
                   3277:   dateintmean=dateintsum/k2cpt; 
                   3278:  
                   3279:   fclose(ficresp);
                   3280:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3281:   free_vector(pp,1,nlstate);
                   3282:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3283:   /* End of Freq */
                   3284: }
                   3285: 
                   3286: /************ Prevalence ********************/
                   3287: 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)
                   3288: {  
                   3289:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3290:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3291:      We still use firstpass and lastpass as another selection.
                   3292:   */
                   3293:  
1.164     brouard  3294:   int i, m, jk, j1, bool, z1,j;
                   3295: 
                   3296:   double **prop;
                   3297:   double posprop; 
1.126     brouard  3298:   double  y2; /* in fractional years */
                   3299:   int iagemin, iagemax;
1.145     brouard  3300:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3301: 
                   3302:   iagemin= (int) agemin;
                   3303:   iagemax= (int) agemax;
                   3304:   /*pp=vector(1,nlstate);*/
                   3305:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3306:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3307:   j1=0;
                   3308:   
1.145     brouard  3309:   /*j=cptcoveff;*/
1.126     brouard  3310:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3311:   
1.145     brouard  3312:   first=1;
                   3313:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3314:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3315:       j1++;*/
1.126     brouard  3316:       
                   3317:       for (i=1; i<=nlstate; i++)  
                   3318:        for(m=iagemin; m <= iagemax+3; m++)
                   3319:          prop[i][m]=0.0;
                   3320:      
                   3321:       for (i=1; i<=imx; i++) { /* Each individual */
                   3322:        bool=1;
                   3323:        if  (cptcovn>0) {
                   3324:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3325:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3326:              bool=0;
                   3327:        } 
                   3328:        if (bool==1) { 
                   3329:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3330:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3331:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3332:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3333:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3334:              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); 
                   3335:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3336:                /*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]]);*/
                   3337:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3338:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3339:              } 
                   3340:            }
                   3341:          } /* end selection of waves */
                   3342:        }
                   3343:       }
                   3344:       for(i=iagemin; i <= iagemax+3; i++){  
                   3345:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3346:          posprop += prop[jk][i]; 
                   3347:        } 
1.145     brouard  3348:        
1.126     brouard  3349:        for(jk=1; jk <=nlstate ; jk++){     
                   3350:          if( i <=  iagemax){ 
                   3351:            if(posprop>=1.e-5){ 
                   3352:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3353:            } else{
                   3354:              if(first==1){
                   3355:                first=0;
                   3356:                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]);
                   3357:              }
                   3358:            }
1.126     brouard  3359:          } 
                   3360:        }/* end jk */ 
                   3361:       }/* end i */ 
1.145     brouard  3362:     /*} *//* end i1 */
                   3363:   } /* end j1 */
1.126     brouard  3364:   
                   3365:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3366:   /*free_vector(pp,1,nlstate);*/
                   3367:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3368: }  /* End of prevalence */
                   3369: 
                   3370: /************* Waves Concatenation ***************/
                   3371: 
                   3372: 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)
                   3373: {
                   3374:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3375:      Death is a valid wave (if date is known).
                   3376:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3377:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3378:      and mw[mi+1][i]. dh depends on stepm.
                   3379:      */
                   3380: 
                   3381:   int i, mi, m;
                   3382:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3383:      double sum=0., jmean=0.;*/
                   3384:   int first;
                   3385:   int j, k=0,jk, ju, jl;
                   3386:   double sum=0.;
                   3387:   first=0;
1.164     brouard  3388:   jmin=100000;
1.126     brouard  3389:   jmax=-1;
                   3390:   jmean=0.;
                   3391:   for(i=1; i<=imx; i++){
                   3392:     mi=0;
                   3393:     m=firstpass;
                   3394:     while(s[m][i] <= nlstate){
                   3395:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3396:        mw[++mi][i]=m;
                   3397:       if(m >=lastpass)
                   3398:        break;
                   3399:       else
                   3400:        m++;
                   3401:     }/* end while */
                   3402:     if (s[m][i] > nlstate){
                   3403:       mi++;    /* Death is another wave */
                   3404:       /* if(mi==0)  never been interviewed correctly before death */
                   3405:         /* Only death is a correct wave */
                   3406:       mw[mi][i]=m;
                   3407:     }
                   3408: 
                   3409:     wav[i]=mi;
                   3410:     if(mi==0){
                   3411:       nbwarn++;
                   3412:       if(first==0){
                   3413:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3414:        first=1;
                   3415:       }
                   3416:       if(first==1){
                   3417:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3418:       }
                   3419:     } /* end mi==0 */
                   3420:   } /* End individuals */
                   3421: 
                   3422:   for(i=1; i<=imx; i++){
                   3423:     for(mi=1; mi<wav[i];mi++){
                   3424:       if (stepm <=0)
                   3425:        dh[mi][i]=1;
                   3426:       else{
                   3427:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3428:          if (agedc[i] < 2*AGESUP) {
                   3429:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3430:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3431:            else if(j<0){
                   3432:              nberr++;
                   3433:              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]);
                   3434:              j=1; /* Temporary Dangerous patch */
                   3435:              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);
                   3436:              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]);
                   3437:              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);
                   3438:            }
                   3439:            k=k+1;
                   3440:            if (j >= jmax){
                   3441:              jmax=j;
                   3442:              ijmax=i;
                   3443:            }
                   3444:            if (j <= jmin){
                   3445:              jmin=j;
                   3446:              ijmin=i;
                   3447:            }
                   3448:            sum=sum+j;
                   3449:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3450:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3451:          }
                   3452:        }
                   3453:        else{
                   3454:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3455: /*       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]); */
                   3456: 
                   3457:          k=k+1;
                   3458:          if (j >= jmax) {
                   3459:            jmax=j;
                   3460:            ijmax=i;
                   3461:          }
                   3462:          else if (j <= jmin){
                   3463:            jmin=j;
                   3464:            ijmin=i;
                   3465:          }
                   3466:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3467:          /*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]);*/
                   3468:          if(j<0){
                   3469:            nberr++;
                   3470:            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]);
                   3471:            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]);
                   3472:          }
                   3473:          sum=sum+j;
                   3474:        }
                   3475:        jk= j/stepm;
                   3476:        jl= j -jk*stepm;
                   3477:        ju= j -(jk+1)*stepm;
                   3478:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3479:          if(jl==0){
                   3480:            dh[mi][i]=jk;
                   3481:            bh[mi][i]=0;
                   3482:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3483:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3484:            dh[mi][i]=jk+1;
                   3485:            bh[mi][i]=ju;
                   3486:          }
                   3487:        }else{
                   3488:          if(jl <= -ju){
                   3489:            dh[mi][i]=jk;
                   3490:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3491:                                 * is higher than the multiple of stepm and negative otherwise.
                   3492:                                 */
                   3493:          }
                   3494:          else{
                   3495:            dh[mi][i]=jk+1;
                   3496:            bh[mi][i]=ju;
                   3497:          }
                   3498:          if(dh[mi][i]==0){
                   3499:            dh[mi][i]=1; /* At least one step */
                   3500:            bh[mi][i]=ju; /* At least one step */
                   3501:            /*  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);*/
                   3502:          }
                   3503:        } /* end if mle */
                   3504:       }
                   3505:     } /* end wave */
                   3506:   }
                   3507:   jmean=sum/k;
                   3508:   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  3509:   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  3510:  }
                   3511: 
                   3512: /*********** Tricode ****************************/
1.145     brouard  3513: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3514: {
1.144     brouard  3515:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3516:   /*     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  3517:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3518:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3519:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3520:   */
1.130     brouard  3521: 
1.145     brouard  3522:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3523:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3524:   int cptcode=0; /* Modality max of covariates j */
                   3525:   int modmincovj=0; /* Modality min of covariates j */
                   3526: 
                   3527: 
1.126     brouard  3528:   cptcoveff=0; 
                   3529:  
1.144     brouard  3530:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3531: 
1.145     brouard  3532:   /* Loop on covariates without age and products */
1.186     brouard  3533:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3534:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3535:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3536:                               modality of this covariate Vj*/ 
1.145     brouard  3537:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3538:                                    * If product of Vn*Vm, still boolean *:
                   3539:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3540:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3541:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3542:                                      modality of the nth covariate of individual i. */
1.145     brouard  3543:       if (ij > modmaxcovj)
                   3544:         modmaxcovj=ij; 
                   3545:       else if (ij < modmincovj) 
                   3546:        modmincovj=ij; 
                   3547:       if ((ij < -1) && (ij > NCOVMAX)){
                   3548:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3549:        exit(1);
                   3550:       }else
1.136     brouard  3551:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3552:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3553:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3554:       /* getting the maximum value of the modality of the covariate
                   3555:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3556:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3557:     } /* end for loop on individuals i */
1.145     brouard  3558:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3559:     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  3560:     cptcode=modmaxcovj;
1.137     brouard  3561:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3562:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3563:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3564:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3565:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3566:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3567:        if( k != -1){
                   3568:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3569:                             covariate for which somebody answered excluding 
                   3570:                             undefined. Usually 2: 0 and 1. */
                   3571:        }
                   3572:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3573:                             covariate for which somebody answered including 
                   3574:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3575:       }
                   3576:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3577:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3578:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3579: 
1.136     brouard  3580:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3581:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3582:        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  3583:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3584:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3585:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3586:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3587:        nbcode[Tvar[j]][ij]=k;
                   3588:        nbcode[Tvar[j]][1]=0;
                   3589:        nbcode[Tvar[j]][2]=1;
                   3590:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3591:        To be continued (not working yet).
1.145     brouard  3592:     */
1.197     brouard  3593:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3594:     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*/
                   3595:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3596:          break;
                   3597:        }
                   3598:        ij++;
1.197     brouard  3599:        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  3600:        cptcode = ij; /* New max modality for covar j */
                   3601:     } /* end of loop on modality i=-1 to 1 or more */
                   3602:       
                   3603:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3604:     /*         /\*recode from 0 *\/ */
                   3605:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3606:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3607:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3608:     /*         } */
                   3609:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3610:     /*         if (ij > ncodemax[j]) { */
                   3611:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3612:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3613:     /*           break; */
                   3614:     /*         } */
                   3615:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3616:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3617:   
1.145     brouard  3618:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3619:   
1.187     brouard  3620:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3621:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3622:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3623:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3624:  } 
1.126     brouard  3625: 
1.192     brouard  3626:  ij=0;
1.145     brouard  3627:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3628:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3629:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3630:      ij++;
1.145     brouard  3631:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3632:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3633:    }else{
                   3634:        /* Tvaraff[ij]=0; */
                   3635:    }
1.126     brouard  3636:  }
1.192     brouard  3637:  /* ij--; */
1.144     brouard  3638:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3639: 
1.126     brouard  3640: }
                   3641: 
1.145     brouard  3642: 
1.126     brouard  3643: /*********** Health Expectancies ****************/
                   3644: 
1.127     brouard  3645: 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  3646: 
                   3647: {
                   3648:   /* Health expectancies, no variances */
1.164     brouard  3649:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3650:   int nhstepma, nstepma; /* Decreasing with age */
                   3651:   double age, agelim, hf;
                   3652:   double ***p3mat;
                   3653:   double eip;
                   3654: 
                   3655:   pstamp(ficreseij);
                   3656:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3657:   fprintf(ficreseij,"# Age");
                   3658:   for(i=1; i<=nlstate;i++){
                   3659:     for(j=1; j<=nlstate;j++){
                   3660:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3661:     }
                   3662:     fprintf(ficreseij," e%1d. ",i);
                   3663:   }
                   3664:   fprintf(ficreseij,"\n");
                   3665: 
                   3666:   
                   3667:   if(estepm < stepm){
                   3668:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3669:   }
                   3670:   else  hstepm=estepm;   
                   3671:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3672:    * This is mainly to measure the difference between two models: for example
                   3673:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3674:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3675:    * progression in between and thus overestimating or underestimating according
                   3676:    * to the curvature of the survival function. If, for the same date, we 
                   3677:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3678:    * to compare the new estimate of Life expectancy with the same linear 
                   3679:    * hypothesis. A more precise result, taking into account a more precise
                   3680:    * curvature will be obtained if estepm is as small as stepm. */
                   3681: 
                   3682:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3683:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3684:      nhstepm is the number of hstepm from age to agelim 
                   3685:      nstepm is the number of stepm from age to agelin. 
                   3686:      Look at hpijx to understand the reason of that which relies in memory size
                   3687:      and note for a fixed period like estepm months */
                   3688:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3689:      survival function given by stepm (the optimization length). Unfortunately it
                   3690:      means that if the survival funtion is printed only each two years of age and if
                   3691:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3692:      results. So we changed our mind and took the option of the best precision.
                   3693:   */
                   3694:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3695: 
                   3696:   agelim=AGESUP;
                   3697:   /* If stepm=6 months */
                   3698:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3699:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3700:     
                   3701: /* nhstepm age range expressed in number of stepm */
                   3702:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3703:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3704:   /* if (stepm >= YEARM) hstepm=1;*/
                   3705:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3706:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3707: 
                   3708:   for (age=bage; age<=fage; age ++){ 
                   3709:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3710:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3711:     /* if (stepm >= YEARM) hstepm=1;*/
                   3712:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3713: 
                   3714:     /* If stepm=6 months */
                   3715:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3716:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3717:     
                   3718:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3719:     
                   3720:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3721:     
                   3722:     printf("%d|",(int)age);fflush(stdout);
                   3723:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3724:     
                   3725:     /* Computing expectancies */
                   3726:     for(i=1; i<=nlstate;i++)
                   3727:       for(j=1; j<=nlstate;j++)
                   3728:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3729:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3730:          
                   3731:          /* 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]);*/
                   3732: 
                   3733:        }
                   3734: 
                   3735:     fprintf(ficreseij,"%3.0f",age );
                   3736:     for(i=1; i<=nlstate;i++){
                   3737:       eip=0;
                   3738:       for(j=1; j<=nlstate;j++){
                   3739:        eip +=eij[i][j][(int)age];
                   3740:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3741:       }
                   3742:       fprintf(ficreseij,"%9.4f", eip );
                   3743:     }
                   3744:     fprintf(ficreseij,"\n");
                   3745:     
                   3746:   }
                   3747:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3748:   printf("\n");
                   3749:   fprintf(ficlog,"\n");
                   3750:   
                   3751: }
                   3752: 
1.127     brouard  3753: 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  3754: 
                   3755: {
                   3756:   /* Covariances of health expectancies eij and of total life expectancies according
                   3757:    to initial status i, ei. .
                   3758:   */
                   3759:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3760:   int nhstepma, nstepma; /* Decreasing with age */
                   3761:   double age, agelim, hf;
                   3762:   double ***p3matp, ***p3matm, ***varhe;
                   3763:   double **dnewm,**doldm;
                   3764:   double *xp, *xm;
                   3765:   double **gp, **gm;
                   3766:   double ***gradg, ***trgradg;
                   3767:   int theta;
                   3768: 
                   3769:   double eip, vip;
                   3770: 
                   3771:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3772:   xp=vector(1,npar);
                   3773:   xm=vector(1,npar);
                   3774:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3775:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3776:   
                   3777:   pstamp(ficresstdeij);
                   3778:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3779:   fprintf(ficresstdeij,"# Age");
                   3780:   for(i=1; i<=nlstate;i++){
                   3781:     for(j=1; j<=nlstate;j++)
                   3782:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3783:     fprintf(ficresstdeij," e%1d. ",i);
                   3784:   }
                   3785:   fprintf(ficresstdeij,"\n");
                   3786: 
                   3787:   pstamp(ficrescveij);
                   3788:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3789:   fprintf(ficrescveij,"# Age");
                   3790:   for(i=1; i<=nlstate;i++)
                   3791:     for(j=1; j<=nlstate;j++){
                   3792:       cptj= (j-1)*nlstate+i;
                   3793:       for(i2=1; i2<=nlstate;i2++)
                   3794:        for(j2=1; j2<=nlstate;j2++){
                   3795:          cptj2= (j2-1)*nlstate+i2;
                   3796:          if(cptj2 <= cptj)
                   3797:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3798:        }
                   3799:     }
                   3800:   fprintf(ficrescveij,"\n");
                   3801:   
                   3802:   if(estepm < stepm){
                   3803:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3804:   }
                   3805:   else  hstepm=estepm;   
                   3806:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3807:    * This is mainly to measure the difference between two models: for example
                   3808:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3809:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3810:    * progression in between and thus overestimating or underestimating according
                   3811:    * to the curvature of the survival function. If, for the same date, we 
                   3812:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3813:    * to compare the new estimate of Life expectancy with the same linear 
                   3814:    * hypothesis. A more precise result, taking into account a more precise
                   3815:    * curvature will be obtained if estepm is as small as stepm. */
                   3816: 
                   3817:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3818:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3819:      nhstepm is the number of hstepm from age to agelim 
                   3820:      nstepm is the number of stepm from age to agelin. 
                   3821:      Look at hpijx to understand the reason of that which relies in memory size
                   3822:      and note for a fixed period like estepm months */
                   3823:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3824:      survival function given by stepm (the optimization length). Unfortunately it
                   3825:      means that if the survival funtion is printed only each two years of age and if
                   3826:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3827:      results. So we changed our mind and took the option of the best precision.
                   3828:   */
                   3829:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3830: 
                   3831:   /* If stepm=6 months */
                   3832:   /* nhstepm age range expressed in number of stepm */
                   3833:   agelim=AGESUP;
                   3834:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3835:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3836:   /* if (stepm >= YEARM) hstepm=1;*/
                   3837:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3838:   
                   3839:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3840:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3841:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3842:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3843:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3844:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3845: 
                   3846:   for (age=bage; age<=fage; age ++){ 
                   3847:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3848:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3849:     /* if (stepm >= YEARM) hstepm=1;*/
                   3850:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3851: 
                   3852:     /* If stepm=6 months */
                   3853:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3854:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3855:     
                   3856:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3857: 
                   3858:     /* Computing  Variances of health expectancies */
                   3859:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3860:        decrease memory allocation */
                   3861:     for(theta=1; theta <=npar; theta++){
                   3862:       for(i=1; i<=npar; i++){ 
                   3863:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3864:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3865:       }
                   3866:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3867:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3868:   
                   3869:       for(j=1; j<= nlstate; j++){
                   3870:        for(i=1; i<=nlstate; i++){
                   3871:          for(h=0; h<=nhstepm-1; h++){
                   3872:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3873:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3874:          }
                   3875:        }
                   3876:       }
                   3877:      
                   3878:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3879:        for(h=0; h<=nhstepm-1; h++){
                   3880:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3881:        }
                   3882:     }/* End theta */
                   3883:     
                   3884:     
                   3885:     for(h=0; h<=nhstepm-1; h++)
                   3886:       for(j=1; j<=nlstate*nlstate;j++)
                   3887:        for(theta=1; theta <=npar; theta++)
                   3888:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3889:     
                   3890: 
                   3891:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3892:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3893:        varhe[ij][ji][(int)age] =0.;
                   3894: 
                   3895:      printf("%d|",(int)age);fflush(stdout);
                   3896:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3897:      for(h=0;h<=nhstepm-1;h++){
                   3898:       for(k=0;k<=nhstepm-1;k++){
                   3899:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3900:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3901:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3902:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3903:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3904:       }
                   3905:     }
                   3906: 
                   3907:     /* Computing expectancies */
                   3908:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3909:     for(i=1; i<=nlstate;i++)
                   3910:       for(j=1; j<=nlstate;j++)
                   3911:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3912:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3913:          
                   3914:          /* 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]);*/
                   3915: 
                   3916:        }
                   3917: 
                   3918:     fprintf(ficresstdeij,"%3.0f",age );
                   3919:     for(i=1; i<=nlstate;i++){
                   3920:       eip=0.;
                   3921:       vip=0.;
                   3922:       for(j=1; j<=nlstate;j++){
                   3923:        eip += eij[i][j][(int)age];
                   3924:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3925:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3926:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3927:       }
                   3928:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3929:     }
                   3930:     fprintf(ficresstdeij,"\n");
                   3931: 
                   3932:     fprintf(ficrescveij,"%3.0f",age );
                   3933:     for(i=1; i<=nlstate;i++)
                   3934:       for(j=1; j<=nlstate;j++){
                   3935:        cptj= (j-1)*nlstate+i;
                   3936:        for(i2=1; i2<=nlstate;i2++)
                   3937:          for(j2=1; j2<=nlstate;j2++){
                   3938:            cptj2= (j2-1)*nlstate+i2;
                   3939:            if(cptj2 <= cptj)
                   3940:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3941:          }
                   3942:       }
                   3943:     fprintf(ficrescveij,"\n");
                   3944:    
                   3945:   }
                   3946:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3947:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3948:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3949:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3950:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3951:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3952:   printf("\n");
                   3953:   fprintf(ficlog,"\n");
                   3954: 
                   3955:   free_vector(xm,1,npar);
                   3956:   free_vector(xp,1,npar);
                   3957:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3958:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3959:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3960: }
                   3961: 
                   3962: /************ Variance ******************/
1.203     brouard  3963:  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 *ncvyear, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126     brouard  3964: {
                   3965:   /* Variance of health expectancies */
                   3966:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3967:   /* double **newm;*/
1.169     brouard  3968:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3969:   
                   3970:   int movingaverage();
1.126     brouard  3971:   double **dnewm,**doldm;
                   3972:   double **dnewmp,**doldmp;
                   3973:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3974:   int k;
1.126     brouard  3975:   double *xp;
                   3976:   double **gp, **gm;  /* for var eij */
                   3977:   double ***gradg, ***trgradg; /*for var eij */
                   3978:   double **gradgp, **trgradgp; /* for var p point j */
                   3979:   double *gpp, *gmp; /* for var p point j */
                   3980:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3981:   double ***p3mat;
                   3982:   double age,agelim, hf;
                   3983:   double ***mobaverage;
                   3984:   int theta;
                   3985:   char digit[4];
                   3986:   char digitp[25];
                   3987: 
                   3988:   char fileresprobmorprev[FILENAMELENGTH];
                   3989: 
                   3990:   if(popbased==1){
                   3991:     if(mobilav!=0)
1.201     brouard  3992:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   3993:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  3994:   }
                   3995:   else 
1.201     brouard  3996:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  3997: 
                   3998:   if (mobilav!=0) {
                   3999:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4000:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4001:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4002:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4003:     }
                   4004:   }
                   4005: 
1.201     brouard  4006:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4007:   sprintf(digit,"%-d",ij);
                   4008:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4009:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4010:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4011:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4012:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4013:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4014:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4015:   }
                   4016:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4017:  
                   4018:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4019:   pstamp(ficresprobmorprev);
                   4020:   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);
                   4021:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4022:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4023:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4024:     for(i=1; i<=nlstate;i++)
                   4025:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4026:   }  
                   4027:   fprintf(ficresprobmorprev,"\n");
                   4028:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4029:   fprintf(ficgp,"\nunset title \n");
                   4030: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4031:   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");
                   4032:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4033: /*   } */
                   4034:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4035:   pstamp(ficresvij);
                   4036:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4037:   if(popbased==1)
1.128     brouard  4038:     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  4039:   else
                   4040:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4041:   fprintf(ficresvij,"# Age");
                   4042:   for(i=1; i<=nlstate;i++)
                   4043:     for(j=1; j<=nlstate;j++)
                   4044:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4045:   fprintf(ficresvij,"\n");
                   4046: 
                   4047:   xp=vector(1,npar);
                   4048:   dnewm=matrix(1,nlstate,1,npar);
                   4049:   doldm=matrix(1,nlstate,1,nlstate);
                   4050:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4051:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4052: 
                   4053:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4054:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4055:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4056:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4057:   
                   4058:   if(estepm < stepm){
                   4059:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4060:   }
                   4061:   else  hstepm=estepm;   
                   4062:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4063:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4064:      nhstepm is the number of hstepm from age to agelim 
                   4065:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  4066:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  4067:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4068:      survival function given by stepm (the optimization length). Unfortunately it
                   4069:      means that if the survival funtion is printed every two years of age and if
                   4070:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4071:      results. So we changed our mind and took the option of the best precision.
                   4072:   */
                   4073:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4074:   agelim = AGESUP;
                   4075:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4076:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4077:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4078:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4079:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4080:     gp=matrix(0,nhstepm,1,nlstate);
                   4081:     gm=matrix(0,nhstepm,1,nlstate);
                   4082: 
                   4083: 
                   4084:     for(theta=1; theta <=npar; theta++){
                   4085:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4086:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4087:       }
                   4088:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4089:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4090: 
                   4091:       if (popbased==1) {
                   4092:        if(mobilav ==0){
                   4093:          for(i=1; i<=nlstate;i++)
                   4094:            prlim[i][i]=probs[(int)age][i][ij];
                   4095:        }else{ /* mobilav */ 
                   4096:          for(i=1; i<=nlstate;i++)
                   4097:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4098:        }
                   4099:       }
                   4100:   
                   4101:       for(j=1; j<= nlstate; j++){
                   4102:        for(h=0; h<=nhstepm; h++){
                   4103:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4104:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4105:        }
                   4106:       }
                   4107:       /* This for computing probability of death (h=1 means
                   4108:          computed over hstepm matrices product = hstepm*stepm months) 
                   4109:          as a weighted average of prlim.
                   4110:       */
                   4111:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4112:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4113:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4114:       }    
                   4115:       /* end probability of death */
                   4116: 
                   4117:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4118:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4119:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4120:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
1.126     brouard  4121:  
                   4122:       if (popbased==1) {
                   4123:        if(mobilav ==0){
                   4124:          for(i=1; i<=nlstate;i++)
                   4125:            prlim[i][i]=probs[(int)age][i][ij];
                   4126:        }else{ /* mobilav */ 
                   4127:          for(i=1; i<=nlstate;i++)
                   4128:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4129:        }
                   4130:       }
                   4131: 
1.128     brouard  4132:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4133:        for(h=0; h<=nhstepm; h++){
                   4134:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4135:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4136:        }
                   4137:       }
                   4138:       /* This for computing probability of death (h=1 means
                   4139:          computed over hstepm matrices product = hstepm*stepm months) 
                   4140:          as a weighted average of prlim.
                   4141:       */
                   4142:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4143:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4144:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4145:       }    
                   4146:       /* end probability of death */
                   4147: 
                   4148:       for(j=1; j<= nlstate; j++) /* vareij */
                   4149:        for(h=0; h<=nhstepm; h++){
                   4150:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4151:        }
                   4152: 
                   4153:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4154:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4155:       }
                   4156: 
                   4157:     } /* End theta */
                   4158: 
                   4159:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4160: 
                   4161:     for(h=0; h<=nhstepm; h++) /* veij */
                   4162:       for(j=1; j<=nlstate;j++)
                   4163:        for(theta=1; theta <=npar; theta++)
                   4164:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4165: 
                   4166:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4167:       for(theta=1; theta <=npar; theta++)
                   4168:        trgradgp[j][theta]=gradgp[theta][j];
                   4169:   
                   4170: 
                   4171:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4172:     for(i=1;i<=nlstate;i++)
                   4173:       for(j=1;j<=nlstate;j++)
                   4174:        vareij[i][j][(int)age] =0.;
                   4175: 
                   4176:     for(h=0;h<=nhstepm;h++){
                   4177:       for(k=0;k<=nhstepm;k++){
                   4178:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4179:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4180:        for(i=1;i<=nlstate;i++)
                   4181:          for(j=1;j<=nlstate;j++)
                   4182:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4183:       }
                   4184:     }
                   4185:   
                   4186:     /* pptj */
                   4187:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4188:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4189:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4190:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4191:        varppt[j][i]=doldmp[j][i];
                   4192:     /* end ppptj */
                   4193:     /*  x centered again */
                   4194:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4195:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4196:  
                   4197:     if (popbased==1) {
                   4198:       if(mobilav ==0){
                   4199:        for(i=1; i<=nlstate;i++)
                   4200:          prlim[i][i]=probs[(int)age][i][ij];
                   4201:       }else{ /* mobilav */ 
                   4202:        for(i=1; i<=nlstate;i++)
                   4203:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4204:       }
                   4205:     }
                   4206:              
                   4207:     /* This for computing probability of death (h=1 means
                   4208:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4209:        as a weighted average of prlim.
                   4210:     */
                   4211:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4212:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4213:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4214:     }    
                   4215:     /* end probability of death */
                   4216: 
                   4217:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4218:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4219:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4220:       for(i=1; i<=nlstate;i++){
                   4221:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4222:       }
                   4223:     } 
                   4224:     fprintf(ficresprobmorprev,"\n");
                   4225: 
                   4226:     fprintf(ficresvij,"%.0f ",age );
                   4227:     for(i=1; i<=nlstate;i++)
                   4228:       for(j=1; j<=nlstate;j++){
                   4229:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4230:       }
                   4231:     fprintf(ficresvij,"\n");
                   4232:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4233:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4234:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4235:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4236:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4237:   } /* End age */
                   4238:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4239:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4240:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4241:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4242:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4243:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4244:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4245:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4246:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4247: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4248: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4249: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4250:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4251:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4252:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4253:   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  4254:   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  4255:   /*  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  4256: */
1.199     brouard  4257: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4258:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4259: 
                   4260:   free_vector(xp,1,npar);
                   4261:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4262:   free_matrix(dnewm,1,nlstate,1,npar);
                   4263:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4264:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4265:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4266:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4267:   fclose(ficresprobmorprev);
                   4268:   fflush(ficgp);
                   4269:   fflush(fichtm); 
                   4270: }  /* end varevsij */
                   4271: 
                   4272: /************ Variance of prevlim ******************/
1.203     brouard  4273:  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 *ncvyear, int ij, char strstart[])
1.126     brouard  4274: {
                   4275:   /* Variance of prevalence limit */
                   4276:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4277: 
1.126     brouard  4278:   double **dnewm,**doldm;
                   4279:   int i, j, nhstepm, hstepm;
                   4280:   double *xp;
                   4281:   double *gp, *gm;
                   4282:   double **gradg, **trgradg;
                   4283:   double age,agelim;
                   4284:   int theta;
                   4285:   
                   4286:   pstamp(ficresvpl);
                   4287:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4288:   fprintf(ficresvpl,"# Age");
                   4289:   for(i=1; i<=nlstate;i++)
                   4290:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4291:   fprintf(ficresvpl,"\n");
                   4292: 
                   4293:   xp=vector(1,npar);
                   4294:   dnewm=matrix(1,nlstate,1,npar);
                   4295:   doldm=matrix(1,nlstate,1,nlstate);
                   4296:   
                   4297:   hstepm=1*YEARM; /* Every year of age */
                   4298:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4299:   agelim = AGESUP;
                   4300:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4301:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4302:     if (stepm >= YEARM) hstepm=1;
                   4303:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4304:     gradg=matrix(1,npar,1,nlstate);
                   4305:     gp=vector(1,nlstate);
                   4306:     gm=vector(1,nlstate);
                   4307: 
                   4308:     for(theta=1; theta <=npar; theta++){
                   4309:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4310:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4311:       }
1.203     brouard  4312:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4313:       for(i=1;i<=nlstate;i++)
                   4314:        gp[i] = prlim[i][i];
                   4315:     
                   4316:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4317:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.203     brouard  4318:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4319:       for(i=1;i<=nlstate;i++)
                   4320:        gm[i] = prlim[i][i];
                   4321: 
                   4322:       for(i=1;i<=nlstate;i++)
                   4323:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4324:     } /* End theta */
                   4325: 
                   4326:     trgradg =matrix(1,nlstate,1,npar);
                   4327: 
                   4328:     for(j=1; j<=nlstate;j++)
                   4329:       for(theta=1; theta <=npar; theta++)
                   4330:        trgradg[j][theta]=gradg[theta][j];
                   4331: 
                   4332:     for(i=1;i<=nlstate;i++)
                   4333:       varpl[i][(int)age] =0.;
                   4334:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4335:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4336:     for(i=1;i<=nlstate;i++)
                   4337:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4338: 
                   4339:     fprintf(ficresvpl,"%.0f ",age );
                   4340:     for(i=1; i<=nlstate;i++)
                   4341:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4342:     fprintf(ficresvpl,"\n");
                   4343:     free_vector(gp,1,nlstate);
                   4344:     free_vector(gm,1,nlstate);
                   4345:     free_matrix(gradg,1,npar,1,nlstate);
                   4346:     free_matrix(trgradg,1,nlstate,1,npar);
                   4347:   } /* End age */
                   4348: 
                   4349:   free_vector(xp,1,npar);
                   4350:   free_matrix(doldm,1,nlstate,1,npar);
                   4351:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4352: 
                   4353: }
                   4354: 
                   4355: /************ Variance of one-step probabilities  ******************/
                   4356: 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[])
                   4357: {
1.164     brouard  4358:   int i, j=0,  k1, l1, tj;
1.126     brouard  4359:   int k2, l2, j1,  z1;
1.164     brouard  4360:   int k=0, l;
1.145     brouard  4361:   int first=1, first1, first2;
1.126     brouard  4362:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4363:   double **dnewm,**doldm;
                   4364:   double *xp;
                   4365:   double *gp, *gm;
                   4366:   double **gradg, **trgradg;
                   4367:   double **mu;
1.164     brouard  4368:   double age, cov[NCOVMAX+1];
1.126     brouard  4369:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4370:   int theta;
                   4371:   char fileresprob[FILENAMELENGTH];
                   4372:   char fileresprobcov[FILENAMELENGTH];
                   4373:   char fileresprobcor[FILENAMELENGTH];
                   4374:   double ***varpij;
                   4375: 
1.201     brouard  4376:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4377:   strcat(fileresprob,fileres);
                   4378:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4379:     printf("Problem with resultfile: %s\n", fileresprob);
                   4380:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4381:   }
1.201     brouard  4382:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4383:   strcat(fileresprobcov,fileresu);
1.126     brouard  4384:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4385:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4386:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4387:   }
1.201     brouard  4388:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4389:   strcat(fileresprobcor,fileresu);
1.126     brouard  4390:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4391:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4392:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4393:   }
                   4394:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4395:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4396:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4397:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4398:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4399:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4400:   pstamp(ficresprob);
                   4401:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4402:   fprintf(ficresprob,"# Age");
                   4403:   pstamp(ficresprobcov);
                   4404:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4405:   fprintf(ficresprobcov,"# Age");
                   4406:   pstamp(ficresprobcor);
                   4407:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4408:   fprintf(ficresprobcor,"# Age");
                   4409: 
                   4410: 
                   4411:   for(i=1; i<=nlstate;i++)
                   4412:     for(j=1; j<=(nlstate+ndeath);j++){
                   4413:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4414:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4415:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4416:     }  
                   4417:  /* fprintf(ficresprob,"\n");
                   4418:   fprintf(ficresprobcov,"\n");
                   4419:   fprintf(ficresprobcor,"\n");
                   4420:  */
1.131     brouard  4421:   xp=vector(1,npar);
1.126     brouard  4422:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4423:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4424:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4425:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4426:   first=1;
                   4427:   fprintf(ficgp,"\n# Routine varprob");
                   4428:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4429:   fprintf(fichtm,"\n");
                   4430: 
1.200     brouard  4431:   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  4432:   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);
                   4433:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4434: and drawn. It helps understanding how is the covariance between two incidences.\
                   4435:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4436:   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. \
                   4437: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4438: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4439: standard deviations wide on each axis. <br>\
                   4440:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4441:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4442: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4443: 
                   4444:   cov[1]=1;
1.145     brouard  4445:   /* tj=cptcoveff; */
                   4446:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4447:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4448:   j1=0;
1.145     brouard  4449:   for(j1=1; j1<=tj;j1++){
                   4450:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4451:     /*j1++;*/
1.126     brouard  4452:       if  (cptcovn>0) {
                   4453:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4454:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4455:        fprintf(ficresprob, "**********\n#\n");
                   4456:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4457:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4458:        fprintf(ficresprobcov, "**********\n#\n");
                   4459:        
                   4460:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4461:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4462:        fprintf(ficgp, "**********\n#\n");
                   4463:        
                   4464:        
                   4465:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4466:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4467:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4468:        
                   4469:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4470:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4471:        fprintf(ficresprobcor, "**********\n#");    
                   4472:       }
                   4473:       
1.145     brouard  4474:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4475:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4476:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4477:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4478:       for (age=bage; age<=fage; age ++){ 
                   4479:        cov[2]=age;
1.187     brouard  4480:        if(nagesqr==1)
                   4481:          cov[3]= age*age;
1.126     brouard  4482:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4483:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4484:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4485:                                                         * 1  1 1 1 1
                   4486:                                                         * 2  2 1 1 1
                   4487:                                                         * 3  1 2 1 1
                   4488:                                                         */
                   4489:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4490:        }
1.186     brouard  4491:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4492:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4493:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4494:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4495:        
                   4496:     
                   4497:        for(theta=1; theta <=npar; theta++){
                   4498:          for(i=1; i<=npar; i++)
                   4499:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4500:          
                   4501:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4502:          
                   4503:          k=0;
                   4504:          for(i=1; i<= (nlstate); i++){
                   4505:            for(j=1; j<=(nlstate+ndeath);j++){
                   4506:              k=k+1;
                   4507:              gp[k]=pmmij[i][j];
                   4508:            }
                   4509:          }
                   4510:          
                   4511:          for(i=1; i<=npar; i++)
                   4512:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4513:     
                   4514:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4515:          k=0;
                   4516:          for(i=1; i<=(nlstate); i++){
                   4517:            for(j=1; j<=(nlstate+ndeath);j++){
                   4518:              k=k+1;
                   4519:              gm[k]=pmmij[i][j];
                   4520:            }
                   4521:          }
                   4522:      
                   4523:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4524:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4525:        }
                   4526: 
                   4527:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4528:          for(theta=1; theta <=npar; theta++)
                   4529:            trgradg[j][theta]=gradg[theta][j];
                   4530:        
                   4531:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4532:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4533: 
                   4534:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4535:        
                   4536:        k=0;
                   4537:        for(i=1; i<=(nlstate); i++){
                   4538:          for(j=1; j<=(nlstate+ndeath);j++){
                   4539:            k=k+1;
                   4540:            mu[k][(int) age]=pmmij[i][j];
                   4541:          }
                   4542:        }
                   4543:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4544:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4545:            varpij[i][j][(int)age] = doldm[i][j];
                   4546: 
                   4547:        /*printf("\n%d ",(int)age);
                   4548:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4549:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4550:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4551:          }*/
                   4552: 
                   4553:        fprintf(ficresprob,"\n%d ",(int)age);
                   4554:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4555:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4556: 
                   4557:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4558:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4559:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4560:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4561:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4562:        }
                   4563:        i=0;
                   4564:        for (k=1; k<=(nlstate);k++){
                   4565:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4566:            i++;
1.126     brouard  4567:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4568:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4569:            for (j=1; j<=i;j++){
1.145     brouard  4570:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4571:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4572:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4573:            }
                   4574:          }
                   4575:        }/* end of loop for state */
                   4576:       } /* end of loop for age */
1.145     brouard  4577:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4578:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4579:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4580:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4581:       
1.126     brouard  4582:       /* Confidence intervalle of pij  */
                   4583:       /*
1.131     brouard  4584:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4585:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4586:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4587:        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);
                   4588:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4589:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4590:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4591:       */
                   4592: 
                   4593:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4594:       first1=1;first2=2;
1.126     brouard  4595:       for (k2=1; k2<=(nlstate);k2++){
                   4596:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4597:          if(l2==k2) continue;
                   4598:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4599:          for (k1=1; k1<=(nlstate);k1++){
                   4600:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4601:              if(l1==k1) continue;
                   4602:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4603:              if(i<=j) continue;
                   4604:              for (age=bage; age<=fage; age ++){ 
                   4605:                if ((int)age %5==0){
                   4606:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4607:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4608:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4609:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4610:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4611:                  c12=cv12/sqrt(v1*v2);
                   4612:                  /* Computing eigen value of matrix of covariance */
                   4613:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4614:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4615:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4616:                    if(first2==1){
                   4617:                      first1=0;
                   4618:                    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);
                   4619:                    }
                   4620:                    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);
                   4621:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4622:                    /* lc2=fabs(lc2); */
1.135     brouard  4623:                  }
                   4624: 
1.126     brouard  4625:                  /* Eigen vectors */
                   4626:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4627:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4628:                  v21=(lc1-v1)/cv12*v11;
                   4629:                  v12=-v21;
                   4630:                  v22=v11;
                   4631:                  tnalp=v21/v11;
                   4632:                  if(first1==1){
                   4633:                    first1=0;
                   4634:                    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);
                   4635:                  }
                   4636:                  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);
                   4637:                  /*printf(fignu*/
                   4638:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4639:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4640:                  if(first==1){
                   4641:                    first=0;
1.200     brouard  4642:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4643:                    fprintf(ficgp,"\nset parametric;unset label");
                   4644:                    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  4645:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4646:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4647:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4648: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4649:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4650:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4651:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4652:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4653:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4654:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4655:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4656:                    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",\
                   4657:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4658:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4659:                  }else{
                   4660:                    first=0;
                   4661:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4662:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4663:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4664:                    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",\
                   4665:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4666:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4667:                  }/* if first */
                   4668:                } /* age mod 5 */
                   4669:              } /* end loop age */
1.201     brouard  4670:              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  4671:              first=1;
                   4672:            } /*l12 */
                   4673:          } /* k12 */
                   4674:        } /*l1 */
                   4675:       }/* k1 */
1.169     brouard  4676:       /* } */ /* loop covariates */
1.126     brouard  4677:   }
                   4678:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4679:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4680:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4681:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4682:   free_vector(xp,1,npar);
                   4683:   fclose(ficresprob);
                   4684:   fclose(ficresprobcov);
                   4685:   fclose(ficresprobcor);
                   4686:   fflush(ficgp);
                   4687:   fflush(fichtmcov);
                   4688: }
                   4689: 
                   4690: 
                   4691: /******************* Printing html file ***********/
1.201     brouard  4692: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4693:                  int lastpass, int stepm, int weightopt, char model[],\
                   4694:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4695:                  int popforecast, int estepm ,\
                   4696:                  double jprev1, double mprev1,double anprev1, \
                   4697:                  double jprev2, double mprev2,double anprev2){
                   4698:   int jj1, k1, i1, cpt;
                   4699: 
                   4700:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4701:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4702: </ul>");
                   4703:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4704:  - 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  4705:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4706:    fprintf(fichtm,"\
                   4707:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4708:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4709:    fprintf(fichtm,"\
                   4710:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4711:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4712:    fprintf(fichtm,"\
1.128     brouard  4713:  - (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  4714:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4715:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4716:    fprintf(fichtm,"\
                   4717:  - Population projections by age and states: \
1.201     brouard  4718:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4719: 
                   4720: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4721: 
1.145     brouard  4722:  m=pow(2,cptcoveff);
1.126     brouard  4723:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4724: 
                   4725:  jj1=0;
                   4726:  for(k1=1; k1<=m;k1++){
1.192     brouard  4727:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4728:      jj1++;
                   4729:      if (cptcovn > 0) {
                   4730:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4731:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4732:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4733:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4734:        }
1.126     brouard  4735:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4736:      }
1.201     brouard  4737:      /* aij, bij */
                   4738:      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> \
                   4739: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4740:      /* Pij */
1.202     brouard  4741:      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  4742: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4743:      /* Quasi-incidences */
1.201     brouard  4744:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4745:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4746:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4747: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4748: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4749:      /* Survival functions (period) in state j */
                   4750:      for(cpt=1; cpt<=nlstate;cpt++){
                   4751:        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> \
                   4752: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4753:      }
                   4754:      /* State specific survival functions (period) */
                   4755:      for(cpt=1; cpt<=nlstate;cpt++){
                   4756:        fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
                   4757:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4758:  <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);
                   4759:      }
                   4760:      /* Period (stable) prevalence in each health state */
                   4761:      for(cpt=1; cpt<=nlstate;cpt++){
                   4762:        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> \
                   4763: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4764:      }
1.126     brouard  4765:      for(cpt=1; cpt<=nlstate;cpt++) {
1.201     brouard  4766:        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> \
                   4767: <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  4768:      }
1.192     brouard  4769:    /* } /\* end i1 *\/ */
1.126     brouard  4770:  }/* End k1 */
                   4771:  fprintf(fichtm,"</ul>");
                   4772: 
                   4773:  fprintf(fichtm,"\
                   4774: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4775:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  4776:  - 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  4777: But because parameters are usually highly correlated (a higher incidence of disability \
                   4778: and a higher incidence of recovery can give very close observed transition) it might \
                   4779: be very useful to look not only at linear confidence intervals estimated from the \
                   4780: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4781: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4782: covariance matrix of the one-step probabilities. \
                   4783: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4784: 
1.193     brouard  4785:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4786:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4787:  fprintf(fichtm,"\
                   4788:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4789:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4790: 
                   4791:  fprintf(fichtm,"\
                   4792:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4793:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4794:  fprintf(fichtm,"\
                   4795:  - 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): \
                   4796:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4797:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4798:  fprintf(fichtm,"\
                   4799:  - (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): \
                   4800:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4801:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4802:  fprintf(fichtm,"\
1.128     brouard  4803:  - 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  4804:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4805:  fprintf(fichtm,"\
1.128     brouard  4806:  - 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  4807:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4808:  fprintf(fichtm,"\
                   4809:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4810:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4811: 
                   4812: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4813: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4814: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4815: /*     <br>",fileres,fileres,fileres,fileres); */
                   4816: /*  else  */
                   4817: /*    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); */
                   4818:  fflush(fichtm);
                   4819:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4820: 
1.145     brouard  4821:  m=pow(2,cptcoveff);
1.126     brouard  4822:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4823: 
                   4824:  jj1=0;
                   4825:  for(k1=1; k1<=m;k1++){
1.192     brouard  4826:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4827:      jj1++;
                   4828:      if (cptcovn > 0) {
                   4829:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4830:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4831:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4832:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4833:      }
                   4834:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4835:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.199     brouard  4836: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.svg <br>\
1.201     brouard  4837: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  4838:      }
                   4839:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4840: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4841: true period expectancies (those weighted with period prevalences are also\
                   4842:  drawn in addition to the population based expectancies computed using\
1.201     brouard  4843:  observed and cahotic prevalences: %s_%d.svg<br>\
                   4844: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4845:    /* } /\* end i1 *\/ */
1.126     brouard  4846:  }/* End k1 */
                   4847:  fprintf(fichtm,"</ul>");
                   4848:  fflush(fichtm);
                   4849: }
                   4850: 
                   4851: /******************* Gnuplot file **************/
1.201     brouard  4852: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4853: 
                   4854:   char dirfileres[132],optfileres[132];
1.164     brouard  4855:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4856:   int ng=0;
1.201     brouard  4857:   int vpopbased;
1.126     brouard  4858: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4859: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4860: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4861: /*   } */
                   4862: 
                   4863:   /*#ifdef windows */
                   4864:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4865:     /*#endif */
                   4866:   m=pow(2,cptcoveff);
                   4867: 
1.202     brouard  4868:   /* Contribution to likelihood */
                   4869:   /* Plot the probability implied in the likelihood */
                   4870:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4871:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4872:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   4873:     fprintf(ficgp,"\nset ter png size 640, 480");
1.204   ! brouard  4874: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  4875:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   4876: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   4877:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204   ! brouard  4878:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
        !          4879:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
        !          4880:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
        !          4881:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
        !          4882:     for (i=1; i<= nlstate ; i ++) {
        !          4883:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
        !          4884:       fprintf(ficgp,"unset log;\n plot  \"%s\"",subdirf(fileresilk));
        !          4885:       fprintf(ficgp,"  u  2:($4 == %d && $5==%d ? $9 : 1/0):5 t \"p%d%d\" with points lc variable \\\n",i,1,i,1);
        !          4886:       for (j=2; j<= nlstate+ndeath ; j ++) {
        !          4887:        fprintf(ficgp,", \"\" u  2:($4 == %d && $5==%d ? $9 : 1/0):5 t \"p%d%d\" with points lc variable ",i,j,i,j);
        !          4888:       }
        !          4889:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
        !          4890:     }
        !          4891:     /* 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 */             
        !          4892:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
        !          4893:     /* 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  4894:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  4895:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   4896: 
1.126     brouard  4897:   strcpy(dirfileres,optionfilefiname);
                   4898:   strcpy(optfileres,"vpl");
                   4899:  /* 1eme*/
1.201     brouard  4900:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4901:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4902:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  4903:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   4904:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4905:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4906: set ylabel \"Probability\" \n\
1.199     brouard  4907: set ter svg size 640, 480\n\
1.201     brouard  4908: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4909: 
                   4910:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4911:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4912:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4913:      }
1.201     brouard  4914:      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  4915:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4916:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4917:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4918:      } 
1.201     brouard  4919:      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  4920:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4921:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4922:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4923:      }  
1.201     brouard  4924:      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));
                   4925:      fprintf(ficgp,"\nset out \n");
                   4926:     } /* k1 */
                   4927:   } /* cpt */
1.126     brouard  4928:   /*2 eme*/
1.153     brouard  4929:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4930:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  4931:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   4932:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   4933:       if(vpopbased==0)
                   4934:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   4935:       else
                   4936:        fprintf(ficgp,"\nreplot ");
                   4937:       for (i=1; i<= nlstate+1 ; i ++) {
                   4938:        k=2*i;
                   4939:        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);
                   4940:        for (j=1; j<= nlstate+1 ; j ++) {
                   4941:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4942:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4943:        }   
                   4944:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   4945:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   4946:        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);
                   4947:        for (j=1; j<= nlstate+1 ; j ++) {
                   4948:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4949:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4950:        }   
                   4951:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   4952:        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);
                   4953:        for (j=1; j<= nlstate+1 ; j ++) {
                   4954:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4955:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4956:        }   
                   4957:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4958:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   4959:       } /* state */
                   4960:     } /* vpopbased */
                   4961:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   4962:   } /* k1 */
1.126     brouard  4963:   /*3eme*/
                   4964:   
                   4965:   for (k1=1; k1<= m ; k1 ++) { 
                   4966:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4967:       /*       k=2+nlstate*(2*cpt-2); */
                   4968:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  4969:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  4970:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  4971: 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  4972:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4973:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4974:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4975:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4976:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4977:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4978:        
                   4979:       */
                   4980:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  4981:        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  4982:        /*      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);*/
                   4983:        
                   4984:       } 
1.201     brouard  4985:       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  4986:     }
                   4987:   }
                   4988:   
1.201     brouard  4989:   /* Survival functions (period) from state i in state j by initial state i */
                   4990:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4991:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   4992:       k=3;
                   4993:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   4994:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   4995:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   4996: set ter svg size 640, 480\n\
                   4997: unset log y\n\
                   4998: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4999:       for (i=1; i<= nlstate ; i ++){
                   5000:        if(i==1)
                   5001:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5002:        else
                   5003:          fprintf(ficgp,", '' ");
                   5004:        l=(nlstate+ndeath)*(i-1)+1;
                   5005:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5006:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5007:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5008:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5009:       } /* nlstate */
                   5010:       fprintf(ficgp,"\nset out\n");
                   5011:     } /* end cpt state*/ 
                   5012:   } /* end covariate */  
                   5013: 
                   5014:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5015:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5016:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5017:       k=3;
                   5018:       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);
                   5019:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5020:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5021: set ter svg size 640, 480\n\
                   5022: unset log y\n\
                   5023: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5024:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5025:        if(j==1)
                   5026:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5027:        else
                   5028:          fprintf(ficgp,", '' ");
                   5029:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5030:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5031:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5032:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5033:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5034:       } /* nlstate */
                   5035:       fprintf(ficgp,", '' ");
                   5036:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5037:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5038:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5039:        if(j < nlstate)
                   5040:          fprintf(ficgp,"$%d +",k+l);
                   5041:        else
                   5042:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5043:       }
                   5044:       fprintf(ficgp,"\nset out\n");
                   5045:     } /* end cpt state*/ 
                   5046:   } /* end covariate */  
                   5047: 
1.202     brouard  5048:   /* CV preval stable (period) for each covariate */
                   5049:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  5050:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  5051:       k=3;
1.153     brouard  5052:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  5053:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5054:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5055: set ter svg size 640, 480\n\
1.126     brouard  5056: unset log y\n\
1.153     brouard  5057: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5058:       for (i=1; i<= nlstate ; i ++){
                   5059:        if(i==1)
1.201     brouard  5060:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5061:        else
                   5062:          fprintf(ficgp,", '' ");
1.154     brouard  5063:        l=(nlstate+ndeath)*(i-1)+1;
                   5064:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5065:        for (j=2; j<= nlstate ; j ++)
                   5066:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5067:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5068:       } /* nlstate */
1.201     brouard  5069:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5070:     } /* end cpt state*/ 
                   5071:   } /* end covariate */  
1.201     brouard  5072: 
1.126     brouard  5073:   /* proba elementaires */
1.187     brouard  5074:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5075:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5076:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5077:     for(k=1; k <=(nlstate+ndeath); k++){
                   5078:       if (k != i) {
1.187     brouard  5079:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5080:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5081:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5082:          jk++; 
                   5083:        }
1.187     brouard  5084:        fprintf(ficgp,"\n");
1.126     brouard  5085:       }
                   5086:     }
                   5087:    }
1.187     brouard  5088:   fprintf(ficgp,"##############\n#\n");
                   5089: 
1.145     brouard  5090:   /*goto avoid;*/
1.200     brouard  5091:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5092:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5093:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5094:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5095:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5096:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5097:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5098:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5099:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5100:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5101:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5102:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5103:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5104:   fprintf(ficgp,"#\n");
1.201     brouard  5105:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5106:      fprintf(ficgp,"# ng=%d\n",ng);
                   5107:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5108:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5109:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5110:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5111:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5112:        if (ng==1){
                   5113:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5114:         fprintf(ficgp,"\nunset log y");
                   5115:        }else if (ng==2){
                   5116:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5117:         fprintf(ficgp,"\nset log y");
                   5118:        }else if (ng==3){
1.126     brouard  5119:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5120:         fprintf(ficgp,"\nset log y");
                   5121:        }else
                   5122:         fprintf(ficgp,"\nunset title ");
                   5123:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5124:        i=1;
                   5125:        for(k2=1; k2<=nlstate; k2++) {
                   5126:         k3=i;
                   5127:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5128:           if (k != k2){
1.201     brouard  5129:             switch( ng) {
                   5130:             case 1:
1.187     brouard  5131:               if(nagesqr==0)
1.201     brouard  5132:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5133:               else /* nagesqr =1 */
1.201     brouard  5134:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5135:               break;
                   5136:             case 2: /* ng=2 */
1.187     brouard  5137:               if(nagesqr==0)
                   5138:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5139:               else /* nagesqr =1 */
1.201     brouard  5140:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5141:               break;
                   5142:             case 3:
                   5143:               if(nagesqr==0)
                   5144:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5145:               else /* nagesqr =1 */
                   5146:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5147:               break;
                   5148:             }
1.141     brouard  5149:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5150:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5151:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5152:               if(ij <=cptcovage) { /* Bug valgrind */
                   5153:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5154:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5155:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5156:                   ij++;
                   5157:                 }
1.186     brouard  5158:               }
                   5159:               else
1.198     brouard  5160:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5161:             }
1.201     brouard  5162:             if(ng != 1){
                   5163:               fprintf(ficgp,")/(1");
1.126     brouard  5164:             
1.201     brouard  5165:               for(k1=1; k1 <=nlstate; k1++){ 
                   5166:                 if(nagesqr==0)
                   5167:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5168:                 else /* nagesqr =1 */
                   5169:                   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);
                   5170:                 
                   5171:                 ij=1;
                   5172:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5173:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5174:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5175:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5176:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5177:                       ij++;
                   5178:                     }
1.197     brouard  5179:                   }
1.201     brouard  5180:                   else
                   5181:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5182:                 }
1.201     brouard  5183:                 fprintf(ficgp,")");
1.126     brouard  5184:               }
                   5185:               fprintf(ficgp,")");
1.201     brouard  5186:               if(ng ==2)
                   5187:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5188:               else /* ng= 3 */
                   5189:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5190:             }else{ /* end ng <> 1 */
                   5191:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5192:             }
                   5193:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5194:             i=i+ncovmodel;
                   5195:           }
                   5196:         } /* end k */
                   5197:        } /* end k2 */
1.201     brouard  5198:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5199:      } /* end jk */
                   5200:    } /* end ng */
1.164     brouard  5201:  /* avoid: */
1.126     brouard  5202:    fflush(ficgp); 
                   5203: }  /* end gnuplot */
                   5204: 
                   5205: 
                   5206: /*************** Moving average **************/
                   5207: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5208: 
                   5209:   int i, cpt, cptcod;
                   5210:   int modcovmax =1;
                   5211:   int mobilavrange, mob;
                   5212:   double age;
                   5213: 
                   5214:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5215:                           a covariate has 2 modalities */
                   5216:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5217: 
                   5218:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5219:     if(mobilav==1) mobilavrange=5; /* default */
                   5220:     else mobilavrange=mobilav;
                   5221:     for (age=bage; age<=fage; age++)
                   5222:       for (i=1; i<=nlstate;i++)
                   5223:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5224:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5225:     /* We keep the original values on the extreme ages bage, fage and for 
                   5226:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5227:        we use a 5 terms etc. until the borders are no more concerned. 
                   5228:     */ 
                   5229:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5230:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5231:        for (i=1; i<=nlstate;i++){
                   5232:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5233:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5234:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5235:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5236:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5237:              }
                   5238:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5239:          }
                   5240:        }
                   5241:       }/* end age */
                   5242:     }/* end mob */
                   5243:   }else return -1;
                   5244:   return 0;
                   5245: }/* End movingaverage */
                   5246: 
                   5247: 
                   5248: /************** Forecasting ******************/
1.169     brouard  5249: 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  5250:   /* proj1, year, month, day of starting projection 
                   5251:      agemin, agemax range of age
                   5252:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5253:      anproj2 year of en of projection (same day and month as proj1).
                   5254:   */
1.164     brouard  5255:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5256:   double agec; /* generic age */
                   5257:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5258:   double *popeffectif,*popcount;
                   5259:   double ***p3mat;
                   5260:   double ***mobaverage;
                   5261:   char fileresf[FILENAMELENGTH];
                   5262: 
                   5263:   agelim=AGESUP;
                   5264:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5265:  
1.201     brouard  5266:   strcpy(fileresf,"F_"); 
                   5267:   strcat(fileresf,fileresu);
1.126     brouard  5268:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5269:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5270:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5271:   }
                   5272:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5273:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5274: 
                   5275:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5276: 
                   5277:   if (mobilav!=0) {
                   5278:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5279:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5280:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5281:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5282:     }
                   5283:   }
                   5284: 
                   5285:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5286:   if (stepm<=12) stepsize=1;
                   5287:   if(estepm < stepm){
                   5288:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5289:   }
                   5290:   else  hstepm=estepm;   
                   5291: 
                   5292:   hstepm=hstepm/stepm; 
                   5293:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5294:                                fractional in yp1 */
                   5295:   anprojmean=yp;
                   5296:   yp2=modf((yp1*12),&yp);
                   5297:   mprojmean=yp;
                   5298:   yp1=modf((yp2*30.5),&yp);
                   5299:   jprojmean=yp;
                   5300:   if(jprojmean==0) jprojmean=1;
                   5301:   if(mprojmean==0) jprojmean=1;
                   5302: 
                   5303:   i1=cptcoveff;
                   5304:   if (cptcovn < 1){i1=1;}
                   5305:   
                   5306:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5307:   
                   5308:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5309: 
                   5310: /*           if (h==(int)(YEARM*yearp)){ */
                   5311:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5312:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5313:       k=k+1;
                   5314:       fprintf(ficresf,"\n#******");
                   5315:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5316:        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  5317:       }
                   5318:       fprintf(ficresf,"******\n");
                   5319:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5320:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5321:        for(i=1; i<=nlstate;i++)              
                   5322:           fprintf(ficresf," p%d%d",i,j);
                   5323:        fprintf(ficresf," p.%d",j);
                   5324:       }
                   5325:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5326:        fprintf(ficresf,"\n");
                   5327:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5328: 
                   5329:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5330:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5331:          nhstepm = nhstepm/hstepm; 
                   5332:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5333:          oldm=oldms;savm=savms;
                   5334:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5335:        
                   5336:          for (h=0; h<=nhstepm; h++){
                   5337:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5338:               fprintf(ficresf,"\n");
                   5339:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5340:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5341:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5342:            } 
                   5343:            for(j=1; j<=nlstate+ndeath;j++) {
                   5344:              ppij=0.;
                   5345:              for(i=1; i<=nlstate;i++) {
                   5346:                if (mobilav==1) 
                   5347:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5348:                else {
                   5349:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5350:                }
                   5351:                if (h*hstepm/YEARM*stepm== yearp) {
                   5352:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5353:                }
                   5354:              } /* end i */
                   5355:              if (h*hstepm/YEARM*stepm==yearp) {
                   5356:                fprintf(ficresf," %.3f", ppij);
                   5357:              }
                   5358:            }/* end j */
                   5359:          } /* end h */
                   5360:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5361:        } /* end agec */
                   5362:       } /* end yearp */
                   5363:     } /* end cptcod */
                   5364:   } /* end  cptcov */
                   5365:        
                   5366:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5367: 
                   5368:   fclose(ficresf);
                   5369: }
                   5370: 
                   5371: /************** Forecasting *****not tested NB*************/
1.169     brouard  5372: 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  5373:   
                   5374:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5375:   int *popage;
                   5376:   double calagedatem, agelim, kk1, kk2;
                   5377:   double *popeffectif,*popcount;
                   5378:   double ***p3mat,***tabpop,***tabpopprev;
                   5379:   double ***mobaverage;
                   5380:   char filerespop[FILENAMELENGTH];
                   5381: 
                   5382:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5383:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5384:   agelim=AGESUP;
                   5385:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5386:   
                   5387:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5388:   
                   5389:   
1.201     brouard  5390:   strcpy(filerespop,"POP_"); 
                   5391:   strcat(filerespop,fileresu);
1.126     brouard  5392:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5393:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5394:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5395:   }
                   5396:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5397:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5398: 
                   5399:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5400: 
                   5401:   if (mobilav!=0) {
                   5402:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5403:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5404:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5405:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5406:     }
                   5407:   }
                   5408: 
                   5409:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5410:   if (stepm<=12) stepsize=1;
                   5411:   
                   5412:   agelim=AGESUP;
                   5413:   
                   5414:   hstepm=1;
                   5415:   hstepm=hstepm/stepm; 
                   5416:   
                   5417:   if (popforecast==1) {
                   5418:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5419:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5420:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5421:     } 
                   5422:     popage=ivector(0,AGESUP);
                   5423:     popeffectif=vector(0,AGESUP);
                   5424:     popcount=vector(0,AGESUP);
                   5425:     
                   5426:     i=1;   
                   5427:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5428:    
                   5429:     imx=i;
                   5430:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5431:   }
                   5432: 
                   5433:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5434:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5435:       k=k+1;
                   5436:       fprintf(ficrespop,"\n#******");
                   5437:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5438:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5439:       }
                   5440:       fprintf(ficrespop,"******\n");
                   5441:       fprintf(ficrespop,"# Age");
                   5442:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5443:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5444:       
                   5445:       for (cpt=0; cpt<=0;cpt++) { 
                   5446:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5447:        
                   5448:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5449:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5450:          nhstepm = nhstepm/hstepm; 
                   5451:          
                   5452:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5453:          oldm=oldms;savm=savms;
                   5454:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5455:        
                   5456:          for (h=0; h<=nhstepm; h++){
                   5457:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5458:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5459:            } 
                   5460:            for(j=1; j<=nlstate+ndeath;j++) {
                   5461:              kk1=0.;kk2=0;
                   5462:              for(i=1; i<=nlstate;i++) {              
                   5463:                if (mobilav==1) 
                   5464:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5465:                else {
                   5466:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5467:                }
                   5468:              }
                   5469:              if (h==(int)(calagedatem+12*cpt)){
                   5470:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5471:                  /*fprintf(ficrespop," %.3f", kk1);
                   5472:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5473:              }
                   5474:            }
                   5475:            for(i=1; i<=nlstate;i++){
                   5476:              kk1=0.;
                   5477:                for(j=1; j<=nlstate;j++){
                   5478:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5479:                }
                   5480:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5481:            }
                   5482: 
                   5483:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5484:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5485:          }
                   5486:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5487:        }
                   5488:       }
                   5489:  
                   5490:   /******/
                   5491: 
                   5492:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5493:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5494:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5495:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5496:          nhstepm = nhstepm/hstepm; 
                   5497:          
                   5498:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5499:          oldm=oldms;savm=savms;
                   5500:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5501:          for (h=0; h<=nhstepm; h++){
                   5502:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5503:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5504:            } 
                   5505:            for(j=1; j<=nlstate+ndeath;j++) {
                   5506:              kk1=0.;kk2=0;
                   5507:              for(i=1; i<=nlstate;i++) {              
                   5508:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5509:              }
                   5510:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5511:            }
                   5512:          }
                   5513:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5514:        }
                   5515:       }
                   5516:    } 
                   5517:   }
                   5518:  
                   5519:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5520: 
                   5521:   if (popforecast==1) {
                   5522:     free_ivector(popage,0,AGESUP);
                   5523:     free_vector(popeffectif,0,AGESUP);
                   5524:     free_vector(popcount,0,AGESUP);
                   5525:   }
                   5526:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5527:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5528:   fclose(ficrespop);
                   5529: } /* End of popforecast */
                   5530: 
                   5531: int fileappend(FILE *fichier, char *optionfich)
                   5532: {
                   5533:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5534:     printf("Problem with file: %s\n", optionfich);
                   5535:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5536:     return (0);
                   5537:   }
                   5538:   fflush(fichier);
                   5539:   return (1);
                   5540: }
                   5541: 
                   5542: 
                   5543: /**************** function prwizard **********************/
                   5544: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5545: {
                   5546: 
                   5547:   /* Wizard to print covariance matrix template */
                   5548: 
1.164     brouard  5549:   char ca[32], cb[32];
                   5550:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5551:   int numlinepar;
                   5552: 
                   5553:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5554:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5555:   for(i=1; i <=nlstate; i++){
                   5556:     jj=0;
                   5557:     for(j=1; j <=nlstate+ndeath; j++){
                   5558:       if(j==i) continue;
                   5559:       jj++;
                   5560:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5561:       printf("%1d%1d",i,j);
                   5562:       fprintf(ficparo,"%1d%1d",i,j);
                   5563:       for(k=1; k<=ncovmodel;k++){
                   5564:        /*        printf(" %lf",param[i][j][k]); */
                   5565:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5566:        printf(" 0.");
                   5567:        fprintf(ficparo," 0.");
                   5568:       }
                   5569:       printf("\n");
                   5570:       fprintf(ficparo,"\n");
                   5571:     }
                   5572:   }
                   5573:   printf("# Scales (for hessian or gradient estimation)\n");
                   5574:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5575:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5576:   for(i=1; i <=nlstate; i++){
                   5577:     jj=0;
                   5578:     for(j=1; j <=nlstate+ndeath; j++){
                   5579:       if(j==i) continue;
                   5580:       jj++;
                   5581:       fprintf(ficparo,"%1d%1d",i,j);
                   5582:       printf("%1d%1d",i,j);
                   5583:       fflush(stdout);
                   5584:       for(k=1; k<=ncovmodel;k++){
                   5585:        /*      printf(" %le",delti3[i][j][k]); */
                   5586:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5587:        printf(" 0.");
                   5588:        fprintf(ficparo," 0.");
                   5589:       }
                   5590:       numlinepar++;
                   5591:       printf("\n");
                   5592:       fprintf(ficparo,"\n");
                   5593:     }
                   5594:   }
                   5595:   printf("# Covariance matrix\n");
                   5596: /* # 121 Var(a12)\n\ */
                   5597: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5598: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5599: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5600: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5601: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5602: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5603: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5604:   fflush(stdout);
                   5605:   fprintf(ficparo,"# Covariance matrix\n");
                   5606:   /* # 121 Var(a12)\n\ */
                   5607:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5608:   /* #   ...\n\ */
                   5609:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5610:   
                   5611:   for(itimes=1;itimes<=2;itimes++){
                   5612:     jj=0;
                   5613:     for(i=1; i <=nlstate; i++){
                   5614:       for(j=1; j <=nlstate+ndeath; j++){
                   5615:        if(j==i) continue;
                   5616:        for(k=1; k<=ncovmodel;k++){
                   5617:          jj++;
                   5618:          ca[0]= k+'a'-1;ca[1]='\0';
                   5619:          if(itimes==1){
                   5620:            printf("#%1d%1d%d",i,j,k);
                   5621:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5622:          }else{
                   5623:            printf("%1d%1d%d",i,j,k);
                   5624:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5625:            /*  printf(" %.5le",matcov[i][j]); */
                   5626:          }
                   5627:          ll=0;
                   5628:          for(li=1;li <=nlstate; li++){
                   5629:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5630:              if(lj==li) continue;
                   5631:              for(lk=1;lk<=ncovmodel;lk++){
                   5632:                ll++;
                   5633:                if(ll<=jj){
                   5634:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5635:                  if(ll<jj){
                   5636:                    if(itimes==1){
                   5637:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5638:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5639:                    }else{
                   5640:                      printf(" 0.");
                   5641:                      fprintf(ficparo," 0.");
                   5642:                    }
                   5643:                  }else{
                   5644:                    if(itimes==1){
                   5645:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5646:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5647:                    }else{
                   5648:                      printf(" 0.");
                   5649:                      fprintf(ficparo," 0.");
                   5650:                    }
                   5651:                  }
                   5652:                }
                   5653:              } /* end lk */
                   5654:            } /* end lj */
                   5655:          } /* end li */
                   5656:          printf("\n");
                   5657:          fprintf(ficparo,"\n");
                   5658:          numlinepar++;
                   5659:        } /* end k*/
                   5660:       } /*end j */
                   5661:     } /* end i */
                   5662:   } /* end itimes */
                   5663: 
                   5664: } /* end of prwizard */
                   5665: /******************* Gompertz Likelihood ******************************/
                   5666: double gompertz(double x[])
                   5667: { 
                   5668:   double A,B,L=0.0,sump=0.,num=0.;
                   5669:   int i,n=0; /* n is the size of the sample */
                   5670: 
                   5671:   for (i=0;i<=imx-1 ; i++) {
                   5672:     sump=sump+weight[i];
                   5673:     /*    sump=sump+1;*/
                   5674:     num=num+1;
                   5675:   }
                   5676:  
                   5677:  
                   5678:   /* for (i=0; i<=imx; i++) 
                   5679:      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]);*/
                   5680: 
                   5681:   for (i=1;i<=imx ; i++)
                   5682:     {
                   5683:       if (cens[i] == 1 && wav[i]>1)
                   5684:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5685:       
                   5686:       if (cens[i] == 0 && wav[i]>1)
                   5687:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5688:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5689:       
                   5690:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5691:       if (wav[i] > 1 ) { /* ??? */
                   5692:        L=L+A*weight[i];
                   5693:        /*      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]);*/
                   5694:       }
                   5695:     }
                   5696: 
                   5697:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5698:  
                   5699:   return -2*L*num/sump;
                   5700: }
                   5701: 
1.136     brouard  5702: #ifdef GSL
                   5703: /******************* Gompertz_f Likelihood ******************************/
                   5704: double gompertz_f(const gsl_vector *v, void *params)
                   5705: { 
                   5706:   double A,B,LL=0.0,sump=0.,num=0.;
                   5707:   double *x= (double *) v->data;
                   5708:   int i,n=0; /* n is the size of the sample */
                   5709: 
                   5710:   for (i=0;i<=imx-1 ; i++) {
                   5711:     sump=sump+weight[i];
                   5712:     /*    sump=sump+1;*/
                   5713:     num=num+1;
                   5714:   }
                   5715:  
                   5716:  
                   5717:   /* for (i=0; i<=imx; i++) 
                   5718:      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]);*/
                   5719:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5720:   for (i=1;i<=imx ; i++)
                   5721:     {
                   5722:       if (cens[i] == 1 && wav[i]>1)
                   5723:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5724:       
                   5725:       if (cens[i] == 0 && wav[i]>1)
                   5726:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5727:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5728:       
                   5729:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5730:       if (wav[i] > 1 ) { /* ??? */
                   5731:        LL=LL+A*weight[i];
                   5732:        /*      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]);*/
                   5733:       }
                   5734:     }
                   5735: 
                   5736:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5737:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5738:  
                   5739:   return -2*LL*num/sump;
                   5740: }
                   5741: #endif
                   5742: 
1.126     brouard  5743: /******************* Printing html file ***********/
1.201     brouard  5744: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5745:                  int lastpass, int stepm, int weightopt, char model[],\
                   5746:                  int imx,  double p[],double **matcov,double agemortsup){
                   5747:   int i,k;
                   5748: 
                   5749:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5750:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5751:   for (i=1;i<=2;i++) 
                   5752:     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  5753:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5754:   fprintf(fichtm,"</ul>");
                   5755: 
                   5756: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5757: 
                   5758:  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>");
                   5759: 
                   5760:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5761:    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]);
                   5762: 
                   5763:  
                   5764:   fflush(fichtm);
                   5765: }
                   5766: 
                   5767: /******************* Gnuplot file **************/
1.201     brouard  5768: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5769: 
                   5770:   char dirfileres[132],optfileres[132];
1.164     brouard  5771: 
1.126     brouard  5772:   int ng;
                   5773: 
                   5774: 
                   5775:   /*#ifdef windows */
                   5776:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5777:     /*#endif */
                   5778: 
                   5779: 
                   5780:   strcpy(dirfileres,optionfilefiname);
                   5781:   strcpy(optfileres,"vpl");
1.199     brouard  5782:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5783:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5784:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5785:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5786:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5787: 
                   5788: } 
                   5789: 
1.136     brouard  5790: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5791: {
1.126     brouard  5792: 
1.136     brouard  5793:   /*-------- data file ----------*/
                   5794:   FILE *fic;
                   5795:   char dummy[]="                         ";
1.164     brouard  5796:   int i=0, j=0, n=0;
1.136     brouard  5797:   int linei, month, year,iout;
                   5798:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5799:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5800:   char *stratrunc;
                   5801:   int lstra;
1.126     brouard  5802: 
                   5803: 
1.136     brouard  5804:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5805:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5806:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5807:   }
1.126     brouard  5808: 
1.136     brouard  5809:   i=1;
                   5810:   linei=0;
                   5811:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5812:     linei=linei+1;
                   5813:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5814:       if(line[j] == '\t')
                   5815:        line[j] = ' ';
                   5816:     }
                   5817:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5818:       ;
                   5819:     };
                   5820:     line[j+1]=0;  /* Trims blanks at end of line */
                   5821:     if(line[0]=='#'){
                   5822:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5823:       printf("Comment line\n%s\n",line);
                   5824:       continue;
                   5825:     }
                   5826:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5827:     strcpy(line, linetmp);
1.136     brouard  5828:   
1.126     brouard  5829: 
1.136     brouard  5830:     for (j=maxwav;j>=1;j--){
1.137     brouard  5831:       cutv(stra, strb, line, ' '); 
1.136     brouard  5832:       if(strb[0]=='.') { /* Missing status */
                   5833:        lval=-1;
                   5834:       }else{
                   5835:        errno=0;
                   5836:        lval=strtol(strb,&endptr,10); 
                   5837:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5838:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5839:          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);
                   5840:          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  5841:          return 1;
                   5842:        }
                   5843:       }
                   5844:       s[j][i]=lval;
                   5845:       
                   5846:       strcpy(line,stra);
                   5847:       cutv(stra, strb,line,' ');
1.169     brouard  5848:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5849:       }
1.169     brouard  5850:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5851:        month=99;
                   5852:        year=9999;
                   5853:       }else{
1.141     brouard  5854:        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);
                   5855:        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  5856:        return 1;
                   5857:       }
                   5858:       anint[j][i]= (double) year; 
                   5859:       mint[j][i]= (double)month; 
                   5860:       strcpy(line,stra);
                   5861:     } /* ENd Waves */
                   5862:     
                   5863:     cutv(stra, strb,line,' '); 
1.169     brouard  5864:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5865:     }
1.169     brouard  5866:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5867:       month=99;
                   5868:       year=9999;
                   5869:     }else{
1.141     brouard  5870:       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);
                   5871:        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  5872:        return 1;
                   5873:     }
                   5874:     andc[i]=(double) year; 
                   5875:     moisdc[i]=(double) month; 
                   5876:     strcpy(line,stra);
                   5877:     
                   5878:     cutv(stra, strb,line,' '); 
1.169     brouard  5879:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5880:     }
1.169     brouard  5881:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5882:       month=99;
                   5883:       year=9999;
                   5884:     }else{
1.141     brouard  5885:       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);
                   5886:       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  5887:        return 1;
                   5888:     }
                   5889:     if (year==9999) {
1.141     brouard  5890:       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);
                   5891:       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  5892:        return 1;
1.126     brouard  5893: 
1.136     brouard  5894:     }
                   5895:     annais[i]=(double)(year);
                   5896:     moisnais[i]=(double)(month); 
                   5897:     strcpy(line,stra);
                   5898:     
                   5899:     cutv(stra, strb,line,' '); 
                   5900:     errno=0;
                   5901:     dval=strtod(strb,&endptr); 
                   5902:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5903:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5904:       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  5905:       fflush(ficlog);
                   5906:       return 1;
                   5907:     }
                   5908:     weight[i]=dval; 
                   5909:     strcpy(line,stra);
                   5910:     
                   5911:     for (j=ncovcol;j>=1;j--){
                   5912:       cutv(stra, strb,line,' '); 
                   5913:       if(strb[0]=='.') { /* Missing status */
                   5914:        lval=-1;
                   5915:       }else{
                   5916:        errno=0;
                   5917:        lval=strtol(strb,&endptr,10); 
                   5918:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5919:          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);
                   5920:          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  5921:          return 1;
                   5922:        }
                   5923:       }
                   5924:       if(lval <-1 || lval >1){
1.141     brouard  5925:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5926:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5927:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5928:  For example, for multinomial values like 1, 2 and 3,\n \
                   5929:  build V1=0 V2=0 for the reference value (1),\n \
                   5930:         V1=1 V2=0 for (2) \n \
                   5931:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5932:  output of IMaCh is often meaningless.\n \
                   5933:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5934:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5935:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5936:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5937:  For example, for multinomial values like 1, 2 and 3,\n \
                   5938:  build V1=0 V2=0 for the reference value (1),\n \
                   5939:         V1=1 V2=0 for (2) \n \
                   5940:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5941:  output of IMaCh is often meaningless.\n \
                   5942:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5943:        return 1;
                   5944:       }
                   5945:       covar[j][i]=(double)(lval);
                   5946:       strcpy(line,stra);
                   5947:     }  
                   5948:     lstra=strlen(stra);
                   5949:      
                   5950:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5951:       stratrunc = &(stra[lstra-9]);
                   5952:       num[i]=atol(stratrunc);
                   5953:     }
                   5954:     else
                   5955:       num[i]=atol(stra);
                   5956:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5957:       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;}*/
                   5958:     
                   5959:     i=i+1;
                   5960:   } /* End loop reading  data */
1.126     brouard  5961: 
1.136     brouard  5962:   *imax=i-1; /* Number of individuals */
                   5963:   fclose(fic);
                   5964:  
                   5965:   return (0);
1.164     brouard  5966:   /* endread: */
1.136     brouard  5967:     printf("Exiting readdata: ");
                   5968:     fclose(fic);
                   5969:     return (1);
1.126     brouard  5970: 
                   5971: 
                   5972: 
1.136     brouard  5973: }
1.145     brouard  5974: void removespace(char *str) {
                   5975:   char *p1 = str, *p2 = str;
                   5976:   do
                   5977:     while (*p2 == ' ')
                   5978:       p2++;
1.169     brouard  5979:   while (*p1++ == *p2++);
1.145     brouard  5980: }
                   5981: 
                   5982: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5983:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5984:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5985:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5986:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5987:    * - cptcovage number of covariates with age*products =2
                   5988:    * - cptcovs number of simple covariates
                   5989:    * - 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
                   5990:    *     which is a new column after the 9 (ncovcol) variables. 
                   5991:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5992:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5993:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5994:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5995:  */
1.136     brouard  5996: {
1.145     brouard  5997:   int i, j, k, ks;
1.164     brouard  5998:   int  j1, k1, k2;
1.136     brouard  5999:   char modelsav[80];
1.145     brouard  6000:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6001:   char *strpt;
1.136     brouard  6002: 
1.145     brouard  6003:   /*removespace(model);*/
1.136     brouard  6004:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6005:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6006:     if (strstr(model,"AGE") !=0){
1.192     brouard  6007:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6008:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6009:       return 1;
                   6010:     }
1.141     brouard  6011:     if (strstr(model,"v") !=0){
                   6012:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6013:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6014:       return 1;
                   6015:     }
1.187     brouard  6016:     strcpy(modelsav,model); 
                   6017:     if ((strpt=strstr(model,"age*age")) !=0){
                   6018:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6019:       if(strpt != model){
                   6020:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6021:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6022:  corresponding column of parameters.\n",model);
                   6023:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6024:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6025:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6026:       return 1;
                   6027:     }
                   6028: 
                   6029:       nagesqr=1;
                   6030:       if (strstr(model,"+age*age") !=0)
                   6031:        substrchaine(modelsav, model, "+age*age");
                   6032:       else if (strstr(model,"age*age+") !=0)
                   6033:        substrchaine(modelsav, model, "age*age+");
                   6034:       else 
                   6035:        substrchaine(modelsav, model, "age*age");
                   6036:     }else
                   6037:       nagesqr=0;
                   6038:     if (strlen(modelsav) >1){
                   6039:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6040:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6041:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6042:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6043:                   * cst, age and age*age 
                   6044:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6045:                   /* including age products which are counted in cptcovage.
                   6046:                  * but the covariates which are products must be treated 
                   6047:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6048:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6049:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6050: 
                   6051:     
                   6052:       /*   Design
                   6053:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6054:        *  <          ncovcol=8                >
                   6055:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6056:        *   k=  1    2      3       4     5       6      7        8
                   6057:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6058:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6059:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6060:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6061:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6062:        *  Tage[++cptcovage]=k
                   6063:        *       if products, new covar are created after ncovcol with k1
                   6064:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6065:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6066:        *  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
                   6067:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6068:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6069:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6070:        *  <          ncovcol=8                >
                   6071:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6072:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6073:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6074:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6075:        * p Tprod[1]@2={                         6, 5}
                   6076:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6077:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6078:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6079:        *How to reorganize?
                   6080:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6081:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6082:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6083:        * Struct []
                   6084:        */
1.145     brouard  6085: 
1.187     brouard  6086:       /* This loop fills the array Tvar from the string 'model'.*/
                   6087:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6088:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6089:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6090:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6091:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6092:       /*       k=1 Tvar[1]=2 (from V2) */
                   6093:       /*       k=5 Tvar[5] */
                   6094:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6095:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6096:       /*       } */
1.198     brouard  6097:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6098:       /*
                   6099:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6100:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6101:         Tvar[k]=0;
1.187     brouard  6102:       cptcovage=0;
                   6103:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6104:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6105:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6106:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6107:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6108:        /*scanf("%d",i);*/
                   6109:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6110:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6111:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6112:            /* covar is not filled and then is empty */
                   6113:            cptcovprod--;
                   6114:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6115:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6116:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6117:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6118:            /*printf("stre=%s ", stre);*/
                   6119:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6120:            cptcovprod--;
                   6121:            cutl(stre,strb,strc,'V');
                   6122:            Tvar[k]=atoi(stre);
                   6123:            cptcovage++;
                   6124:            Tage[cptcovage]=k;
                   6125:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6126:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6127:            cptcovn++;
                   6128:            cptcovprodnoage++;k1++;
                   6129:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6130:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6131:                                   because this model-covariate is a construction we invent a new column
                   6132:                                   ncovcol + k1
                   6133:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6134:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6135:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6136:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6137:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6138:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6139:            k2=k2+2;
                   6140:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6141:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6142:            for (i=1; i<=lastobs;i++){
                   6143:              /* Computes the new covariate which is a product of
                   6144:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6145:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6146:            }
                   6147:          } /* End age is not in the model */
                   6148:        } /* End if model includes a product */
                   6149:        else { /* no more sum */
                   6150:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6151:          /*  scanf("%d",i);*/
                   6152:          cutl(strd,strc,strb,'V');
                   6153:          ks++; /**< Number of simple covariates */
1.145     brouard  6154:          cptcovn++;
1.187     brouard  6155:          Tvar[k]=atoi(strd);
                   6156:        }
                   6157:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6158:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6159:          scanf("%d",i);*/
                   6160:       } /* end of loop + on total covariates */
                   6161:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6162:   } /* end if strlen(model == 0) */
1.136     brouard  6163:   
                   6164:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6165:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6166: 
                   6167:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6168:   printf("cptcovprod=%d ", cptcovprod);
                   6169:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6170: 
                   6171:   scanf("%d ",i);*/
                   6172: 
                   6173: 
1.137     brouard  6174:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6175:   /*endread:*/
1.136     brouard  6176:     printf("Exiting decodemodel: ");
                   6177:     return (1);
                   6178: }
                   6179: 
1.169     brouard  6180: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6181: {
                   6182:   int i, m;
                   6183: 
                   6184:   for (i=1; i<=imx; i++) {
                   6185:     for(m=2; (m<= maxwav); m++) {
                   6186:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6187:        anint[m][i]=9999;
                   6188:        s[m][i]=-1;
                   6189:       }
                   6190:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6191:        *nberr = *nberr + 1;
                   6192:        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);
                   6193:        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  6194:        s[m][i]=-1;
                   6195:       }
                   6196:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6197:        (*nberr)++;
1.136     brouard  6198:        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]); 
                   6199:        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]); 
                   6200:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6201:       }
                   6202:     }
                   6203:   }
                   6204: 
                   6205:   for (i=1; i<=imx; i++)  {
                   6206:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6207:     for(m=firstpass; (m<= lastpass); m++){
                   6208:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6209:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6210:          if(agedc[i]>0){
                   6211:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6212:              agev[m][i]=agedc[i];
                   6213:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6214:            }else {
1.136     brouard  6215:              if ((int)andc[i]!=9999){
                   6216:                nbwarn++;
                   6217:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6218:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6219:                agev[m][i]=-1;
                   6220:              }
                   6221:            }
1.169     brouard  6222:          } /* agedc > 0 */
1.136     brouard  6223:        }
                   6224:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6225:                                 years but with the precision of a month */
                   6226:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6227:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6228:            agev[m][i]=1;
                   6229:          else if(agev[m][i] < *agemin){ 
                   6230:            *agemin=agev[m][i];
                   6231:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6232:          }
                   6233:          else if(agev[m][i] >*agemax){
                   6234:            *agemax=agev[m][i];
1.156     brouard  6235:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6236:          }
                   6237:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6238:          /*     agev[m][i] = age[i]+2*m;*/
                   6239:        }
                   6240:        else { /* =9 */
                   6241:          agev[m][i]=1;
                   6242:          s[m][i]=-1;
                   6243:        }
                   6244:       }
                   6245:       else /*= 0 Unknown */
                   6246:        agev[m][i]=1;
                   6247:     }
                   6248:     
                   6249:   }
                   6250:   for (i=1; i<=imx; i++)  {
                   6251:     for(m=firstpass; (m<=lastpass); m++){
                   6252:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6253:        (*nberr)++;
1.136     brouard  6254:        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);     
                   6255:        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);     
                   6256:        return 1;
                   6257:       }
                   6258:     }
                   6259:   }
                   6260: 
                   6261:   /*for (i=1; i<=imx; i++){
                   6262:   for (m=firstpass; (m<lastpass); m++){
                   6263:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6264: }
                   6265: 
                   6266: }*/
                   6267: 
                   6268: 
1.139     brouard  6269:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6270:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6271: 
                   6272:   return (0);
1.164     brouard  6273:  /* endread:*/
1.136     brouard  6274:     printf("Exiting calandcheckages: ");
                   6275:     return (1);
                   6276: }
                   6277: 
1.172     brouard  6278: #if defined(_MSC_VER)
                   6279: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6280: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6281: //#include "stdafx.h"
                   6282: //#include <stdio.h>
                   6283: //#include <tchar.h>
                   6284: //#include <windows.h>
                   6285: //#include <iostream>
                   6286: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6287: 
                   6288: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6289: 
                   6290: BOOL IsWow64()
                   6291: {
                   6292:        BOOL bIsWow64 = FALSE;
                   6293: 
                   6294:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6295:        //  (HANDLE, PBOOL);
                   6296: 
                   6297:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6298: 
                   6299:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6300:        const char funcName[] = "IsWow64Process";
                   6301:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6302:                GetProcAddress(module, funcName);
                   6303: 
                   6304:        if (NULL != fnIsWow64Process)
                   6305:        {
                   6306:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6307:                        &bIsWow64))
                   6308:                        //throw std::exception("Unknown error");
                   6309:                        printf("Unknown error\n");
                   6310:        }
                   6311:        return bIsWow64 != FALSE;
                   6312: }
                   6313: #endif
1.177     brouard  6314: 
1.191     brouard  6315: void syscompilerinfo(int logged)
1.167     brouard  6316:  {
                   6317:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6318:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6319:    /* /GS /W3 /Gy
                   6320:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6321:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6322:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6323:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6324:    */ 
                   6325:    /* 64 bits */
1.185     brouard  6326:    /*
                   6327:      /GS /W3 /Gy
                   6328:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6329:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6330:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6331:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6332:    /* Optimization are useless and O3 is slower than O2 */
                   6333:    /*
                   6334:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6335:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6336:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6337:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6338:    */
1.186     brouard  6339:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6340:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6341:       /PDB:"visual studio
                   6342:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6343:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6344:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6345:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6346:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6347:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6348:       uiAccess='false'"
                   6349:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6350:       /NOLOGO /TLBID:1
                   6351:    */
1.177     brouard  6352: #if defined __INTEL_COMPILER
1.178     brouard  6353: #if defined(__GNUC__)
                   6354:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6355: #endif
1.177     brouard  6356: #elif defined(__GNUC__) 
1.179     brouard  6357: #ifndef  __APPLE__
1.174     brouard  6358: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6359: #endif
1.177     brouard  6360:    struct utsname sysInfo;
1.178     brouard  6361:    int cross = CROSS;
                   6362:    if (cross){
                   6363:           printf("Cross-");
1.191     brouard  6364:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6365:    }
1.174     brouard  6366: #endif
                   6367: 
1.171     brouard  6368: #include <stdint.h>
1.178     brouard  6369: 
1.191     brouard  6370:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6371: #if defined(__clang__)
1.191     brouard  6372:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6373: #endif
                   6374: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6375:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6376: #endif
                   6377: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6378:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6379: #endif
                   6380: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6381:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6382: #endif
                   6383: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6384:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6385: #endif
                   6386: #if defined(_MSC_VER)
1.191     brouard  6387:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6388: #endif
                   6389: #if defined(__PGI)
1.191     brouard  6390:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6391: #endif
                   6392: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6393:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6394: #endif
1.191     brouard  6395:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6396:    
1.167     brouard  6397: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6398: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6399:     // Windows (x64 and x86)
1.191     brouard  6400:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6401: #elif __unix__ // all unices, not all compilers
                   6402:     // Unix
1.191     brouard  6403:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6404: #elif __linux__
                   6405:     // linux
1.191     brouard  6406:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6407: #elif __APPLE__
1.174     brouard  6408:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6409:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6410: #endif
                   6411: 
                   6412: /*  __MINGW32__          */
                   6413: /*  __CYGWIN__  */
                   6414: /* __MINGW64__  */
                   6415: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6416: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6417: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6418: /* _WIN64  // Defined for applications for Win64. */
                   6419: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6420: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6421: 
1.167     brouard  6422: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6423:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6424: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6425:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6426: #else
1.191     brouard  6427:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6428: #endif
                   6429: 
1.169     brouard  6430: #if defined(__GNUC__)
                   6431: # if defined(__GNUC_PATCHLEVEL__)
                   6432: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6433:                             + __GNUC_MINOR__ * 100 \
                   6434:                             + __GNUC_PATCHLEVEL__)
                   6435: # else
                   6436: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6437:                             + __GNUC_MINOR__ * 100)
                   6438: # endif
1.174     brouard  6439:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6440:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6441: 
                   6442:    if (uname(&sysInfo) != -1) {
                   6443:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6444:         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  6445:    }
                   6446:    else
                   6447:       perror("uname() error");
1.179     brouard  6448:    //#ifndef __INTEL_COMPILER 
                   6449: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6450:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6451:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6452: #endif
1.169     brouard  6453: #endif
1.172     brouard  6454: 
                   6455:    //   void main()
                   6456:    //   {
1.169     brouard  6457: #if defined(_MSC_VER)
1.174     brouard  6458:    if (IsWow64()){
1.191     brouard  6459:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6460:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6461:    }
                   6462:    else{
1.191     brouard  6463:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6464:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6465:    }
1.172     brouard  6466:    //     printf("\nPress Enter to continue...");
                   6467:    //     getchar();
                   6468:    //   }
                   6469: 
1.169     brouard  6470: #endif
                   6471:    
1.167     brouard  6472: 
                   6473:  }
1.136     brouard  6474: 
1.203     brouard  6475:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
1.180     brouard  6476:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6477:   int i, j, k, i1 ;
1.202     brouard  6478:   /* double ftolpl = 1.e-10; */
1.180     brouard  6479:   double age, agebase, agelim;
1.203     brouard  6480:   double tot;
1.180     brouard  6481: 
1.202     brouard  6482:   strcpy(filerespl,"PL_");
                   6483:   strcat(filerespl,fileresu);
                   6484:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6485:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6486:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6487:   }
                   6488:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6489:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6490:   pstamp(ficrespl);
1.203     brouard  6491:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6492:   fprintf(ficrespl,"#Age ");
                   6493:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6494:   fprintf(ficrespl,"\n");
1.180     brouard  6495:   
                   6496:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6497: 
                   6498:     agebase=ageminpar;
                   6499:     agelim=agemaxpar;
                   6500: 
                   6501:     i1=pow(2,cptcoveff);
                   6502:     if (cptcovn < 1){i1=1;}
                   6503: 
                   6504:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6505:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6506:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6507:        k=k+1;
                   6508:        /* to clean */
1.198     brouard  6509:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6510:        fprintf(ficrespl,"#******");
                   6511:        printf("#******");
                   6512:        fprintf(ficlog,"#******");
1.180     brouard  6513:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6514:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6515:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6516:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6517:        }
                   6518:        fprintf(ficrespl,"******\n");
                   6519:        printf("******\n");
                   6520:        fprintf(ficlog,"******\n");
                   6521: 
                   6522:        fprintf(ficrespl,"#Age ");
                   6523:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6524:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6525:        }
1.203     brouard  6526:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6527:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6528:        
                   6529:        for (age=agebase; age<=agelim; age++){
                   6530:        /* for (age=agebase; age<=agebase; age++){ */
1.203     brouard  6531:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
1.180     brouard  6532:          fprintf(ficrespl,"%.0f ",age );
                   6533:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6534:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6535:          tot=0.;
                   6536:          for(i=1; i<=nlstate;i++){
                   6537:            tot +=  prlim[i][i];
1.180     brouard  6538:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6539:          }
                   6540:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
1.180     brouard  6541:        } /* Age */
                   6542:        /* was end of cptcod */
                   6543:     } /* cptcov */
1.184     brouard  6544:        return 0;
1.180     brouard  6545: }
                   6546: 
                   6547: int hPijx(double *p, int bage, int fage){
                   6548:     /*------------- h Pij x at various ages ------------*/
                   6549: 
                   6550:   int stepsize;
                   6551:   int agelim;
                   6552:   int hstepm;
                   6553:   int nhstepm;
                   6554:   int h, i, i1, j, k;
                   6555: 
                   6556:   double agedeb;
                   6557:   double ***p3mat;
                   6558: 
1.201     brouard  6559:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6560:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6561:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6562:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6563:     }
                   6564:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6565:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6566:   
                   6567:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6568:     /*if (stepm<=24) stepsize=2;*/
                   6569: 
                   6570:     agelim=AGESUP;
                   6571:     hstepm=stepsize*YEARM; /* Every year of age */
                   6572:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6573: 
                   6574:     /* hstepm=1;   aff par mois*/
                   6575:     pstamp(ficrespij);
                   6576:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6577:     i1= pow(2,cptcoveff);
1.183     brouard  6578:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6579:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6580:    /*          k=k+1;  */
                   6581:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6582:       fprintf(ficrespij,"\n#****** ");
                   6583:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6584:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6585:       fprintf(ficrespij,"******\n");
                   6586:       
                   6587:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6588:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6589:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6590:        
                   6591:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6592:        
1.183     brouard  6593:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6594:        oldm=oldms;savm=savms;
                   6595:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6596:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6597:        for(i=1; i<=nlstate;i++)
                   6598:          for(j=1; j<=nlstate+ndeath;j++)
                   6599:            fprintf(ficrespij," %1d-%1d",i,j);
                   6600:        fprintf(ficrespij,"\n");
                   6601:        for (h=0; h<=nhstepm; h++){
                   6602:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6603:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6604:          for(i=1; i<=nlstate;i++)
                   6605:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6606:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6607:          fprintf(ficrespij,"\n");
                   6608:        }
1.183     brouard  6609:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6610:        fprintf(ficrespij,"\n");
                   6611:       }
1.180     brouard  6612:       /*}*/
                   6613:     }
1.184     brouard  6614:        return 0;
1.180     brouard  6615: }
                   6616: 
                   6617: 
1.136     brouard  6618: /***********************************************/
                   6619: /**************** Main Program *****************/
                   6620: /***********************************************/
                   6621: 
                   6622: int main(int argc, char *argv[])
                   6623: {
                   6624: #ifdef GSL
                   6625:   const gsl_multimin_fminimizer_type *T;
                   6626:   size_t iteri = 0, it;
                   6627:   int rval = GSL_CONTINUE;
                   6628:   int status = GSL_SUCCESS;
                   6629:   double ssval;
                   6630: #endif
                   6631:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6632:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.203     brouard  6633:   int ncvyearnp=0;
                   6634:   int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6635:   int jj, ll, li, lj, lk;
1.136     brouard  6636:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6637:   int num_filled;
1.136     brouard  6638:   int itimes;
                   6639:   int NDIM=2;
                   6640:   int vpopbased=0;
                   6641: 
1.164     brouard  6642:   char ca[32], cb[32];
1.136     brouard  6643:   /*  FILE *fichtm; *//* Html File */
                   6644:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6645:   struct stat info;
1.191     brouard  6646:   double agedeb=0.;
1.194     brouard  6647: 
                   6648:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6649: 
1.165     brouard  6650:   double fret;
1.191     brouard  6651:   double dum=0.; /* Dummy variable */
1.136     brouard  6652:   double ***p3mat;
                   6653:   double ***mobaverage;
1.164     brouard  6654: 
                   6655:   char line[MAXLINE];
1.197     brouard  6656:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6657: 
                   6658:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6659:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6660:   char *tok, *val; /* pathtot */
1.136     brouard  6661:   int firstobs=1, lastobs=10;
1.195     brouard  6662:   int c,  h , cpt, c2;
1.191     brouard  6663:   int jl=0;
                   6664:   int i1, j1, jk, stepsize=0;
1.194     brouard  6665:   int count=0;
                   6666: 
1.164     brouard  6667:   int *tab; 
1.136     brouard  6668:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6669:   int mobilav=0,popforecast=0;
1.191     brouard  6670:   int hstepm=0, nhstepm=0;
1.136     brouard  6671:   int agemortsup;
                   6672:   float  sumlpop=0.;
                   6673:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6674:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6675: 
1.191     brouard  6676:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6677:   double ftolpl=FTOL;
                   6678:   double **prlim;
                   6679:   double ***param; /* Matrix of parameters */
                   6680:   double  *p;
                   6681:   double **matcov; /* Matrix of covariance */
1.203     brouard  6682:   double **hess; /* Hessian matrix */
1.136     brouard  6683:   double ***delti3; /* Scale */
                   6684:   double *delti; /* Scale */
                   6685:   double ***eij, ***vareij;
                   6686:   double **varpl; /* Variances of prevalence limits by age */
                   6687:   double *epj, vepp;
1.164     brouard  6688: 
1.136     brouard  6689:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6690:   double **ximort;
1.145     brouard  6691:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6692:   int *dcwave;
                   6693: 
1.164     brouard  6694:   char z[1]="c";
1.136     brouard  6695: 
                   6696:   /*char  *strt;*/
                   6697:   char strtend[80];
1.126     brouard  6698: 
1.164     brouard  6699: 
1.126     brouard  6700: /*   setlocale (LC_ALL, ""); */
                   6701: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6702: /*   textdomain (PACKAGE); */
                   6703: /*   setlocale (LC_CTYPE, ""); */
                   6704: /*   setlocale (LC_MESSAGES, ""); */
                   6705: 
                   6706:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6707:   rstart_time = time(NULL);  
                   6708:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6709:   start_time = *localtime(&rstart_time);
1.126     brouard  6710:   curr_time=start_time;
1.157     brouard  6711:   /*tml = *localtime(&start_time.tm_sec);*/
                   6712:   /* strcpy(strstart,asctime(&tml)); */
                   6713:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6714: 
                   6715: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6716: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6717: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6718: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6719: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6720: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6721: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6722: /*   strt=asctime(&tmg); */
                   6723: /*   printf("Time(after) =%s",strstart);  */
                   6724: /*  (void) time (&time_value);
                   6725: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6726: *  tm = *localtime(&time_value);
                   6727: *  strstart=asctime(&tm);
                   6728: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6729: */
                   6730: 
                   6731:   nberr=0; /* Number of errors and warnings */
                   6732:   nbwarn=0;
1.184     brouard  6733: #ifdef WIN32
                   6734:   _getcwd(pathcd, size);
                   6735: #else
1.126     brouard  6736:   getcwd(pathcd, size);
1.184     brouard  6737: #endif
1.191     brouard  6738:   syscompilerinfo(0);
1.196     brouard  6739:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6740:   if(argc <=1){
                   6741:     printf("\nEnter the parameter file name: ");
                   6742:     fgets(pathr,FILENAMELENGTH,stdin);
                   6743:     i=strlen(pathr);
                   6744:     if(pathr[i-1]=='\n')
                   6745:       pathr[i-1]='\0';
1.156     brouard  6746:     i=strlen(pathr);
                   6747:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6748:       pathr[i-1]='\0';
1.126     brouard  6749:    for (tok = pathr; tok != NULL; ){
                   6750:       printf("Pathr |%s|\n",pathr);
                   6751:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6752:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6753:       strcpy (pathtot, val);
                   6754:       if(pathr[0] == '\0') break; /* Dirty */
                   6755:     }
                   6756:   }
                   6757:   else{
                   6758:     strcpy(pathtot,argv[1]);
                   6759:   }
                   6760:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6761:   /*cygwin_split_path(pathtot,path,optionfile);
                   6762:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6763:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6764: 
                   6765:   /* Split argv[0], imach program to get pathimach */
                   6766:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6767:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6768:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6769:  /*   strcpy(pathimach,argv[0]); */
                   6770:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6771:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6772:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6773: #ifdef WIN32
                   6774:   _chdir(path); /* Can be a relative path */
                   6775:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6776: #else
1.126     brouard  6777:   chdir(path); /* Can be a relative path */
1.184     brouard  6778:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6779: #endif
                   6780:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6781:   strcpy(command,"mkdir ");
                   6782:   strcat(command,optionfilefiname);
                   6783:   if((outcmd=system(command)) != 0){
1.169     brouard  6784:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6785:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6786:     /* fclose(ficlog); */
                   6787: /*     exit(1); */
                   6788:   }
                   6789: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6790: /*     perror("mkdir"); */
                   6791: /*   } */
                   6792: 
                   6793:   /*-------- arguments in the command line --------*/
                   6794: 
1.186     brouard  6795:   /* Main Log file */
1.126     brouard  6796:   strcat(filelog, optionfilefiname);
                   6797:   strcat(filelog,".log");    /* */
                   6798:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6799:     printf("Problem with logfile %s\n",filelog);
                   6800:     goto end;
                   6801:   }
                   6802:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6803:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6804:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6805:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6806:  path=%s \n\
                   6807:  optionfile=%s\n\
                   6808:  optionfilext=%s\n\
1.156     brouard  6809:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6810: 
1.197     brouard  6811:   syscompilerinfo(1);
1.167     brouard  6812: 
1.126     brouard  6813:   printf("Local time (at start):%s",strstart);
                   6814:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6815:   fflush(ficlog);
                   6816: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6817: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6818: 
                   6819:   /* */
                   6820:   strcpy(fileres,"r");
                   6821:   strcat(fileres, optionfilefiname);
1.201     brouard  6822:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6823:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6824:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6825: 
1.186     brouard  6826:   /* Main ---------arguments file --------*/
1.126     brouard  6827: 
                   6828:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6829:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6830:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6831:     fflush(ficlog);
1.149     brouard  6832:     /* goto end; */
                   6833:     exit(70); 
1.126     brouard  6834:   }
                   6835: 
                   6836: 
                   6837: 
                   6838:   strcpy(filereso,"o");
1.201     brouard  6839:   strcat(filereso,fileresu);
1.126     brouard  6840:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6841:     printf("Problem with Output resultfile: %s\n", filereso);
                   6842:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6843:     fflush(ficlog);
                   6844:     goto end;
                   6845:   }
                   6846: 
                   6847:   /* Reads comments: lines beginning with '#' */
                   6848:   numlinepar=0;
1.197     brouard  6849: 
                   6850:     /* First parameter line */
                   6851:   while(fgets(line, MAXLINE, ficpar)) {
                   6852:     /* If line starts with a # it is a comment */
                   6853:     if (line[0] == '#') {
                   6854:       numlinepar++;
                   6855:       fputs(line,stdout);
                   6856:       fputs(line,ficparo);
                   6857:       fputs(line,ficlog);
                   6858:       continue;
                   6859:     }else
                   6860:       break;
                   6861:   }
                   6862:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6863:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6864:     if (num_filled != 5) {
                   6865:       printf("Should be 5 parameters\n");
                   6866:     }
1.126     brouard  6867:     numlinepar++;
1.197     brouard  6868:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6869:   }
                   6870:   /* Second parameter line */
                   6871:   while(fgets(line, MAXLINE, ficpar)) {
                   6872:     /* If line starts with a # it is a comment */
                   6873:     if (line[0] == '#') {
                   6874:       numlinepar++;
                   6875:       fputs(line,stdout);
                   6876:       fputs(line,ficparo);
                   6877:       fputs(line,ficlog);
                   6878:       continue;
                   6879:     }else
                   6880:       break;
                   6881:   }
                   6882:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6883:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6884:     if (num_filled != 8) {
                   6885:       printf("Not 8\n");
                   6886:     }
                   6887:     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  6888:   }
1.203     brouard  6889:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   6890:   ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  6891:   /* Third parameter line */
                   6892:   while(fgets(line, MAXLINE, ficpar)) {
                   6893:     /* If line starts with a # it is a comment */
                   6894:     if (line[0] == '#') {
                   6895:       numlinepar++;
                   6896:       fputs(line,stdout);
                   6897:       fputs(line,ficparo);
                   6898:       fputs(line,ficlog);
                   6899:       continue;
                   6900:     }else
                   6901:       break;
                   6902:   }
1.201     brouard  6903:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   6904:     if (num_filled == 0)
                   6905:             model[0]='\0';
                   6906:     else if (num_filled != 1){
1.197     brouard  6907:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6908:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6909:       model[0]='\0';
                   6910:       goto end;
                   6911:     }
                   6912:     else{
                   6913:       if (model[0]=='+'){
                   6914:        for(i=1; i<=strlen(model);i++)
                   6915:          modeltemp[i-1]=model[i];
1.201     brouard  6916:        strcpy(model,modeltemp); 
1.197     brouard  6917:       }
                   6918:     }
1.199     brouard  6919:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  6920:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  6921:   }
                   6922:   /* 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); */
                   6923:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   6924:   /* 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  6925:   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);
                   6926:   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  6927:   fflush(ficlog);
1.190     brouard  6928:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6929:   if(model[0]=='#'){
1.187     brouard  6930:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6931:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6932:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6933:     if(mle != -1){
                   6934:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6935:       exit(1);
                   6936:     }
                   6937:   }
1.126     brouard  6938:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6939:     ungetc(c,ficpar);
                   6940:     fgets(line, MAXLINE, ficpar);
                   6941:     numlinepar++;
1.195     brouard  6942:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6943:       z[0]=line[1];
                   6944:     }
                   6945:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6946:     fputs(line, stdout);
                   6947:     //puts(line);
1.126     brouard  6948:     fputs(line,ficparo);
                   6949:     fputs(line,ficlog);
                   6950:   }
                   6951:   ungetc(c,ficpar);
                   6952: 
                   6953:    
1.145     brouard  6954:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6955:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6956:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6957:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6958:   */
                   6959:   if (strlen(model)>1) 
1.187     brouard  6960:     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  6961:   else
1.187     brouard  6962:     ncovmodel=2; /* Constant and age */
1.133     brouard  6963:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6964:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6965:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6966:     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);
                   6967:     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);
                   6968:     fflush(stdout);
                   6969:     fclose (ficlog);
                   6970:     goto end;
                   6971:   }
1.126     brouard  6972:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6973:   delti=delti3[1][1];
                   6974:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6975:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6976:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6977:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6978:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6979:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6980:     fclose (ficparo);
                   6981:     fclose (ficlog);
                   6982:     goto end;
                   6983:     exit(0);
                   6984:   }
1.186     brouard  6985:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6986:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6987:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6988:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6989:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6990:     matcov=matrix(1,npar,1,npar);
1.203     brouard  6991:     hess=matrix(1,npar,1,npar);
1.126     brouard  6992:   }
                   6993:   else{
1.145     brouard  6994:     /* Read guessed parameters */
1.126     brouard  6995:     /* Reads comments: lines beginning with '#' */
                   6996:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6997:       ungetc(c,ficpar);
                   6998:       fgets(line, MAXLINE, ficpar);
                   6999:       numlinepar++;
1.141     brouard  7000:       fputs(line,stdout);
1.126     brouard  7001:       fputs(line,ficparo);
                   7002:       fputs(line,ficlog);
                   7003:     }
                   7004:     ungetc(c,ficpar);
                   7005:     
                   7006:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7007:     for(i=1; i <=nlstate; i++){
                   7008:       j=0;
                   7009:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7010:        if(jj==i) continue;
                   7011:        j++;
                   7012:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7013:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7014:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7015: It might be a problem of design; if ncovcol and the model are correct\n \
                   7016: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7017:          exit(1);
                   7018:        }
                   7019:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7020:        if(mle==1)
1.193     brouard  7021:          printf("%1d%1d",i,jj);
                   7022:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7023:        for(k=1; k<=ncovmodel;k++){
                   7024:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7025:          if(mle==1){
                   7026:            printf(" %lf",param[i][j][k]);
                   7027:            fprintf(ficlog," %lf",param[i][j][k]);
                   7028:          }
                   7029:          else
                   7030:            fprintf(ficlog," %lf",param[i][j][k]);
                   7031:          fprintf(ficparo," %lf",param[i][j][k]);
                   7032:        }
                   7033:        fscanf(ficpar,"\n");
                   7034:        numlinepar++;
                   7035:        if(mle==1)
                   7036:          printf("\n");
                   7037:        fprintf(ficlog,"\n");
                   7038:        fprintf(ficparo,"\n");
                   7039:       }
                   7040:     }  
                   7041:     fflush(ficlog);
                   7042: 
1.145     brouard  7043:     /* Reads scales values */
1.126     brouard  7044:     p=param[1][1];
                   7045:     
                   7046:     /* Reads comments: lines beginning with '#' */
                   7047:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7048:       ungetc(c,ficpar);
                   7049:       fgets(line, MAXLINE, ficpar);
                   7050:       numlinepar++;
1.141     brouard  7051:       fputs(line,stdout);
1.126     brouard  7052:       fputs(line,ficparo);
                   7053:       fputs(line,ficlog);
                   7054:     }
                   7055:     ungetc(c,ficpar);
                   7056: 
                   7057:     for(i=1; i <=nlstate; i++){
                   7058:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7059:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7060:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7061:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7062:          exit(1);
                   7063:        }
                   7064:        printf("%1d%1d",i,j);
                   7065:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7066:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7067:        for(k=1; k<=ncovmodel;k++){
                   7068:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7069:          printf(" %le",delti3[i][j][k]);
                   7070:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7071:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7072:        }
                   7073:        fscanf(ficpar,"\n");
                   7074:        numlinepar++;
                   7075:        printf("\n");
                   7076:        fprintf(ficparo,"\n");
                   7077:        fprintf(ficlog,"\n");
                   7078:       }
                   7079:     }
                   7080:     fflush(ficlog);
                   7081: 
1.145     brouard  7082:     /* Reads covariance matrix */
1.126     brouard  7083:     delti=delti3[1][1];
                   7084: 
                   7085: 
                   7086:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7087:   
                   7088:     /* Reads comments: lines beginning with '#' */
                   7089:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7090:       ungetc(c,ficpar);
                   7091:       fgets(line, MAXLINE, ficpar);
                   7092:       numlinepar++;
1.141     brouard  7093:       fputs(line,stdout);
1.126     brouard  7094:       fputs(line,ficparo);
                   7095:       fputs(line,ficlog);
                   7096:     }
                   7097:     ungetc(c,ficpar);
                   7098:   
                   7099:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7100:     hess=matrix(1,npar,1,npar);
1.131     brouard  7101:     for(i=1; i <=npar; i++)
                   7102:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7103:       
1.194     brouard  7104:     /* Scans npar lines */
1.126     brouard  7105:     for(i=1; i <=npar; i++){
1.194     brouard  7106:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7107:       if(count != 3){
                   7108:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7109: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7110: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7111:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7112: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7113: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7114:        exit(1);
                   7115:       }else
1.126     brouard  7116:       if(mle==1)
1.194     brouard  7117:        printf("%1d%1d%1d",i1,j1,jk);
                   7118:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7119:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7120:       for(j=1; j <=i; j++){
                   7121:        fscanf(ficpar," %le",&matcov[i][j]);
                   7122:        if(mle==1){
                   7123:          printf(" %.5le",matcov[i][j]);
                   7124:        }
                   7125:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7126:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7127:       }
                   7128:       fscanf(ficpar,"\n");
                   7129:       numlinepar++;
                   7130:       if(mle==1)
                   7131:        printf("\n");
                   7132:       fprintf(ficlog,"\n");
                   7133:       fprintf(ficparo,"\n");
                   7134:     }
1.194     brouard  7135:     /* End of read covariance matrix npar lines */
1.126     brouard  7136:     for(i=1; i <=npar; i++)
                   7137:       for(j=i+1;j<=npar;j++)
                   7138:        matcov[i][j]=matcov[j][i];
                   7139:     
                   7140:     if(mle==1)
                   7141:       printf("\n");
                   7142:     fprintf(ficlog,"\n");
                   7143:     
                   7144:     fflush(ficlog);
                   7145:     
                   7146:     /*-------- Rewriting parameter file ----------*/
                   7147:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7148:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7149:     strcat(rfileres,".");    /* */
                   7150:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7151:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7152:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7153:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7154:     }
                   7155:     fprintf(ficres,"#%s\n",version);
                   7156:   }    /* End of mle != -3 */
                   7157: 
1.186     brouard  7158:   /*  Main data
                   7159:    */
1.126     brouard  7160:   n= lastobs;
                   7161:   num=lvector(1,n);
                   7162:   moisnais=vector(1,n);
                   7163:   annais=vector(1,n);
                   7164:   moisdc=vector(1,n);
                   7165:   andc=vector(1,n);
                   7166:   agedc=vector(1,n);
                   7167:   cod=ivector(1,n);
                   7168:   weight=vector(1,n);
                   7169:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7170:   mint=matrix(1,maxwav,1,n);
                   7171:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7172:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7173:   tab=ivector(1,NCOVMAX);
1.144     brouard  7174:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7175:   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  7176: 
1.136     brouard  7177:   /* Reads data from file datafile */
                   7178:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7179:     goto end;
                   7180: 
                   7181:   /* Calculation of the number of parameters from char model */
1.137     brouard  7182:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7183:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7184:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7185:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7186:        k=1 Tvar[1]=2 (from V2)
                   7187:     */
                   7188:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7189:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7190:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7191:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7192:   */
                   7193:   /* For model-covariate k tells which data-covariate to use but
                   7194:     because this model-covariate is a construction we invent a new column
                   7195:     ncovcol + k1
                   7196:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7197:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7198:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7199:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7200:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7201:   */
1.145     brouard  7202:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7203:   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  7204:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7205:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7206:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7207:                         4 covariates (3 plus signs)
                   7208:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7209:                      */  
1.136     brouard  7210: 
1.186     brouard  7211: /* Main decodemodel */
                   7212: 
1.187     brouard  7213: 
1.136     brouard  7214:   if(decodemodel(model, lastobs) == 1)
                   7215:     goto end;
                   7216: 
1.137     brouard  7217:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7218:     nbwarn++;
                   7219:     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); 
                   7220:     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); 
                   7221:   }
1.136     brouard  7222:     /*  if(mle==1){*/
1.137     brouard  7223:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7224:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7225:   }
                   7226: 
                   7227:     /*-calculation of age at interview from date of interview and age at death -*/
                   7228:   agev=matrix(1,maxwav,1,imx);
                   7229: 
                   7230:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7231:     goto end;
                   7232: 
1.126     brouard  7233: 
1.136     brouard  7234:   agegomp=(int)agemin;
                   7235:   free_vector(moisnais,1,n);
                   7236:   free_vector(annais,1,n);
1.126     brouard  7237:   /* free_matrix(mint,1,maxwav,1,n);
                   7238:      free_matrix(anint,1,maxwav,1,n);*/
                   7239:   free_vector(moisdc,1,n);
                   7240:   free_vector(andc,1,n);
1.145     brouard  7241:   /* */
                   7242:   
1.126     brouard  7243:   wav=ivector(1,imx);
                   7244:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7245:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7246:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7247:    
                   7248:   /* Concatenates waves */
                   7249:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7250:   /* */
                   7251:  
1.126     brouard  7252:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7253: 
                   7254:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7255:   ncodemax[1]=1;
1.145     brouard  7256:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7257:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7258:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7259:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7260:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7261:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7262: 
1.200     brouard  7263:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7264:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7265:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7266:   h=0;
                   7267: 
                   7268: 
                   7269:   /*if (cptcovn > 0) */
1.126     brouard  7270:       
1.145     brouard  7271:  
1.126     brouard  7272:   m=pow(2,cptcoveff);
                   7273:  
1.144     brouard  7274:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7275:           * For k=4 covariates, h goes from 1 to 2**k
                   7276:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7277:           *     h\k   1     2     3     4
1.143     brouard  7278:           *______________________________  
                   7279:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7280:           *     2     2     1     1     1
                   7281:           *     3 i=2 1     2     1     1
                   7282:           *     4     2     2     1     1
                   7283:           *     5 i=3 1 i=2 1     2     1
                   7284:           *     6     2     1     2     1
                   7285:           *     7 i=4 1     2     2     1
                   7286:           *     8     2     2     2     1
1.197     brouard  7287:           *     9 i=5 1 i=3 1 i=2 1     2
                   7288:           *    10     2     1     1     2
                   7289:           *    11 i=6 1     2     1     2
                   7290:           *    12     2     2     1     2
                   7291:           *    13 i=7 1 i=4 1     2     2    
                   7292:           *    14     2     1     2     2
                   7293:           *    15 i=8 1     2     2     2
                   7294:           *    16     2     2     2     2
1.143     brouard  7295:           */
1.202     brouard  7296:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7297:   /*   /\* printf("h=%2d ", h); *\/ */
                   7298:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7299:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7300:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7301:   /*    /\* } *\/ */
                   7302:   /*    /\* printf("\n"); *\/ */
                   7303:   /* } */
1.197     brouard  7304:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7305:   /*   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 *\/  */
                   7306:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7307:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7308:   /*     h++; */
                   7309:   /*     if (h>m)  */
                   7310:   /*       h=1; */
                   7311:   /*     codtab[h][k]=j; */
                   7312:   /*     /\* codtab[12][3]=1; *\/ */
                   7313:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7314:   /*     /\* 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]]); *\/ */
                   7315:   /*   }  */
                   7316:   /*     } */
                   7317:   /*   } */
                   7318:   /* }  */
1.126     brouard  7319:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7320:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7321:   /* for(i=1; i <=m ;i++){  */
                   7322:   /*    for(k=1; k <=cptcovn; k++){ */
                   7323:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7324:   /*    } */
                   7325:   /*    printf("\n"); */
                   7326:   /* } */
                   7327:   /*   scanf("%d",i);*/
1.145     brouard  7328: 
                   7329:  free_ivector(Ndum,-1,NCOVMAX);
                   7330: 
                   7331: 
1.126     brouard  7332:     
1.186     brouard  7333:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7334:   strcpy(optionfilegnuplot,optionfilefiname);
                   7335:   if(mle==-3)
1.201     brouard  7336:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7337:   strcat(optionfilegnuplot,".gp");
                   7338: 
                   7339:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7340:     printf("Problem with file %s",optionfilegnuplot);
                   7341:   }
                   7342:   else{
1.204   ! brouard  7343:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7344:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7345:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7346:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7347:   }
                   7348:   /*  fclose(ficgp);*/
1.186     brouard  7349: 
                   7350: 
                   7351:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7352: 
                   7353:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7354:   if(mle==-3)
1.201     brouard  7355:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7356:   strcat(optionfilehtm,".htm");
                   7357:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7358:     printf("Problem with %s \n",optionfilehtm);
                   7359:     exit(0);
1.126     brouard  7360:   }
                   7361: 
                   7362:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7363:   strcat(optionfilehtmcov,"-cov.htm");
                   7364:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7365:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7366:   }
                   7367:   else{
                   7368:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7369: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204   ! brouard  7370: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7371:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7372:   }
                   7373: 
1.204   ! brouard  7374:   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>  \
        !          7375: <hr size=\"2\" color=\"#EC5E5E\"> \n\
        !          7376: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7377: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204   ! brouard  7378: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7379: \n\
                   7380: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7381:  <ul><li><h4>Parameter files</h4>\n\
                   7382:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7383:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7384:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7385:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7386:  - Date and time at start: %s</ul>\n",\
                   7387:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7388:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7389:          fileres,fileres,\
                   7390:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7391:   fflush(fichtm);
                   7392: 
                   7393:   strcpy(pathr,path);
                   7394:   strcat(pathr,optionfilefiname);
1.184     brouard  7395: #ifdef WIN32
                   7396:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7397: #else
1.126     brouard  7398:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7399: #endif
                   7400:          
1.126     brouard  7401:   
                   7402:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7403:      and prints on file fileres'p'. */
                   7404:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7405: 
                   7406:   fprintf(fichtm,"\n");
                   7407:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7408: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7409: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7410:          imx,agemin,agemax,jmin,jmax,jmean);
                   7411:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7412:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7413:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7414:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7415:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7416:     
                   7417:    
                   7418:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7419:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7420:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7421: 
                   7422:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7423:   /* For mortality only */
1.126     brouard  7424:   if (mle==-3){
1.136     brouard  7425:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7426:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7427:     cens=ivector(1,n);
                   7428:     ageexmed=vector(1,n);
                   7429:     agecens=vector(1,n);
                   7430:     dcwave=ivector(1,n);
                   7431:  
                   7432:     for (i=1; i<=imx; i++){
                   7433:       dcwave[i]=-1;
                   7434:       for (m=firstpass; m<=lastpass; m++)
                   7435:        if (s[m][i]>nlstate) {
                   7436:          dcwave[i]=m;
                   7437:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7438:          break;
                   7439:        }
                   7440:     }
                   7441: 
                   7442:     for (i=1; i<=imx; i++) {
                   7443:       if (wav[i]>0){
                   7444:        ageexmed[i]=agev[mw[1][i]][i];
                   7445:        j=wav[i];
                   7446:        agecens[i]=1.; 
                   7447: 
                   7448:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7449:          agecens[i]=agev[mw[j][i]][i];
                   7450:          cens[i]= 1;
                   7451:        }else if (ageexmed[i]< 1) 
                   7452:          cens[i]= -1;
                   7453:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7454:          cens[i]=0 ;
                   7455:       }
                   7456:       else cens[i]=-1;
                   7457:     }
                   7458:     
                   7459:     for (i=1;i<=NDIM;i++) {
                   7460:       for (j=1;j<=NDIM;j++)
                   7461:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7462:     }
                   7463:     
1.145     brouard  7464:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7465:     /*printf("%lf %lf", p[1], p[2]);*/
                   7466:     
                   7467:     
1.136     brouard  7468: #ifdef GSL
                   7469:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7470: #else
1.126     brouard  7471:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7472: #endif
1.201     brouard  7473:     strcpy(filerespow,"POW-MORT_"); 
                   7474:     strcat(filerespow,fileresu);
1.126     brouard  7475:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7476:       printf("Problem with resultfile: %s\n", filerespow);
                   7477:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7478:     }
1.136     brouard  7479: #ifdef GSL
                   7480:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7481: #else
1.126     brouard  7482:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7483: #endif
1.126     brouard  7484:     /*  for (i=1;i<=nlstate;i++)
                   7485:        for(j=1;j<=nlstate+ndeath;j++)
                   7486:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7487:     */
                   7488:     fprintf(ficrespow,"\n");
1.136     brouard  7489: #ifdef GSL
                   7490:     /* gsl starts here */ 
                   7491:     T = gsl_multimin_fminimizer_nmsimplex;
                   7492:     gsl_multimin_fminimizer *sfm = NULL;
                   7493:     gsl_vector *ss, *x;
                   7494:     gsl_multimin_function minex_func;
                   7495: 
                   7496:     /* Initial vertex size vector */
                   7497:     ss = gsl_vector_alloc (NDIM);
                   7498:     
                   7499:     if (ss == NULL){
                   7500:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7501:     }
                   7502:     /* Set all step sizes to 1 */
                   7503:     gsl_vector_set_all (ss, 0.001);
                   7504: 
                   7505:     /* Starting point */
1.126     brouard  7506:     
1.136     brouard  7507:     x = gsl_vector_alloc (NDIM);
                   7508:     
                   7509:     if (x == NULL){
                   7510:       gsl_vector_free(ss);
                   7511:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7512:     }
                   7513:   
                   7514:     /* Initialize method and iterate */
                   7515:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7516:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7517:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7518:     gsl_vector_set(x, 0, p[1]);
                   7519:     gsl_vector_set(x, 1, p[2]);
                   7520: 
                   7521:     minex_func.f = &gompertz_f;
                   7522:     minex_func.n = NDIM;
                   7523:     minex_func.params = (void *)&p; /* ??? */
                   7524:     
                   7525:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7526:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7527:     
                   7528:     printf("Iterations beginning .....\n\n");
                   7529:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7530: 
                   7531:     iteri=0;
                   7532:     while (rval == GSL_CONTINUE){
                   7533:       iteri++;
                   7534:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7535:       
                   7536:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7537:       fflush(0);
                   7538:       
                   7539:       if (status) 
                   7540:         break;
                   7541:       
                   7542:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7543:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7544:       
                   7545:       if (rval == GSL_SUCCESS)
                   7546:         printf ("converged to a local maximum at\n");
                   7547:       
                   7548:       printf("%5d ", iteri);
                   7549:       for (it = 0; it < NDIM; it++){
                   7550:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7551:       }
                   7552:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7553:     }
                   7554:     
                   7555:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7556:     
                   7557:     gsl_vector_free(x); /* initial values */
                   7558:     gsl_vector_free(ss); /* inital step size */
                   7559:     for (it=0; it<NDIM; it++){
                   7560:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7561:       fprintf(ficrespow," %.12lf", p[it]);
                   7562:     }
                   7563:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7564: #endif
                   7565: #ifdef POWELL
                   7566:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7567: #endif  
1.126     brouard  7568:     fclose(ficrespow);
                   7569:     
1.203     brouard  7570:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7571: 
                   7572:     for(i=1; i <=NDIM; i++)
                   7573:       for(j=i+1;j<=NDIM;j++)
                   7574:        matcov[i][j]=matcov[j][i];
                   7575:     
                   7576:     printf("\nCovariance matrix\n ");
1.203     brouard  7577:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7578:     for(i=1; i <=NDIM; i++) {
                   7579:       for(j=1;j<=NDIM;j++){ 
                   7580:        printf("%f ",matcov[i][j]);
1.203     brouard  7581:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7582:       }
1.203     brouard  7583:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7584:     }
                   7585:     
                   7586:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7587:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7588:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7589:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7590:     }
1.126     brouard  7591:     lsurv=vector(1,AGESUP);
                   7592:     lpop=vector(1,AGESUP);
                   7593:     tpop=vector(1,AGESUP);
                   7594:     lsurv[agegomp]=100000;
                   7595:     
                   7596:     for (k=agegomp;k<=AGESUP;k++) {
                   7597:       agemortsup=k;
                   7598:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7599:     }
                   7600:     
                   7601:     for (k=agegomp;k<agemortsup;k++)
                   7602:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7603:     
                   7604:     for (k=agegomp;k<agemortsup;k++){
                   7605:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7606:       sumlpop=sumlpop+lpop[k];
                   7607:     }
                   7608:     
                   7609:     tpop[agegomp]=sumlpop;
                   7610:     for (k=agegomp;k<(agemortsup-3);k++){
                   7611:       /*  tpop[k+1]=2;*/
                   7612:       tpop[k+1]=tpop[k]-lpop[k];
                   7613:     }
                   7614:     
                   7615:     
                   7616:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7617:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7618:       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]);
                   7619:     
                   7620:     
                   7621:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7622:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7623:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7624: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7625: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7626:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7627: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7628: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7629:     }else
1.201     brouard  7630:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7631:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7632:                     stepm, weightopt,\
                   7633:                     model,imx,p,matcov,agemortsup);
                   7634:     
                   7635:     free_vector(lsurv,1,AGESUP);
                   7636:     free_vector(lpop,1,AGESUP);
                   7637:     free_vector(tpop,1,AGESUP);
1.136     brouard  7638: #ifdef GSL
                   7639:     free_ivector(cens,1,n);
                   7640:     free_vector(agecens,1,n);
                   7641:     free_ivector(dcwave,1,n);
                   7642:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7643: #endif
1.186     brouard  7644:   } /* Endof if mle==-3 mortality only */
                   7645:   /* Standard maximisation */
1.203     brouard  7646:   else{ /* For mle !=- 3 */
1.132     brouard  7647:     globpr=0;/* debug */
1.186     brouard  7648:     /* Computes likelihood for initial parameters */
1.132     brouard  7649:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7650:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7651:     for (k=1; k<=npar;k++)
                   7652:       printf(" %d %8.5f",k,p[k]);
                   7653:     printf("\n");
1.186     brouard  7654:     globpr=1; /* again, to print the contributions */
1.126     brouard  7655:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7656:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7657:     for (k=1; k<=npar;k++)
                   7658:       printf(" %d %8.5f",k,p[k]);
                   7659:     printf("\n");
1.186     brouard  7660:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7661:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7662:     }
                   7663:     
                   7664:     /*--------- results files --------------*/
1.192     brouard  7665:     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  7666:     
                   7667:     
                   7668:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7669:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7670:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7671:     for(i=1,jk=1; i <=nlstate; i++){
                   7672:       for(k=1; k <=(nlstate+ndeath); k++){
                   7673:        if (k != i) {
                   7674:          printf("%d%d ",i,k);
                   7675:          fprintf(ficlog,"%d%d ",i,k);
                   7676:          fprintf(ficres,"%1d%1d ",i,k);
                   7677:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7678:            printf("%12.7f ",p[jk]);
                   7679:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7680:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7681:            jk++; 
                   7682:          }
                   7683:          printf("\n");
                   7684:          fprintf(ficlog,"\n");
                   7685:          fprintf(ficres,"\n");
                   7686:        }
                   7687:       }
                   7688:     }
1.203     brouard  7689:     if(mle != 0){
                   7690:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  7691:       ftolhess=ftol; /* Usually correct */
1.203     brouard  7692:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   7693:       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");
                   7694:       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");
                   7695:       for(i=1,jk=1; i <=nlstate; i++){
                   7696:        for(k=1; k <=(nlstate+ndeath); k++){
                   7697:          if (k != i) {
                   7698:            printf("%d%d ",i,k);
                   7699:            fprintf(ficlog,"%d%d ",i,k);
                   7700:            for(j=1; j <=ncovmodel; j++){
                   7701:              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]));
                   7702:              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]));
                   7703:              jk++; 
                   7704:            }
                   7705:            printf("\n");
                   7706:            fprintf(ficlog,"\n");
1.193     brouard  7707:          }
                   7708:        }
                   7709:       }
1.203     brouard  7710:     } /* end of hesscov and Wald tests */
1.193     brouard  7711: 
1.203     brouard  7712:     /*  */
1.126     brouard  7713:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7714:     printf("# Scales (for hessian or gradient estimation)\n");
                   7715:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7716:     for(i=1,jk=1; i <=nlstate; i++){
                   7717:       for(j=1; j <=nlstate+ndeath; j++){
                   7718:        if (j!=i) {
                   7719:          fprintf(ficres,"%1d%1d",i,j);
                   7720:          printf("%1d%1d",i,j);
                   7721:          fprintf(ficlog,"%1d%1d",i,j);
                   7722:          for(k=1; k<=ncovmodel;k++){
                   7723:            printf(" %.5e",delti[jk]);
                   7724:            fprintf(ficlog," %.5e",delti[jk]);
                   7725:            fprintf(ficres," %.5e",delti[jk]);
                   7726:            jk++;
                   7727:          }
                   7728:          printf("\n");
                   7729:          fprintf(ficlog,"\n");
                   7730:          fprintf(ficres,"\n");
                   7731:        }
                   7732:       }
                   7733:     }
                   7734:     
                   7735:     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  7736:     if(mle >= 1) /* To big for the screen */
1.126     brouard  7737:       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");
                   7738:     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");
                   7739:     /* # 121 Var(a12)\n\ */
                   7740:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7741:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7742:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7743:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7744:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7745:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7746:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7747:     
                   7748:     
                   7749:     /* Just to have a covariance matrix which will be more understandable
                   7750:        even is we still don't want to manage dictionary of variables
                   7751:     */
                   7752:     for(itimes=1;itimes<=2;itimes++){
                   7753:       jj=0;
                   7754:       for(i=1; i <=nlstate; i++){
                   7755:        for(j=1; j <=nlstate+ndeath; j++){
                   7756:          if(j==i) continue;
                   7757:          for(k=1; k<=ncovmodel;k++){
                   7758:            jj++;
                   7759:            ca[0]= k+'a'-1;ca[1]='\0';
                   7760:            if(itimes==1){
                   7761:              if(mle>=1)
                   7762:                printf("#%1d%1d%d",i,j,k);
                   7763:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7764:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7765:            }else{
                   7766:              if(mle>=1)
                   7767:                printf("%1d%1d%d",i,j,k);
                   7768:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7769:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7770:            }
                   7771:            ll=0;
                   7772:            for(li=1;li <=nlstate; li++){
                   7773:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7774:                if(lj==li) continue;
                   7775:                for(lk=1;lk<=ncovmodel;lk++){
                   7776:                  ll++;
                   7777:                  if(ll<=jj){
                   7778:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7779:                    if(ll<jj){
                   7780:                      if(itimes==1){
                   7781:                        if(mle>=1)
                   7782:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7783:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7784:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7785:                      }else{
                   7786:                        if(mle>=1)
                   7787:                          printf(" %.5e",matcov[jj][ll]); 
                   7788:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7789:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7790:                      }
                   7791:                    }else{
                   7792:                      if(itimes==1){
                   7793:                        if(mle>=1)
                   7794:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7795:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7796:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7797:                      }else{
                   7798:                        if(mle>=1)
1.203     brouard  7799:                          printf(" %.7e",matcov[jj][ll]); 
                   7800:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   7801:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  7802:                      }
                   7803:                    }
                   7804:                  }
                   7805:                } /* end lk */
                   7806:              } /* end lj */
                   7807:            } /* end li */
                   7808:            if(mle>=1)
                   7809:              printf("\n");
                   7810:            fprintf(ficlog,"\n");
                   7811:            fprintf(ficres,"\n");
                   7812:            numlinepar++;
                   7813:          } /* end k*/
                   7814:        } /*end j */
                   7815:       } /* end i */
                   7816:     } /* end itimes */
                   7817:     
                   7818:     fflush(ficlog);
                   7819:     fflush(ficres);
                   7820:     
                   7821:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7822:       ungetc(c,ficpar);
                   7823:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7824:       fputs(line,stdout);
1.126     brouard  7825:       fputs(line,ficparo);
                   7826:     }
                   7827:     ungetc(c,ficpar);
                   7828:     
                   7829:     estepm=0;
                   7830:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7831:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7832:     if (fage <= 2) {
                   7833:       bage = ageminpar;
                   7834:       fage = agemaxpar;
                   7835:     }
                   7836:     
                   7837:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7838:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7839:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7840: 
                   7841:     /* Other stuffs, more or less useful */    
1.126     brouard  7842:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7843:       ungetc(c,ficpar);
                   7844:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7845:       fputs(line,stdout);
1.126     brouard  7846:       fputs(line,ficparo);
                   7847:     }
                   7848:     ungetc(c,ficpar);
                   7849:     
                   7850:     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);
                   7851:     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);
                   7852:     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);
                   7853:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7854:     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);
                   7855:     
                   7856:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7857:       ungetc(c,ficpar);
                   7858:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7859:       fputs(line,stdout);
1.126     brouard  7860:       fputs(line,ficparo);
                   7861:     }
                   7862:     ungetc(c,ficpar);
                   7863:     
                   7864:     
                   7865:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7866:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7867:     
                   7868:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7869:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7870:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7871:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7872:     
                   7873:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7874:       ungetc(c,ficpar);
                   7875:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7876:       fputs(line,stdout);
1.126     brouard  7877:       fputs(line,ficparo);
                   7878:     }
                   7879:     ungetc(c,ficpar);
                   7880:     
                   7881:     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);
                   7882:     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);
                   7883:     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);
                   7884:     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);
                   7885:     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);
                   7886:     /* day and month of proj2 are not used but only year anproj2.*/
                   7887:     
                   7888:     
                   7889:     
1.145     brouard  7890:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7891:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7892:     
                   7893:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7894:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7895:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7896: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7897: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7898:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7899: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7900: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7901:     }else
1.201     brouard  7902:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7903:     
1.201     brouard  7904:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  7905:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7906:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7907:       
                   7908:    /*------------ free_vector  -------------*/
                   7909:    /*  chdir(path); */
                   7910:  
                   7911:     free_ivector(wav,1,imx);
                   7912:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7913:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7914:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7915:     free_lvector(num,1,n);
                   7916:     free_vector(agedc,1,n);
                   7917:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7918:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7919:     fclose(ficparo);
                   7920:     fclose(ficres);
                   7921: 
                   7922: 
1.186     brouard  7923:     /* Other results (useful)*/
                   7924: 
                   7925: 
1.126     brouard  7926:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7927:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7928:     prlim=matrix(1,nlstate,1,nlstate);
1.203     brouard  7929:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, ncvyear);
1.126     brouard  7930:     fclose(ficrespl);
                   7931: 
1.145     brouard  7932: #ifdef FREEEXIT2
                   7933: #include "freeexit2.h"
                   7934: #endif
                   7935: 
1.126     brouard  7936:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7937:     /*#include "hpijx.h"*/
                   7938:     hPijx(p, bage, fage);
1.145     brouard  7939:     fclose(ficrespij);
1.126     brouard  7940: 
1.145     brouard  7941:   /*-------------- Variance of one-step probabilities---*/
                   7942:     k=1;
1.126     brouard  7943:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7944: 
                   7945: 
                   7946:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7947:     for(i=1;i<=AGESUP;i++)
                   7948:       for(j=1;j<=NCOVMAX;j++)
                   7949:        for(k=1;k<=NCOVMAX;k++)
                   7950:          probs[i][j][k]=0.;
                   7951: 
                   7952:     /*---------- Forecasting ------------------*/
                   7953:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7954:     if(prevfcast==1){
                   7955:       /*    if(stepm ==1){*/
1.201     brouard  7956:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  7957:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7958:       /*      }  */
                   7959:       /*      else{ */
                   7960:       /*        erreur=108; */
                   7961:       /*        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); */
                   7962:       /*        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); */
                   7963:       /*      } */
                   7964:     }
1.186     brouard  7965:  
                   7966:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7967: 
1.127     brouard  7968:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7969: 
                   7970:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7971:     /*  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",\
                   7972:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7973:     */
1.126     brouard  7974: 
1.127     brouard  7975:     if (mobilav!=0) {
                   7976:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7977:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7978:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7979:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7980:       }
1.126     brouard  7981:     }
                   7982: 
                   7983: 
1.127     brouard  7984:     /*---------- Health expectancies, no variances ------------*/
                   7985: 
1.201     brouard  7986:     strcpy(filerese,"E_");
                   7987:     strcat(filerese,fileresu);
1.126     brouard  7988:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7989:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7990:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7991:     }
                   7992:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7993:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7994:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7995:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7996:           
                   7997:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7998:        fprintf(ficreseij,"\n#****** ");
                   7999:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8000:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8001:        }
                   8002:        fprintf(ficreseij,"******\n");
                   8003: 
                   8004:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8005:        oldm=oldms;savm=savms;
                   8006:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8007:       
                   8008:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8009:       /*}*/
1.127     brouard  8010:     }
                   8011:     fclose(ficreseij);
                   8012: 
                   8013: 
                   8014:     /*---------- Health expectancies and variances ------------*/
                   8015: 
                   8016: 
1.201     brouard  8017:     strcpy(filerest,"T_");
                   8018:     strcat(filerest,fileresu);
1.127     brouard  8019:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8020:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8021:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8022:     }
                   8023:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   8024:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   8025: 
1.126     brouard  8026: 
1.201     brouard  8027:     strcpy(fileresstde,"STDE_");
                   8028:     strcat(fileresstde,fileresu);
1.126     brouard  8029:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8030:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8031:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8032:     }
                   8033:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8034:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8035: 
1.201     brouard  8036:     strcpy(filerescve,"CVE_");
                   8037:     strcat(filerescve,fileresu);
1.126     brouard  8038:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8039:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8040:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8041:     }
                   8042:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8043:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8044: 
1.201     brouard  8045:     strcpy(fileresv,"V_");
                   8046:     strcat(fileresv,fileresu);
1.126     brouard  8047:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8048:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8049:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8050:     }
                   8051:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   8052:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   8053: 
1.145     brouard  8054:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8055:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8056:           
                   8057:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8058:        fprintf(ficrest,"\n#****** ");
1.126     brouard  8059:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8060:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8061:        fprintf(ficrest,"******\n");
                   8062: 
                   8063:        fprintf(ficresstdeij,"\n#****** ");
                   8064:        fprintf(ficrescveij,"\n#****** ");
                   8065:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8066:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8067:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8068:        }
                   8069:        fprintf(ficresstdeij,"******\n");
                   8070:        fprintf(ficrescveij,"******\n");
                   8071: 
                   8072:        fprintf(ficresvij,"\n#****** ");
                   8073:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8074:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8075:        fprintf(ficresvij,"******\n");
                   8076: 
                   8077:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8078:        oldm=oldms;savm=savms;
1.127     brouard  8079:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  8080:        /*
                   8081:         */
                   8082:        /* goto endfree; */
1.126     brouard  8083:  
                   8084:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8085:        pstamp(ficrest);
1.145     brouard  8086: 
                   8087: 
1.128     brouard  8088:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199     brouard  8089:          oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161     brouard  8090:          cptcod= 0; /* To be deleted */
1.203     brouard  8091:          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.145     brouard  8092:          fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
1.128     brouard  8093:          if(vpopbased==1)
                   8094:            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);
                   8095:          else
                   8096:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
1.201     brouard  8097:          fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
1.128     brouard  8098:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8099:          fprintf(ficrest,"\n");
1.199     brouard  8100:          /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128     brouard  8101:          epj=vector(1,nlstate+1);
                   8102:          for(age=bage; age <=fage ;age++){
1.203     brouard  8103:            prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
1.128     brouard  8104:            if (vpopbased==1) {
                   8105:              if(mobilav ==0){
                   8106:                for(i=1; i<=nlstate;i++)
                   8107:                  prlim[i][i]=probs[(int)age][i][k];
                   8108:              }else{ /* mobilav */ 
                   8109:                for(i=1; i<=nlstate;i++)
                   8110:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   8111:              }
1.126     brouard  8112:            }
                   8113:        
1.201     brouard  8114:            fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
1.199     brouard  8115:            /* printf(" age %4.0f ",age); */
1.128     brouard  8116:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8117:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8118:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199     brouard  8119:                /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8120:                /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128     brouard  8121:              }
                   8122:              epj[nlstate+1] +=epj[j];
1.126     brouard  8123:            }
1.199     brouard  8124:            /* printf(" age %4.0f \n",age); */
1.126     brouard  8125: 
1.128     brouard  8126:            for(i=1, vepp=0.;i <=nlstate;i++)
                   8127:              for(j=1;j <=nlstate;j++)
                   8128:                vepp += vareij[i][j][(int)age];
                   8129:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8130:            for(j=1;j <=nlstate;j++){
                   8131:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   8132:            }
                   8133:            fprintf(ficrest,"\n");
1.126     brouard  8134:          }
                   8135:        }
                   8136:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8137:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8138:        free_vector(epj,1,nlstate+1);
1.145     brouard  8139:       /*}*/
1.126     brouard  8140:     }
                   8141:     free_vector(weight,1,n);
1.145     brouard  8142:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8143:     free_imatrix(s,1,maxwav+1,1,n);
                   8144:     free_matrix(anint,1,maxwav,1,n); 
                   8145:     free_matrix(mint,1,maxwav,1,n);
                   8146:     free_ivector(cod,1,n);
                   8147:     free_ivector(tab,1,NCOVMAX);
                   8148:     fclose(ficresstdeij);
                   8149:     fclose(ficrescveij);
                   8150:     fclose(ficresvij);
                   8151:     fclose(ficrest);
                   8152:     fclose(ficpar);
                   8153:   
                   8154:     /*------- Variance of period (stable) prevalence------*/   
                   8155: 
1.201     brouard  8156:     strcpy(fileresvpl,"VPL_");
                   8157:     strcat(fileresvpl,fileresu);
1.126     brouard  8158:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8159:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8160:       exit(0);
                   8161:     }
                   8162:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   8163: 
1.145     brouard  8164:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8165:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8166:           
                   8167:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8168:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8169:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8170:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8171:        fprintf(ficresvpl,"******\n");
                   8172:       
                   8173:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8174:        oldm=oldms;savm=savms;
1.203     brouard  8175:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
1.126     brouard  8176:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8177:       /*}*/
1.126     brouard  8178:     }
                   8179: 
                   8180:     fclose(ficresvpl);
                   8181: 
                   8182:     /*---------- End : free ----------------*/
                   8183:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8184:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8185:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8186:  /* endfree:*/
1.141     brouard  8187:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8188:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8189:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8190:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8191:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8192:     free_matrix(covar,0,NCOVMAX,1,n);
                   8193:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8194:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8195:     /*free_vector(delti,1,npar);*/
                   8196:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8197:     free_matrix(agev,1,maxwav,1,imx);
                   8198:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8199: 
1.145     brouard  8200:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8201:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8202:     free_ivector(Tvar,1,NCOVMAX);
                   8203:     free_ivector(Tprod,1,NCOVMAX);
                   8204:     free_ivector(Tvaraff,1,NCOVMAX);
                   8205:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8206: 
                   8207:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8208:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8209:   fflush(fichtm);
                   8210:   fflush(ficgp);
                   8211:   
                   8212: 
                   8213:   if((nberr >0) || (nbwarn>0)){
                   8214:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8215:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8216:   }else{
                   8217:     printf("End of Imach\n");
                   8218:     fprintf(ficlog,"End of Imach\n");
                   8219:   }
                   8220:   printf("See log file on %s\n",filelog);
                   8221:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8222:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8223:   rend_time = time(NULL);  
                   8224:   end_time = *localtime(&rend_time);
                   8225:   /* tml = *localtime(&end_time.tm_sec); */
                   8226:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8227:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8228:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8229:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8230: 
1.157     brouard  8231:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8232:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8233:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8234:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8235: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8236:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8237:   fclose(fichtm);
                   8238:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8239:   fclose(fichtmcov);
                   8240:   fclose(ficgp);
                   8241:   fclose(ficlog);
                   8242:   /*------ End -----------*/
                   8243: 
                   8244: 
                   8245:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8246: #ifdef WIN32
                   8247:    if (_chdir(pathcd) != 0)
                   8248:           printf("Can't move to directory %s!\n",path);
                   8249:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8250: #else
1.126     brouard  8251:    if(chdir(pathcd) != 0)
1.184     brouard  8252:           printf("Can't move to directory %s!\n", path);
                   8253:    if (getcwd(pathcd, MAXLINE) > 0)
                   8254: #endif 
1.126     brouard  8255:     printf("Current directory %s!\n",pathcd);
                   8256:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8257:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8258: #ifdef _WIN32
1.126     brouard  8259:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8260: #endif
                   8261:   if(!stat(plotcmd,&info)){
1.158     brouard  8262:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8263:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8264:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8265:     }else
                   8266:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8267: #ifdef __unix
1.126     brouard  8268:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8269:     if(!stat(plotcmd,&info)){
1.158     brouard  8270:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8271:     }else
                   8272:       strcpy(pplotcmd,plotcmd);
                   8273: #endif
                   8274:   }else
                   8275:     strcpy(pplotcmd,plotcmd);
                   8276:   
                   8277:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8278:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8279: 
                   8280:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8281:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8282:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8283:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8284:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8285:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8286:   }
1.158     brouard  8287:   printf(" Successful, please wait...");
1.126     brouard  8288:   while (z[0] != 'q') {
                   8289:     /* chdir(path); */
1.154     brouard  8290:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8291:     scanf("%s",z);
                   8292: /*     if (z[0] == 'c') system("./imach"); */
                   8293:     if (z[0] == 'e') {
1.158     brouard  8294: #ifdef __APPLE__
1.152     brouard  8295:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8296: #elif __linux
                   8297:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8298: #else
1.152     brouard  8299:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8300: #endif
                   8301:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8302:       system(pplotcmd);
1.126     brouard  8303:     }
                   8304:     else if (z[0] == 'g') system(plotcmd);
                   8305:     else if (z[0] == 'q') exit(0);
                   8306:   }
                   8307:   end:
                   8308:   while (z[0] != 'q') {
1.195     brouard  8309:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8310:     scanf("%s",z);
                   8311:   }
                   8312: }

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