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

1.208   ! brouard     1: /* $Id: imach.c,v 1.207 2015/10/27 17:36:57 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.208   ! brouard     4:   Revision 1.207  2015/10/27 17:36:57  brouard
        !             5:   *** empty log message ***
        !             6: 
1.207     brouard     7:   Revision 1.206  2015/10/24 07:14:11  brouard
                      8:   *** empty log message ***
                      9: 
1.206     brouard    10:   Revision 1.205  2015/10/23 15:50:53  brouard
                     11:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     12: 
1.205     brouard    13:   Revision 1.204  2015/10/01 16:20:26  brouard
                     14:   Summary: Some new graphs of contribution to likelihood
                     15: 
1.204     brouard    16:   Revision 1.203  2015/09/30 17:45:14  brouard
                     17:   Summary: looking at better estimation of the hessian
                     18: 
                     19:   Also a better criteria for convergence to the period prevalence And
                     20:   therefore adding the number of years needed to converge. (The
                     21:   prevalence in any alive state shold sum to one
                     22: 
1.203     brouard    23:   Revision 1.202  2015/09/22 19:45:16  brouard
                     24:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     25: 
1.202     brouard    26:   Revision 1.201  2015/09/15 17:34:58  brouard
                     27:   Summary: 0.98r0
                     28: 
                     29:   - Some new graphs like suvival functions
                     30:   - Some bugs fixed like model=1+age+V2.
                     31: 
1.201     brouard    32:   Revision 1.200  2015/09/09 16:53:55  brouard
                     33:   Summary: Big bug thanks to Flavia
                     34: 
                     35:   Even model=1+age+V2. did not work anymore
                     36: 
1.200     brouard    37:   Revision 1.199  2015/09/07 14:09:23  brouard
                     38:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     39: 
1.199     brouard    40:   Revision 1.198  2015/09/03 07:14:39  brouard
                     41:   Summary: 0.98q5 Flavia
                     42: 
1.198     brouard    43:   Revision 1.197  2015/09/01 18:24:39  brouard
                     44:   *** empty log message ***
                     45: 
1.197     brouard    46:   Revision 1.196  2015/08/18 23:17:52  brouard
                     47:   Summary: 0.98q5
                     48: 
1.196     brouard    49:   Revision 1.195  2015/08/18 16:28:39  brouard
                     50:   Summary: Adding a hack for testing purpose
                     51: 
                     52:   After reading the title, ftol and model lines, if the comment line has
                     53:   a q, starting with #q, the answer at the end of the run is quit. It
                     54:   permits to run test files in batch with ctest. The former workaround was
                     55:   $ echo q | imach foo.imach
                     56: 
1.195     brouard    57:   Revision 1.194  2015/08/18 13:32:00  brouard
                     58:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     59: 
1.194     brouard    60:   Revision 1.193  2015/08/04 07:17:42  brouard
                     61:   Summary: 0.98q4
                     62: 
1.193     brouard    63:   Revision 1.192  2015/07/16 16:49:02  brouard
                     64:   Summary: Fixing some outputs
                     65: 
1.192     brouard    66:   Revision 1.191  2015/07/14 10:00:33  brouard
                     67:   Summary: Some fixes
                     68: 
1.191     brouard    69:   Revision 1.190  2015/05/05 08:51:13  brouard
                     70:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     71: 
                     72:   Fix 1+age+.
                     73: 
1.190     brouard    74:   Revision 1.189  2015/04/30 14:45:16  brouard
                     75:   Summary: 0.98q2
                     76: 
1.189     brouard    77:   Revision 1.188  2015/04/30 08:27:53  brouard
                     78:   *** empty log message ***
                     79: 
1.188     brouard    80:   Revision 1.187  2015/04/29 09:11:15  brouard
                     81:   *** empty log message ***
                     82: 
1.187     brouard    83:   Revision 1.186  2015/04/23 12:01:52  brouard
                     84:   Summary: V1*age is working now, version 0.98q1
                     85: 
                     86:   Some codes had been disabled in order to simplify and Vn*age was
                     87:   working in the optimization phase, ie, giving correct MLE parameters,
                     88:   but, as usual, outputs were not correct and program core dumped.
                     89: 
1.186     brouard    90:   Revision 1.185  2015/03/11 13:26:42  brouard
                     91:   Summary: Inclusion of compile and links command line for Intel Compiler
                     92: 
1.185     brouard    93:   Revision 1.184  2015/03/11 11:52:39  brouard
                     94:   Summary: Back from Windows 8. Intel Compiler
                     95: 
1.184     brouard    96:   Revision 1.183  2015/03/10 20:34:32  brouard
                     97:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     98: 
                     99:   We use directest instead of original Powell test; probably no
                    100:   incidence on the results, but better justifications;
                    101:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    102:   wrong results.
                    103: 
1.183     brouard   104:   Revision 1.182  2015/02/12 08:19:57  brouard
                    105:   Summary: Trying to keep directest which seems simpler and more general
                    106:   Author: Nicolas Brouard
                    107: 
1.182     brouard   108:   Revision 1.181  2015/02/11 23:22:24  brouard
                    109:   Summary: Comments on Powell added
                    110: 
                    111:   Author:
                    112: 
1.181     brouard   113:   Revision 1.180  2015/02/11 17:33:45  brouard
                    114:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    115: 
1.180     brouard   116:   Revision 1.179  2015/01/04 09:57:06  brouard
                    117:   Summary: back to OS/X
                    118: 
1.179     brouard   119:   Revision 1.178  2015/01/04 09:35:48  brouard
                    120:   *** empty log message ***
                    121: 
1.178     brouard   122:   Revision 1.177  2015/01/03 18:40:56  brouard
                    123:   Summary: Still testing ilc32 on OSX
                    124: 
1.177     brouard   125:   Revision 1.176  2015/01/03 16:45:04  brouard
                    126:   *** empty log message ***
                    127: 
1.176     brouard   128:   Revision 1.175  2015/01/03 16:33:42  brouard
                    129:   *** empty log message ***
                    130: 
1.175     brouard   131:   Revision 1.174  2015/01/03 16:15:49  brouard
                    132:   Summary: Still in cross-compilation
                    133: 
1.174     brouard   134:   Revision 1.173  2015/01/03 12:06:26  brouard
                    135:   Summary: trying to detect cross-compilation
                    136: 
1.173     brouard   137:   Revision 1.172  2014/12/27 12:07:47  brouard
                    138:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    139: 
1.172     brouard   140:   Revision 1.171  2014/12/23 13:26:59  brouard
                    141:   Summary: Back from Visual C
                    142: 
                    143:   Still problem with utsname.h on Windows
                    144: 
1.171     brouard   145:   Revision 1.170  2014/12/23 11:17:12  brouard
                    146:   Summary: Cleaning some \%% back to %%
                    147: 
                    148:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    149: 
1.170     brouard   150:   Revision 1.169  2014/12/22 23:08:31  brouard
                    151:   Summary: 0.98p
                    152: 
                    153:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    154: 
1.169     brouard   155:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   156:   Summary: update
1.169     brouard   157: 
1.168     brouard   158:   Revision 1.167  2014/12/22 13:50:56  brouard
                    159:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    160: 
                    161:   Testing on Linux 64
                    162: 
1.167     brouard   163:   Revision 1.166  2014/12/22 11:40:47  brouard
                    164:   *** empty log message ***
                    165: 
1.166     brouard   166:   Revision 1.165  2014/12/16 11:20:36  brouard
                    167:   Summary: After compiling on Visual C
                    168: 
                    169:   * imach.c (Module): Merging 1.61 to 1.162
                    170: 
1.165     brouard   171:   Revision 1.164  2014/12/16 10:52:11  brouard
                    172:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    173: 
                    174:   * imach.c (Module): Merging 1.61 to 1.162
                    175: 
1.164     brouard   176:   Revision 1.163  2014/12/16 10:30:11  brouard
                    177:   * imach.c (Module): Merging 1.61 to 1.162
                    178: 
1.163     brouard   179:   Revision 1.162  2014/09/25 11:43:39  brouard
                    180:   Summary: temporary backup 0.99!
                    181: 
1.162     brouard   182:   Revision 1.1  2014/09/16 11:06:58  brouard
                    183:   Summary: With some code (wrong) for nlopt
                    184: 
                    185:   Author:
                    186: 
                    187:   Revision 1.161  2014/09/15 20:41:41  brouard
                    188:   Summary: Problem with macro SQR on Intel compiler
                    189: 
1.161     brouard   190:   Revision 1.160  2014/09/02 09:24:05  brouard
                    191:   *** empty log message ***
                    192: 
1.160     brouard   193:   Revision 1.159  2014/09/01 10:34:10  brouard
                    194:   Summary: WIN32
                    195:   Author: Brouard
                    196: 
1.159     brouard   197:   Revision 1.158  2014/08/27 17:11:51  brouard
                    198:   *** empty log message ***
                    199: 
1.158     brouard   200:   Revision 1.157  2014/08/27 16:26:55  brouard
                    201:   Summary: Preparing windows Visual studio version
                    202:   Author: Brouard
                    203: 
                    204:   In order to compile on Visual studio, time.h is now correct and time_t
                    205:   and tm struct should be used. difftime should be used but sometimes I
                    206:   just make the differences in raw time format (time(&now).
                    207:   Trying to suppress #ifdef LINUX
                    208:   Add xdg-open for __linux in order to open default browser.
                    209: 
1.157     brouard   210:   Revision 1.156  2014/08/25 20:10:10  brouard
                    211:   *** empty log message ***
                    212: 
1.156     brouard   213:   Revision 1.155  2014/08/25 18:32:34  brouard
                    214:   Summary: New compile, minor changes
                    215:   Author: Brouard
                    216: 
1.155     brouard   217:   Revision 1.154  2014/06/20 17:32:08  brouard
                    218:   Summary: Outputs now all graphs of convergence to period prevalence
                    219: 
1.154     brouard   220:   Revision 1.153  2014/06/20 16:45:46  brouard
                    221:   Summary: If 3 live state, convergence to period prevalence on same graph
                    222:   Author: Brouard
                    223: 
1.153     brouard   224:   Revision 1.152  2014/06/18 17:54:09  brouard
                    225:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    226: 
1.152     brouard   227:   Revision 1.151  2014/06/18 16:43:30  brouard
                    228:   *** empty log message ***
                    229: 
1.151     brouard   230:   Revision 1.150  2014/06/18 16:42:35  brouard
                    231:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    232:   Author: brouard
                    233: 
1.150     brouard   234:   Revision 1.149  2014/06/18 15:51:14  brouard
                    235:   Summary: Some fixes in parameter files errors
                    236:   Author: Nicolas Brouard
                    237: 
1.149     brouard   238:   Revision 1.148  2014/06/17 17:38:48  brouard
                    239:   Summary: Nothing new
                    240:   Author: Brouard
                    241: 
                    242:   Just a new packaging for OS/X version 0.98nS
                    243: 
1.148     brouard   244:   Revision 1.147  2014/06/16 10:33:11  brouard
                    245:   *** empty log message ***
                    246: 
1.147     brouard   247:   Revision 1.146  2014/06/16 10:20:28  brouard
                    248:   Summary: Merge
                    249:   Author: Brouard
                    250: 
                    251:   Merge, before building revised version.
                    252: 
1.146     brouard   253:   Revision 1.145  2014/06/10 21:23:15  brouard
                    254:   Summary: Debugging with valgrind
                    255:   Author: Nicolas Brouard
                    256: 
                    257:   Lot of changes in order to output the results with some covariates
                    258:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    259:   improve the code.
                    260:   No more memory valgrind error but a lot has to be done in order to
                    261:   continue the work of splitting the code into subroutines.
                    262:   Also, decodemodel has been improved. Tricode is still not
                    263:   optimal. nbcode should be improved. Documentation has been added in
                    264:   the source code.
                    265: 
1.144     brouard   266:   Revision 1.143  2014/01/26 09:45:38  brouard
                    267:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    268: 
                    269:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    270:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    271: 
1.143     brouard   272:   Revision 1.142  2014/01/26 03:57:36  brouard
                    273:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    274: 
                    275:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    276: 
1.142     brouard   277:   Revision 1.141  2014/01/26 02:42:01  brouard
                    278:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    279: 
1.141     brouard   280:   Revision 1.140  2011/09/02 10:37:54  brouard
                    281:   Summary: times.h is ok with mingw32 now.
                    282: 
1.140     brouard   283:   Revision 1.139  2010/06/14 07:50:17  brouard
                    284:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    285:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    286: 
1.139     brouard   287:   Revision 1.138  2010/04/30 18:19:40  brouard
                    288:   *** empty log message ***
                    289: 
1.138     brouard   290:   Revision 1.137  2010/04/29 18:11:38  brouard
                    291:   (Module): Checking covariates for more complex models
                    292:   than V1+V2. A lot of change to be done. Unstable.
                    293: 
1.137     brouard   294:   Revision 1.136  2010/04/26 20:30:53  brouard
                    295:   (Module): merging some libgsl code. Fixing computation
                    296:   of likelione (using inter/intrapolation if mle = 0) in order to
                    297:   get same likelihood as if mle=1.
                    298:   Some cleaning of code and comments added.
                    299: 
1.136     brouard   300:   Revision 1.135  2009/10/29 15:33:14  brouard
                    301:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    302: 
1.135     brouard   303:   Revision 1.134  2009/10/29 13:18:53  brouard
                    304:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    305: 
1.134     brouard   306:   Revision 1.133  2009/07/06 10:21:25  brouard
                    307:   just nforces
                    308: 
1.133     brouard   309:   Revision 1.132  2009/07/06 08:22:05  brouard
                    310:   Many tings
                    311: 
1.132     brouard   312:   Revision 1.131  2009/06/20 16:22:47  brouard
                    313:   Some dimensions resccaled
                    314: 
1.131     brouard   315:   Revision 1.130  2009/05/26 06:44:34  brouard
                    316:   (Module): Max Covariate is now set to 20 instead of 8. A
                    317:   lot of cleaning with variables initialized to 0. Trying to make
                    318:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    319: 
1.130     brouard   320:   Revision 1.129  2007/08/31 13:49:27  lievre
                    321:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    322: 
1.129     lievre    323:   Revision 1.128  2006/06/30 13:02:05  brouard
                    324:   (Module): Clarifications on computing e.j
                    325: 
1.128     brouard   326:   Revision 1.127  2006/04/28 18:11:50  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:   (Module): In order to speed up (in case of numerous covariates) we
                    331:   compute health expectancies (without variances) in a first step
                    332:   and then all the health expectancies with variances or standard
                    333:   deviation (needs data from the Hessian matrices) which slows the
                    334:   computation.
                    335:   In the future we should be able to stop the program is only health
                    336:   expectancies and graph are needed without standard deviations.
                    337: 
1.127     brouard   338:   Revision 1.126  2006/04/28 17:23:28  brouard
                    339:   (Module): Yes the sum of survivors was wrong since
                    340:   imach-114 because nhstepm was no more computed in the age
                    341:   loop. Now we define nhstepma in the age loop.
                    342:   Version 0.98h
                    343: 
1.126     brouard   344:   Revision 1.125  2006/04/04 15:20:31  lievre
                    345:   Errors in calculation of health expectancies. Age was not initialized.
                    346:   Forecasting file added.
                    347: 
                    348:   Revision 1.124  2006/03/22 17:13:53  lievre
                    349:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    350:   The log-likelihood is printed in the log file
                    351: 
                    352:   Revision 1.123  2006/03/20 10:52:43  brouard
                    353:   * imach.c (Module): <title> changed, corresponds to .htm file
                    354:   name. <head> headers where missing.
                    355: 
                    356:   * imach.c (Module): Weights can have a decimal point as for
                    357:   English (a comma might work with a correct LC_NUMERIC environment,
                    358:   otherwise the weight is truncated).
                    359:   Modification of warning when the covariates values are not 0 or
                    360:   1.
                    361:   Version 0.98g
                    362: 
                    363:   Revision 1.122  2006/03/20 09:45:41  brouard
                    364:   (Module): Weights can have a decimal point as for
                    365:   English (a comma might work with a correct LC_NUMERIC environment,
                    366:   otherwise the weight is truncated).
                    367:   Modification of warning when the covariates values are not 0 or
                    368:   1.
                    369:   Version 0.98g
                    370: 
                    371:   Revision 1.121  2006/03/16 17:45:01  lievre
                    372:   * imach.c (Module): Comments concerning covariates added
                    373: 
                    374:   * imach.c (Module): refinements in the computation of lli if
                    375:   status=-2 in order to have more reliable computation if stepm is
                    376:   not 1 month. Version 0.98f
                    377: 
                    378:   Revision 1.120  2006/03/16 15:10:38  lievre
                    379:   (Module): refinements in the computation of lli if
                    380:   status=-2 in order to have more reliable computation if stepm is
                    381:   not 1 month. Version 0.98f
                    382: 
                    383:   Revision 1.119  2006/03/15 17:42:26  brouard
                    384:   (Module): Bug if status = -2, the loglikelihood was
                    385:   computed as likelihood omitting the logarithm. Version O.98e
                    386: 
                    387:   Revision 1.118  2006/03/14 18:20:07  brouard
                    388:   (Module): varevsij Comments added explaining the second
                    389:   table of variances if popbased=1 .
                    390:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    391:   (Module): Function pstamp added
                    392:   (Module): Version 0.98d
                    393: 
                    394:   Revision 1.117  2006/03/14 17:16:22  brouard
                    395:   (Module): varevsij Comments added explaining the second
                    396:   table of variances if popbased=1 .
                    397:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    398:   (Module): Function pstamp added
                    399:   (Module): Version 0.98d
                    400: 
                    401:   Revision 1.116  2006/03/06 10:29:27  brouard
                    402:   (Module): Variance-covariance wrong links and
                    403:   varian-covariance of ej. is needed (Saito).
                    404: 
                    405:   Revision 1.115  2006/02/27 12:17:45  brouard
                    406:   (Module): One freematrix added in mlikeli! 0.98c
                    407: 
                    408:   Revision 1.114  2006/02/26 12:57:58  brouard
                    409:   (Module): Some improvements in processing parameter
                    410:   filename with strsep.
                    411: 
                    412:   Revision 1.113  2006/02/24 14:20:24  brouard
                    413:   (Module): Memory leaks checks with valgrind and:
                    414:   datafile was not closed, some imatrix were not freed and on matrix
                    415:   allocation too.
                    416: 
                    417:   Revision 1.112  2006/01/30 09:55:26  brouard
                    418:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    419: 
                    420:   Revision 1.111  2006/01/25 20:38:18  brouard
                    421:   (Module): Lots of cleaning and bugs added (Gompertz)
                    422:   (Module): Comments can be added in data file. Missing date values
                    423:   can be a simple dot '.'.
                    424: 
                    425:   Revision 1.110  2006/01/25 00:51:50  brouard
                    426:   (Module): Lots of cleaning and bugs added (Gompertz)
                    427: 
                    428:   Revision 1.109  2006/01/24 19:37:15  brouard
                    429:   (Module): Comments (lines starting with a #) are allowed in data.
                    430: 
                    431:   Revision 1.108  2006/01/19 18:05:42  lievre
                    432:   Gnuplot problem appeared...
                    433:   To be fixed
                    434: 
                    435:   Revision 1.107  2006/01/19 16:20:37  brouard
                    436:   Test existence of gnuplot in imach path
                    437: 
                    438:   Revision 1.106  2006/01/19 13:24:36  brouard
                    439:   Some cleaning and links added in html output
                    440: 
                    441:   Revision 1.105  2006/01/05 20:23:19  lievre
                    442:   *** empty log message ***
                    443: 
                    444:   Revision 1.104  2005/09/30 16:11:43  lievre
                    445:   (Module): sump fixed, loop imx fixed, and simplifications.
                    446:   (Module): If the status is missing at the last wave but we know
                    447:   that the person is alive, then we can code his/her status as -2
                    448:   (instead of missing=-1 in earlier versions) and his/her
                    449:   contributions to the likelihood is 1 - Prob of dying from last
                    450:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    451:   the healthy state at last known wave). Version is 0.98
                    452: 
                    453:   Revision 1.103  2005/09/30 15:54:49  lievre
                    454:   (Module): sump fixed, loop imx fixed, and simplifications.
                    455: 
                    456:   Revision 1.102  2004/09/15 17:31:30  brouard
                    457:   Add the possibility to read data file including tab characters.
                    458: 
                    459:   Revision 1.101  2004/09/15 10:38:38  brouard
                    460:   Fix on curr_time
                    461: 
                    462:   Revision 1.100  2004/07/12 18:29:06  brouard
                    463:   Add version for Mac OS X. Just define UNIX in Makefile
                    464: 
                    465:   Revision 1.99  2004/06/05 08:57:40  brouard
                    466:   *** empty log message ***
                    467: 
                    468:   Revision 1.98  2004/05/16 15:05:56  brouard
                    469:   New version 0.97 . First attempt to estimate force of mortality
                    470:   directly from the data i.e. without the need of knowing the health
                    471:   state at each age, but using a Gompertz model: log u =a + b*age .
                    472:   This is the basic analysis of mortality and should be done before any
                    473:   other analysis, in order to test if the mortality estimated from the
                    474:   cross-longitudinal survey is different from the mortality estimated
                    475:   from other sources like vital statistic data.
                    476: 
                    477:   The same imach parameter file can be used but the option for mle should be -3.
                    478: 
1.133     brouard   479:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   480:   former routines in order to include the new code within the former code.
                    481: 
                    482:   The output is very simple: only an estimate of the intercept and of
                    483:   the slope with 95% confident intervals.
                    484: 
                    485:   Current limitations:
                    486:   A) Even if you enter covariates, i.e. with the
                    487:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    488:   B) There is no computation of Life Expectancy nor Life Table.
                    489: 
                    490:   Revision 1.97  2004/02/20 13:25:42  lievre
                    491:   Version 0.96d. Population forecasting command line is (temporarily)
                    492:   suppressed.
                    493: 
                    494:   Revision 1.96  2003/07/15 15:38:55  brouard
                    495:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    496:   rewritten within the same printf. Workaround: many printfs.
                    497: 
                    498:   Revision 1.95  2003/07/08 07:54:34  brouard
                    499:   * imach.c (Repository):
                    500:   (Repository): Using imachwizard code to output a more meaningful covariance
                    501:   matrix (cov(a12,c31) instead of numbers.
                    502: 
                    503:   Revision 1.94  2003/06/27 13:00:02  brouard
                    504:   Just cleaning
                    505: 
                    506:   Revision 1.93  2003/06/25 16:33:55  brouard
                    507:   (Module): On windows (cygwin) function asctime_r doesn't
                    508:   exist so I changed back to asctime which exists.
                    509:   (Module): Version 0.96b
                    510: 
                    511:   Revision 1.92  2003/06/25 16:30:45  brouard
                    512:   (Module): On windows (cygwin) function asctime_r doesn't
                    513:   exist so I changed back to asctime which exists.
                    514: 
                    515:   Revision 1.91  2003/06/25 15:30:29  brouard
                    516:   * imach.c (Repository): Duplicated warning errors corrected.
                    517:   (Repository): Elapsed time after each iteration is now output. It
                    518:   helps to forecast when convergence will be reached. Elapsed time
                    519:   is stamped in powell.  We created a new html file for the graphs
                    520:   concerning matrix of covariance. It has extension -cov.htm.
                    521: 
                    522:   Revision 1.90  2003/06/24 12:34:15  brouard
                    523:   (Module): Some bugs corrected for windows. Also, when
                    524:   mle=-1 a template is output in file "or"mypar.txt with the design
                    525:   of the covariance matrix to be input.
                    526: 
                    527:   Revision 1.89  2003/06/24 12:30:52  brouard
                    528:   (Module): Some bugs corrected for windows. Also, when
                    529:   mle=-1 a template is output in file "or"mypar.txt with the design
                    530:   of the covariance matrix to be input.
                    531: 
                    532:   Revision 1.88  2003/06/23 17:54:56  brouard
                    533:   * 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.
                    534: 
                    535:   Revision 1.87  2003/06/18 12:26:01  brouard
                    536:   Version 0.96
                    537: 
                    538:   Revision 1.86  2003/06/17 20:04:08  brouard
                    539:   (Module): Change position of html and gnuplot routines and added
                    540:   routine fileappend.
                    541: 
                    542:   Revision 1.85  2003/06/17 13:12:43  brouard
                    543:   * imach.c (Repository): Check when date of death was earlier that
                    544:   current date of interview. It may happen when the death was just
                    545:   prior to the death. In this case, dh was negative and likelihood
                    546:   was wrong (infinity). We still send an "Error" but patch by
                    547:   assuming that the date of death was just one stepm after the
                    548:   interview.
                    549:   (Repository): Because some people have very long ID (first column)
                    550:   we changed int to long in num[] and we added a new lvector for
                    551:   memory allocation. But we also truncated to 8 characters (left
                    552:   truncation)
                    553:   (Repository): No more line truncation errors.
                    554: 
                    555:   Revision 1.84  2003/06/13 21:44:43  brouard
                    556:   * imach.c (Repository): Replace "freqsummary" at a correct
                    557:   place. It differs from routine "prevalence" which may be called
                    558:   many times. Probs is memory consuming and must be used with
                    559:   parcimony.
                    560:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    561: 
                    562:   Revision 1.83  2003/06/10 13:39:11  lievre
                    563:   *** empty log message ***
                    564: 
                    565:   Revision 1.82  2003/06/05 15:57:20  brouard
                    566:   Add log in  imach.c and  fullversion number is now printed.
                    567: 
                    568: */
                    569: /*
                    570:    Interpolated Markov Chain
                    571: 
                    572:   Short summary of the programme:
                    573:   
                    574:   This program computes Healthy Life Expectancies from
                    575:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    576:   first survey ("cross") where individuals from different ages are
                    577:   interviewed on their health status or degree of disability (in the
                    578:   case of a health survey which is our main interest) -2- at least a
                    579:   second wave of interviews ("longitudinal") which measure each change
                    580:   (if any) in individual health status.  Health expectancies are
                    581:   computed from the time spent in each health state according to a
                    582:   model. More health states you consider, more time is necessary to reach the
                    583:   Maximum Likelihood of the parameters involved in the model.  The
                    584:   simplest model is the multinomial logistic model where pij is the
                    585:   probability to be observed in state j at the second wave
                    586:   conditional to be observed in state i at the first wave. Therefore
                    587:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    588:   'age' is age and 'sex' is a covariate. If you want to have a more
                    589:   complex model than "constant and age", you should modify the program
                    590:   where the markup *Covariates have to be included here again* invites
                    591:   you to do it.  More covariates you add, slower the
                    592:   convergence.
                    593: 
                    594:   The advantage of this computer programme, compared to a simple
                    595:   multinomial logistic model, is clear when the delay between waves is not
                    596:   identical for each individual. Also, if a individual missed an
                    597:   intermediate interview, the information is lost, but taken into
                    598:   account using an interpolation or extrapolation.  
                    599: 
                    600:   hPijx is the probability to be observed in state i at age x+h
                    601:   conditional to the observed state i at age x. The delay 'h' can be
                    602:   split into an exact number (nh*stepm) of unobserved intermediate
                    603:   states. This elementary transition (by month, quarter,
                    604:   semester or year) is modelled as a multinomial logistic.  The hPx
                    605:   matrix is simply the matrix product of nh*stepm elementary matrices
                    606:   and the contribution of each individual to the likelihood is simply
                    607:   hPijx.
                    608: 
                    609:   Also this programme outputs the covariance matrix of the parameters but also
                    610:   of the life expectancies. It also computes the period (stable) prevalence. 
                    611:   
1.133     brouard   612:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    613:            Institut national d'études démographiques, Paris.
1.126     brouard   614:   This software have been partly granted by Euro-REVES, a concerted action
                    615:   from the European Union.
                    616:   It is copyrighted identically to a GNU software product, ie programme and
                    617:   software can be distributed freely for non commercial use. Latest version
                    618:   can be accessed at http://euroreves.ined.fr/imach .
                    619: 
                    620:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    621:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    622:   
                    623:   **********************************************************************/
                    624: /*
                    625:   main
                    626:   read parameterfile
                    627:   read datafile
                    628:   concatwav
                    629:   freqsummary
                    630:   if (mle >= 1)
                    631:     mlikeli
                    632:   print results files
                    633:   if mle==1 
                    634:      computes hessian
                    635:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    636:       begin-prev-date,...
                    637:   open gnuplot file
                    638:   open html file
1.145     brouard   639:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    640:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    641:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    642:     freexexit2 possible for memory heap.
                    643: 
                    644:   h Pij x                         | pij_nom  ficrestpij
                    645:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    646:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    647:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    648: 
                    649:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    650:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    651:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    652:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    653:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    654: 
1.126     brouard   655:   forecasting if prevfcast==1 prevforecast call prevalence()
                    656:   health expectancies
                    657:   Variance-covariance of DFLE
                    658:   prevalence()
                    659:    movingaverage()
                    660:   varevsij() 
                    661:   if popbased==1 varevsij(,popbased)
                    662:   total life expectancies
                    663:   Variance of period (stable) prevalence
                    664:  end
                    665: */
                    666: 
1.187     brouard   667: /* #define DEBUG */
                    668: /* #define DEBUGBRENT */
1.203     brouard   669: /* #define DEBUGLINMIN */
                    670: /* #define DEBUGHESS */
                    671: #define DEBUGHESSIJ
                    672: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   673: #define POWELL /* Instead of NLOPT */
1.192     brouard   674: #define POWELLF1F3 /* Skip test */
1.186     brouard   675: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    676: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   677: 
                    678: #include <math.h>
                    679: #include <stdio.h>
                    680: #include <stdlib.h>
                    681: #include <string.h>
1.159     brouard   682: 
                    683: #ifdef _WIN32
                    684: #include <io.h>
1.172     brouard   685: #include <windows.h>
                    686: #include <tchar.h>
1.159     brouard   687: #else
1.126     brouard   688: #include <unistd.h>
1.159     brouard   689: #endif
1.126     brouard   690: 
                    691: #include <limits.h>
                    692: #include <sys/types.h>
1.171     brouard   693: 
                    694: #if defined(__GNUC__)
                    695: #include <sys/utsname.h> /* Doesn't work on Windows */
                    696: #endif
                    697: 
1.126     brouard   698: #include <sys/stat.h>
                    699: #include <errno.h>
1.159     brouard   700: /* extern int errno; */
1.126     brouard   701: 
1.157     brouard   702: /* #ifdef LINUX */
                    703: /* #include <time.h> */
                    704: /* #include "timeval.h" */
                    705: /* #else */
                    706: /* #include <sys/time.h> */
                    707: /* #endif */
                    708: 
1.126     brouard   709: #include <time.h>
                    710: 
1.136     brouard   711: #ifdef GSL
                    712: #include <gsl/gsl_errno.h>
                    713: #include <gsl/gsl_multimin.h>
                    714: #endif
                    715: 
1.167     brouard   716: 
1.162     brouard   717: #ifdef NLOPT
                    718: #include <nlopt.h>
                    719: typedef struct {
                    720:   double (* function)(double [] );
                    721: } myfunc_data ;
                    722: #endif
                    723: 
1.126     brouard   724: /* #include <libintl.h> */
                    725: /* #define _(String) gettext (String) */
                    726: 
1.141     brouard   727: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   728: 
                    729: #define GNUPLOTPROGRAM "gnuplot"
                    730: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    731: #define FILENAMELENGTH 132
                    732: 
                    733: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    734: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    735: 
1.144     brouard   736: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    737: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   738: 
                    739: #define NINTERVMAX 8
1.144     brouard   740: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    741: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    742: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   743: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   744: #define MAXN 20000
1.144     brouard   745: #define YEARM 12. /**< Number of months per year */
1.126     brouard   746: #define AGESUP 130
                    747: #define AGEBASE 40
1.194     brouard   748: #define AGEOVERFLOW 1.e20
1.164     brouard   749: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   750: #ifdef _WIN32
                    751: #define DIRSEPARATOR '\\'
                    752: #define CHARSEPARATOR "\\"
                    753: #define ODIRSEPARATOR '/'
                    754: #else
1.126     brouard   755: #define DIRSEPARATOR '/'
                    756: #define CHARSEPARATOR "/"
                    757: #define ODIRSEPARATOR '\\'
                    758: #endif
                    759: 
1.208   ! brouard   760: /* $Id: imach.c,v 1.207 2015/10/27 17:36:57 brouard Exp $ */
1.126     brouard   761: /* $State: Exp $ */
1.196     brouard   762: #include "version.h"
                    763: char version[]=__IMACH_VERSION__;
1.204     brouard   764: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.208   ! brouard   765: char fullversion[]="$Revision: 1.207 $ $Date: 2015/10/27 17:36:57 $"; 
1.126     brouard   766: char strstart[80];
                    767: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   768: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   769: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   770: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    771: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    772: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    773: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    774: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    775: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    776: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    777: int cptcov=0; /* Working variable */
1.126     brouard   778: int npar=NPARMAX;
                    779: int nlstate=2; /* Number of live states */
                    780: int ndeath=1; /* Number of dead states */
1.130     brouard   781: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   782: int popbased=0;
                    783: 
                    784: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   785: int maxwav=0; /* Maxim number of waves */
                    786: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    787: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    788: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   789:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   790: int mle=1, weightopt=0;
1.126     brouard   791: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    792: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    793: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    794:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   795: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   796: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   797: double **matprod2(); /* test */
1.126     brouard   798: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    799: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   800: /*FILE *fic ; */ /* Used in readdata only */
                    801: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   802: FILE *ficlog, *ficrespow;
1.130     brouard   803: int globpr=0; /* Global variable for printing or not */
1.126     brouard   804: double fretone; /* Only one call to likelihood */
1.130     brouard   805: long ipmx=0; /* Number of contributions */
1.126     brouard   806: double sw; /* Sum of weights */
                    807: char filerespow[FILENAMELENGTH];
                    808: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    809: FILE *ficresilk;
                    810: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    811: FILE *ficresprobmorprev;
                    812: FILE *fichtm, *fichtmcov; /* Html File */
                    813: FILE *ficreseij;
                    814: char filerese[FILENAMELENGTH];
                    815: FILE *ficresstdeij;
                    816: char fileresstde[FILENAMELENGTH];
                    817: FILE *ficrescveij;
                    818: char filerescve[FILENAMELENGTH];
                    819: FILE  *ficresvij;
                    820: char fileresv[FILENAMELENGTH];
                    821: FILE  *ficresvpl;
                    822: char fileresvpl[FILENAMELENGTH];
                    823: char title[MAXLINE];
                    824: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    825: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    826: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    827: char command[FILENAMELENGTH];
                    828: int  outcmd=0;
                    829: 
                    830: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   831: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   832: char filelog[FILENAMELENGTH]; /* Log file */
                    833: char filerest[FILENAMELENGTH];
                    834: char fileregp[FILENAMELENGTH];
                    835: char popfile[FILENAMELENGTH];
                    836: 
                    837: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    838: 
1.157     brouard   839: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    840: /* struct timezone tzp; */
                    841: /* extern int gettimeofday(); */
                    842: struct tm tml, *gmtime(), *localtime();
                    843: 
                    844: extern time_t time();
                    845: 
                    846: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    847: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    848: struct tm tm;
                    849: 
1.126     brouard   850: char strcurr[80], strfor[80];
                    851: 
                    852: char *endptr;
                    853: long lval;
                    854: double dval;
                    855: 
                    856: #define NR_END 1
                    857: #define FREE_ARG char*
                    858: #define FTOL 1.0e-10
                    859: 
                    860: #define NRANSI 
                    861: #define ITMAX 200 
                    862: 
                    863: #define TOL 2.0e-4 
                    864: 
                    865: #define CGOLD 0.3819660 
                    866: #define ZEPS 1.0e-10 
                    867: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    868: 
                    869: #define GOLD 1.618034 
                    870: #define GLIMIT 100.0 
                    871: #define TINY 1.0e-20 
                    872: 
                    873: static double maxarg1,maxarg2;
                    874: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    875: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    876:   
                    877: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    878: #define rint(a) floor(a+0.5)
1.166     brouard   879: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   880: #define mytinydouble 1.0e-16
1.166     brouard   881: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    882: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    883: /* static double dsqrarg; */
                    884: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   885: static double sqrarg;
                    886: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    887: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    888: int agegomp= AGEGOMP;
                    889: 
                    890: int imx; 
                    891: int stepm=1;
                    892: /* Stepm, step in month: minimum step interpolation*/
                    893: 
                    894: int estepm;
                    895: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    896: 
                    897: int m,nb;
                    898: long *num;
1.197     brouard   899: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   900: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    901:                   covariate for which somebody answered excluding 
                    902:                   undefined. Usually 2: 0 and 1. */
                    903: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    904:                             covariate for which somebody answered including 
                    905:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   906: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    907: double **pmmij, ***probs;
                    908: double *ageexmed,*agecens;
                    909: double dateintmean=0;
                    910: 
                    911: double *weight;
                    912: int **s; /* Status */
1.141     brouard   913: double *agedc;
1.145     brouard   914: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   915:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   916:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   917: double  idx; 
                    918: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   919: int *Tage;
1.145     brouard   920: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   921: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   922: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   923: double *lsurv, *lpop, *tpop;
                    924: 
1.143     brouard   925: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    926: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   927: 
                    928: /**************** split *************************/
                    929: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    930: {
                    931:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    932:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    933:   */ 
                    934:   char *ss;                            /* pointer */
1.186     brouard   935:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   936: 
                    937:   l1 = strlen(path );                  /* length of path */
                    938:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    939:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    940:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    941:     strcpy( name, path );              /* we got the fullname name because no directory */
                    942:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    943:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    944:     /* get current working directory */
                    945:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   946: #ifdef WIN32
                    947:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    948: #else
                    949:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    950: #endif
1.126     brouard   951:       return( GLOCK_ERROR_GETCWD );
                    952:     }
                    953:     /* got dirc from getcwd*/
                    954:     printf(" DIRC = %s \n",dirc);
1.205     brouard   955:   } else {                             /* strip directory from path */
1.126     brouard   956:     ss++;                              /* after this, the filename */
                    957:     l2 = strlen( ss );                 /* length of filename */
                    958:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    959:     strcpy( name, ss );                /* save file name */
                    960:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   961:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   962:     printf(" DIRC2 = %s \n",dirc);
                    963:   }
                    964:   /* We add a separator at the end of dirc if not exists */
                    965:   l1 = strlen( dirc );                 /* length of directory */
                    966:   if( dirc[l1-1] != DIRSEPARATOR ){
                    967:     dirc[l1] =  DIRSEPARATOR;
                    968:     dirc[l1+1] = 0; 
                    969:     printf(" DIRC3 = %s \n",dirc);
                    970:   }
                    971:   ss = strrchr( name, '.' );           /* find last / */
                    972:   if (ss >0){
                    973:     ss++;
                    974:     strcpy(ext,ss);                    /* save extension */
                    975:     l1= strlen( name);
                    976:     l2= strlen(ss)+1;
                    977:     strncpy( finame, name, l1-l2);
                    978:     finame[l1-l2]= 0;
                    979:   }
                    980: 
                    981:   return( 0 );                         /* we're done */
                    982: }
                    983: 
                    984: 
                    985: /******************************************/
                    986: 
                    987: void replace_back_to_slash(char *s, char*t)
                    988: {
                    989:   int i;
                    990:   int lg=0;
                    991:   i=0;
                    992:   lg=strlen(t);
                    993:   for(i=0; i<= lg; i++) {
                    994:     (s[i] = t[i]);
                    995:     if (t[i]== '\\') s[i]='/';
                    996:   }
                    997: }
                    998: 
1.132     brouard   999: char *trimbb(char *out, char *in)
1.137     brouard  1000: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1001:   char *s;
                   1002:   s=out;
                   1003:   while (*in != '\0'){
1.137     brouard  1004:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1005:       in++;
                   1006:     }
                   1007:     *out++ = *in++;
                   1008:   }
                   1009:   *out='\0';
                   1010:   return s;
                   1011: }
                   1012: 
1.187     brouard  1013: /* char *substrchaine(char *out, char *in, char *chain) */
                   1014: /* { */
                   1015: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1016: /*   char *s, *t; */
                   1017: /*   t=in;s=out; */
                   1018: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1019: /*     *out++ = *in++; */
                   1020: /*   } */
                   1021: 
                   1022: /*   /\* *in matches *chain *\/ */
                   1023: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1024: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1025: /*   } */
                   1026: /*   in--; chain--; */
                   1027: /*   while ( (*in != '\0')){ */
                   1028: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1029: /*     *out++ = *in++; */
                   1030: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1031: /*   } */
                   1032: /*   *out='\0'; */
                   1033: /*   out=s; */
                   1034: /*   return out; */
                   1035: /* } */
                   1036: char *substrchaine(char *out, char *in, char *chain)
                   1037: {
                   1038:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1039:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1040: 
                   1041:   char *strloc;
                   1042: 
                   1043:   strcpy (out, in); 
                   1044:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1045:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1046:   if(strloc != NULL){ 
                   1047:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1048:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1049:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1050:   }
                   1051:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1052:   return out;
                   1053: }
                   1054: 
                   1055: 
1.145     brouard  1056: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1057: {
1.187     brouard  1058:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1059:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1060:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1061:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1062:   */
1.160     brouard  1063:   char *s, *t;
1.145     brouard  1064:   t=in;s=in;
                   1065:   while ((*in != occ) && (*in != '\0')){
                   1066:     *alocc++ = *in++;
                   1067:   }
                   1068:   if( *in == occ){
                   1069:     *(alocc)='\0';
                   1070:     s=++in;
                   1071:   }
                   1072:  
                   1073:   if (s == t) {/* occ not found */
                   1074:     *(alocc-(in-s))='\0';
                   1075:     in=s;
                   1076:   }
                   1077:   while ( *in != '\0'){
                   1078:     *blocc++ = *in++;
                   1079:   }
                   1080: 
                   1081:   *blocc='\0';
                   1082:   return t;
                   1083: }
1.137     brouard  1084: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1085: {
1.187     brouard  1086:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1087:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1088:      gives blocc="abcdef2ghi" and alocc="j".
                   1089:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1090:   */
                   1091:   char *s, *t;
                   1092:   t=in;s=in;
                   1093:   while (*in != '\0'){
                   1094:     while( *in == occ){
                   1095:       *blocc++ = *in++;
                   1096:       s=in;
                   1097:     }
                   1098:     *blocc++ = *in++;
                   1099:   }
                   1100:   if (s == t) /* occ not found */
                   1101:     *(blocc-(in-s))='\0';
                   1102:   else
                   1103:     *(blocc-(in-s)-1)='\0';
                   1104:   in=s;
                   1105:   while ( *in != '\0'){
                   1106:     *alocc++ = *in++;
                   1107:   }
                   1108: 
                   1109:   *alocc='\0';
                   1110:   return s;
                   1111: }
                   1112: 
1.126     brouard  1113: int nbocc(char *s, char occ)
                   1114: {
                   1115:   int i,j=0;
                   1116:   int lg=20;
                   1117:   i=0;
                   1118:   lg=strlen(s);
                   1119:   for(i=0; i<= lg; i++) {
                   1120:   if  (s[i] == occ ) j++;
                   1121:   }
                   1122:   return j;
                   1123: }
                   1124: 
1.137     brouard  1125: /* void cutv(char *u,char *v, char*t, char occ) */
                   1126: /* { */
                   1127: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1128: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1129: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1130: /*   int i,lg,j,p=0; */
                   1131: /*   i=0; */
                   1132: /*   lg=strlen(t); */
                   1133: /*   for(j=0; j<=lg-1; j++) { */
                   1134: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1135: /*   } */
1.126     brouard  1136: 
1.137     brouard  1137: /*   for(j=0; j<p; j++) { */
                   1138: /*     (u[j] = t[j]); */
                   1139: /*   } */
                   1140: /*      u[p]='\0'; */
1.126     brouard  1141: 
1.137     brouard  1142: /*    for(j=0; j<= lg; j++) { */
                   1143: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1144: /*   } */
                   1145: /* } */
1.126     brouard  1146: 
1.160     brouard  1147: #ifdef _WIN32
                   1148: char * strsep(char **pp, const char *delim)
                   1149: {
                   1150:   char *p, *q;
                   1151:          
                   1152:   if ((p = *pp) == NULL)
                   1153:     return 0;
                   1154:   if ((q = strpbrk (p, delim)) != NULL)
                   1155:   {
                   1156:     *pp = q + 1;
                   1157:     *q = '\0';
                   1158:   }
                   1159:   else
                   1160:     *pp = 0;
                   1161:   return p;
                   1162: }
                   1163: #endif
                   1164: 
1.126     brouard  1165: /********************** nrerror ********************/
                   1166: 
                   1167: void nrerror(char error_text[])
                   1168: {
                   1169:   fprintf(stderr,"ERREUR ...\n");
                   1170:   fprintf(stderr,"%s\n",error_text);
                   1171:   exit(EXIT_FAILURE);
                   1172: }
                   1173: /*********************** vector *******************/
                   1174: double *vector(int nl, int nh)
                   1175: {
                   1176:   double *v;
                   1177:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1178:   if (!v) nrerror("allocation failure in vector");
                   1179:   return v-nl+NR_END;
                   1180: }
                   1181: 
                   1182: /************************ free vector ******************/
                   1183: void free_vector(double*v, int nl, int nh)
                   1184: {
                   1185:   free((FREE_ARG)(v+nl-NR_END));
                   1186: }
                   1187: 
                   1188: /************************ivector *******************************/
                   1189: int *ivector(long nl,long nh)
                   1190: {
                   1191:   int *v;
                   1192:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1193:   if (!v) nrerror("allocation failure in ivector");
                   1194:   return v-nl+NR_END;
                   1195: }
                   1196: 
                   1197: /******************free ivector **************************/
                   1198: void free_ivector(int *v, long nl, long nh)
                   1199: {
                   1200:   free((FREE_ARG)(v+nl-NR_END));
                   1201: }
                   1202: 
                   1203: /************************lvector *******************************/
                   1204: long *lvector(long nl,long nh)
                   1205: {
                   1206:   long *v;
                   1207:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1208:   if (!v) nrerror("allocation failure in ivector");
                   1209:   return v-nl+NR_END;
                   1210: }
                   1211: 
                   1212: /******************free lvector **************************/
                   1213: void free_lvector(long *v, long nl, long nh)
                   1214: {
                   1215:   free((FREE_ARG)(v+nl-NR_END));
                   1216: }
                   1217: 
                   1218: /******************* imatrix *******************************/
                   1219: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1220:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1221: { 
                   1222:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1223:   int **m; 
                   1224:   
                   1225:   /* allocate pointers to rows */ 
                   1226:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1227:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1228:   m += NR_END; 
                   1229:   m -= nrl; 
                   1230:   
                   1231:   
                   1232:   /* allocate rows and set pointers to them */ 
                   1233:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1234:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1235:   m[nrl] += NR_END; 
                   1236:   m[nrl] -= ncl; 
                   1237:   
                   1238:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1239:   
                   1240:   /* return pointer to array of pointers to rows */ 
                   1241:   return m; 
                   1242: } 
                   1243: 
                   1244: /****************** free_imatrix *************************/
                   1245: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1246:       int **m;
                   1247:       long nch,ncl,nrh,nrl; 
                   1248:      /* free an int matrix allocated by imatrix() */ 
                   1249: { 
                   1250:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1251:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1252: } 
                   1253: 
                   1254: /******************* matrix *******************************/
                   1255: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1256: {
                   1257:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1258:   double **m;
                   1259: 
                   1260:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1261:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1262:   m += NR_END;
                   1263:   m -= nrl;
                   1264: 
                   1265:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1266:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1267:   m[nrl] += NR_END;
                   1268:   m[nrl] -= ncl;
                   1269: 
                   1270:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1271:   return m;
1.145     brouard  1272:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1273: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1274: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1275:    */
                   1276: }
                   1277: 
                   1278: /*************************free matrix ************************/
                   1279: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1280: {
                   1281:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1282:   free((FREE_ARG)(m+nrl-NR_END));
                   1283: }
                   1284: 
                   1285: /******************* ma3x *******************************/
                   1286: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1287: {
                   1288:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1289:   double ***m;
                   1290: 
                   1291:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1292:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1293:   m += NR_END;
                   1294:   m -= nrl;
                   1295: 
                   1296:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1297:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1298:   m[nrl] += NR_END;
                   1299:   m[nrl] -= ncl;
                   1300: 
                   1301:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1302: 
                   1303:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1304:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1305:   m[nrl][ncl] += NR_END;
                   1306:   m[nrl][ncl] -= nll;
                   1307:   for (j=ncl+1; j<=nch; j++) 
                   1308:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1309:   
                   1310:   for (i=nrl+1; i<=nrh; i++) {
                   1311:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1312:     for (j=ncl+1; j<=nch; j++) 
                   1313:       m[i][j]=m[i][j-1]+nlay;
                   1314:   }
                   1315:   return m; 
                   1316:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1317:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1318:   */
                   1319: }
                   1320: 
                   1321: /*************************free ma3x ************************/
                   1322: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1323: {
                   1324:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1325:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1326:   free((FREE_ARG)(m+nrl-NR_END));
                   1327: }
                   1328: 
                   1329: /*************** function subdirf ***********/
                   1330: char *subdirf(char fileres[])
                   1331: {
                   1332:   /* Caution optionfilefiname is hidden */
                   1333:   strcpy(tmpout,optionfilefiname);
                   1334:   strcat(tmpout,"/"); /* Add to the right */
                   1335:   strcat(tmpout,fileres);
                   1336:   return tmpout;
                   1337: }
                   1338: 
                   1339: /*************** function subdirf2 ***********/
                   1340: char *subdirf2(char fileres[], char *preop)
                   1341: {
                   1342:   
                   1343:   /* Caution optionfilefiname is hidden */
                   1344:   strcpy(tmpout,optionfilefiname);
                   1345:   strcat(tmpout,"/");
                   1346:   strcat(tmpout,preop);
                   1347:   strcat(tmpout,fileres);
                   1348:   return tmpout;
                   1349: }
                   1350: 
                   1351: /*************** function subdirf3 ***********/
                   1352: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1353: {
                   1354:   
                   1355:   /* Caution optionfilefiname is hidden */
                   1356:   strcpy(tmpout,optionfilefiname);
                   1357:   strcat(tmpout,"/");
                   1358:   strcat(tmpout,preop);
                   1359:   strcat(tmpout,preop2);
                   1360:   strcat(tmpout,fileres);
                   1361:   return tmpout;
                   1362: }
                   1363: 
1.162     brouard  1364: char *asc_diff_time(long time_sec, char ascdiff[])
                   1365: {
                   1366:   long sec_left, days, hours, minutes;
                   1367:   days = (time_sec) / (60*60*24);
                   1368:   sec_left = (time_sec) % (60*60*24);
                   1369:   hours = (sec_left) / (60*60) ;
                   1370:   sec_left = (sec_left) %(60*60);
                   1371:   minutes = (sec_left) /60;
                   1372:   sec_left = (sec_left) % (60);
                   1373:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1374:   return ascdiff;
                   1375: }
                   1376: 
1.126     brouard  1377: /***************** f1dim *************************/
                   1378: extern int ncom; 
                   1379: extern double *pcom,*xicom;
                   1380: extern double (*nrfunc)(double []); 
                   1381:  
                   1382: double f1dim(double x) 
                   1383: { 
                   1384:   int j; 
                   1385:   double f;
                   1386:   double *xt; 
                   1387:  
                   1388:   xt=vector(1,ncom); 
                   1389:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1390:   f=(*nrfunc)(xt); 
                   1391:   free_vector(xt,1,ncom); 
                   1392:   return f; 
                   1393: } 
                   1394: 
                   1395: /*****************brent *************************/
                   1396: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1397: {
                   1398:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1399:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1400:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1401:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1402:    * returned function value. 
                   1403:   */
1.126     brouard  1404:   int iter; 
                   1405:   double a,b,d,etemp;
1.159     brouard  1406:   double fu=0,fv,fw,fx;
1.164     brouard  1407:   double ftemp=0.;
1.126     brouard  1408:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1409:   double e=0.0; 
                   1410:  
                   1411:   a=(ax < cx ? ax : cx); 
                   1412:   b=(ax > cx ? ax : cx); 
                   1413:   x=w=v=bx; 
                   1414:   fw=fv=fx=(*f)(x); 
                   1415:   for (iter=1;iter<=ITMAX;iter++) { 
                   1416:     xm=0.5*(a+b); 
                   1417:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1418:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1419:     printf(".");fflush(stdout);
                   1420:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1421: #ifdef DEBUGBRENT
1.126     brouard  1422:     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);
                   1423:     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);
                   1424:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1425: #endif
                   1426:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1427:       *xmin=x; 
                   1428:       return fx; 
                   1429:     } 
                   1430:     ftemp=fu;
                   1431:     if (fabs(e) > tol1) { 
                   1432:       r=(x-w)*(fx-fv); 
                   1433:       q=(x-v)*(fx-fw); 
                   1434:       p=(x-v)*q-(x-w)*r; 
                   1435:       q=2.0*(q-r); 
                   1436:       if (q > 0.0) p = -p; 
                   1437:       q=fabs(q); 
                   1438:       etemp=e; 
                   1439:       e=d; 
                   1440:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1441:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1442:       else { 
                   1443:        d=p/q; 
                   1444:        u=x+d; 
                   1445:        if (u-a < tol2 || b-u < tol2) 
                   1446:          d=SIGN(tol1,xm-x); 
                   1447:       } 
                   1448:     } else { 
                   1449:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1450:     } 
                   1451:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1452:     fu=(*f)(u); 
                   1453:     if (fu <= fx) { 
                   1454:       if (u >= x) a=x; else b=x; 
                   1455:       SHFT(v,w,x,u) 
1.183     brouard  1456:       SHFT(fv,fw,fx,fu) 
                   1457:     } else { 
                   1458:       if (u < x) a=u; else b=u; 
                   1459:       if (fu <= fw || w == x) { 
                   1460:        v=w; 
                   1461:        w=u; 
                   1462:        fv=fw; 
                   1463:        fw=fu; 
                   1464:       } else if (fu <= fv || v == x || v == w) { 
                   1465:        v=u; 
                   1466:        fv=fu; 
                   1467:       } 
                   1468:     } 
1.126     brouard  1469:   } 
                   1470:   nrerror("Too many iterations in brent"); 
                   1471:   *xmin=x; 
                   1472:   return fx; 
                   1473: } 
                   1474: 
                   1475: /****************** mnbrak ***********************/
                   1476: 
                   1477: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1478:            double (*func)(double)) 
1.183     brouard  1479: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1480: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1481: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1482: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1483:    */
1.126     brouard  1484:   double ulim,u,r,q, dum;
                   1485:   double fu; 
1.187     brouard  1486: 
                   1487:   double scale=10.;
                   1488:   int iterscale=0;
                   1489: 
                   1490:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1491:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1492: 
                   1493: 
                   1494:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1495:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1496:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1497:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1498:   /* } */
                   1499: 
1.126     brouard  1500:   if (*fb > *fa) { 
                   1501:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1502:     SHFT(dum,*fb,*fa,dum) 
                   1503:   } 
1.126     brouard  1504:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1505:   *fc=(*func)(*cx); 
1.183     brouard  1506: #ifdef DEBUG
                   1507:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1508:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1509: #endif
                   1510:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1511:     r=(*bx-*ax)*(*fb-*fc); 
                   1512:     q=(*bx-*cx)*(*fb-*fa); 
                   1513:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1514:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1515:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1516:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1517:       fu=(*func)(u); 
1.163     brouard  1518: #ifdef DEBUG
                   1519:       /* f(x)=A(x-u)**2+f(u) */
                   1520:       double A, fparabu; 
                   1521:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1522:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1523:       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);
                   1524:       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  1525:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1526:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1527:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1528:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1529: #endif 
1.184     brouard  1530: #ifdef MNBRAKORIGINAL
1.183     brouard  1531: #else
1.191     brouard  1532: /*       if (fu > *fc) { */
                   1533: /* #ifdef DEBUG */
                   1534: /*       printf("mnbrak4  fu > fc \n"); */
                   1535: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1536: /* #endif */
                   1537: /*     /\* 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 *\\/  *\/ */
                   1538: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1539: /*     dum=u; /\* Shifting c and u *\/ */
                   1540: /*     u = *cx; */
                   1541: /*     *cx = dum; */
                   1542: /*     dum = fu; */
                   1543: /*     fu = *fc; */
                   1544: /*     *fc =dum; */
                   1545: /*       } else { /\* end *\/ */
                   1546: /* #ifdef DEBUG */
                   1547: /*       printf("mnbrak3  fu < fc \n"); */
                   1548: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1549: /* #endif */
                   1550: /*     dum=u; /\* Shifting c and u *\/ */
                   1551: /*     u = *cx; */
                   1552: /*     *cx = dum; */
                   1553: /*     dum = fu; */
                   1554: /*     fu = *fc; */
                   1555: /*     *fc =dum; */
                   1556: /*       } */
1.183     brouard  1557: #ifdef DEBUG
1.191     brouard  1558:       printf("mnbrak34  fu < or >= fc \n");
                   1559:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1560: #endif
1.191     brouard  1561:       dum=u; /* Shifting c and u */
                   1562:       u = *cx;
                   1563:       *cx = dum;
                   1564:       dum = fu;
                   1565:       fu = *fc;
                   1566:       *fc =dum;
1.183     brouard  1567: #endif
1.162     brouard  1568:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1569: #ifdef DEBUG
                   1570:       printf("mnbrak2  u after c but before ulim\n");
                   1571:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1572: #endif
1.126     brouard  1573:       fu=(*func)(u); 
                   1574:       if (fu < *fc) { 
1.183     brouard  1575: #ifdef DEBUG
                   1576:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1577:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1578: #endif
1.126     brouard  1579:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1580:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1581:       } 
1.162     brouard  1582:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1583: #ifdef DEBUG
                   1584:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1585:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1586: #endif
1.126     brouard  1587:       u=ulim; 
                   1588:       fu=(*func)(u); 
1.183     brouard  1589:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1590: #ifdef DEBUG
                   1591:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1592:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1593: #endif
1.126     brouard  1594:       u=(*cx)+GOLD*(*cx-*bx); 
                   1595:       fu=(*func)(u); 
1.183     brouard  1596:     } /* end tests */
1.126     brouard  1597:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1598:     SHFT(*fa,*fb,*fc,fu) 
                   1599: #ifdef DEBUG
                   1600:       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);
                   1601:       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);
                   1602: #endif
                   1603:   } /* 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  1604: } 
                   1605: 
                   1606: /*************** linmin ************************/
1.162     brouard  1607: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1608: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1609: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1610: the value of func at the returned location p . This is actually all accomplished by calling the
                   1611: routines mnbrak and brent .*/
1.126     brouard  1612: int ncom; 
                   1613: double *pcom,*xicom;
                   1614: double (*nrfunc)(double []); 
                   1615:  
                   1616: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1617: { 
                   1618:   double brent(double ax, double bx, double cx, 
                   1619:               double (*f)(double), double tol, double *xmin); 
                   1620:   double f1dim(double x); 
                   1621:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1622:              double *fc, double (*func)(double)); 
                   1623:   int j; 
                   1624:   double xx,xmin,bx,ax; 
                   1625:   double fx,fb,fa;
1.187     brouard  1626: 
1.203     brouard  1627: #ifdef LINMINORIGINAL
                   1628: #else
                   1629:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1630: #endif
                   1631:   
1.126     brouard  1632:   ncom=n; 
                   1633:   pcom=vector(1,n); 
                   1634:   xicom=vector(1,n); 
                   1635:   nrfunc=func; 
                   1636:   for (j=1;j<=n;j++) { 
                   1637:     pcom[j]=p[j]; 
1.202     brouard  1638:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1639:   } 
1.187     brouard  1640: 
1.203     brouard  1641: #ifdef LINMINORIGINAL
                   1642:   xx=1.;
                   1643: #else
                   1644:   axs=0.0;
                   1645:   xxs=1.;
                   1646:   do{
                   1647:     xx= xxs;
                   1648: #endif
1.187     brouard  1649:     ax=0.;
                   1650:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1651:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1652:     /* 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))   */
                   1653:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1654:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1655:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1656:     /* 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  1657: #ifdef LINMINORIGINAL
                   1658: #else
                   1659:     if (fx != fx){
                   1660:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1661:        printf("|");
                   1662:        fprintf(ficlog,"|");
                   1663: #ifdef DEBUGLINMIN
                   1664:        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);
                   1665: #endif
                   1666:     }
                   1667:   }while(fx != fx);
                   1668: #endif
                   1669:   
1.191     brouard  1670: #ifdef DEBUGLINMIN
                   1671:   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  1672:   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  1673: #endif
1.187     brouard  1674:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1675:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1676:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1677:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1678:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1679: #ifdef DEBUG
                   1680:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1681:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1682: #endif
1.191     brouard  1683: #ifdef DEBUGLINMIN
                   1684:   printf("linmin end ");
1.202     brouard  1685:   fprintf(ficlog,"linmin end ");
1.191     brouard  1686: #endif
1.126     brouard  1687:   for (j=1;j<=n;j++) { 
1.203     brouard  1688: #ifdef LINMINORIGINAL
                   1689:     xi[j] *= xmin; 
                   1690: #else
                   1691: #ifdef DEBUGLINMIN
                   1692:     if(xxs <1.0)
                   1693:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1694: #endif
                   1695:     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) */
                   1696: #ifdef DEBUGLINMIN
                   1697:     if(xxs <1.0)
                   1698:       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 );
                   1699: #endif
                   1700: #endif
1.187     brouard  1701:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1702:   } 
1.191     brouard  1703: #ifdef DEBUGLINMIN
1.203     brouard  1704:   printf("\n");
1.191     brouard  1705:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1706:   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  1707:   for (j=1;j<=n;j++) { 
1.202     brouard  1708:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1709:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1710:     if(j % ncovmodel == 0){
1.191     brouard  1711:       printf("\n");
1.202     brouard  1712:       fprintf(ficlog,"\n");
                   1713:     }
1.191     brouard  1714:   }
1.203     brouard  1715: #else
1.191     brouard  1716: #endif
1.126     brouard  1717:   free_vector(xicom,1,n); 
                   1718:   free_vector(pcom,1,n); 
                   1719: } 
                   1720: 
                   1721: 
                   1722: /*************** powell ************************/
1.162     brouard  1723: /*
                   1724: Minimization of a function func of n variables. Input consists of an initial starting point
                   1725: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1726: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1727: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1728: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1729: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1730:  */
1.126     brouard  1731: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1732:            double (*func)(double [])) 
                   1733: { 
                   1734:   void linmin(double p[], double xi[], int n, double *fret, 
                   1735:              double (*func)(double [])); 
                   1736:   int i,ibig,j; 
                   1737:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1738:   double directest;
1.126     brouard  1739:   double fp,fptt;
                   1740:   double *xits;
                   1741:   int niterf, itmp;
                   1742: 
                   1743:   pt=vector(1,n); 
                   1744:   ptt=vector(1,n); 
                   1745:   xit=vector(1,n); 
                   1746:   xits=vector(1,n); 
                   1747:   *fret=(*func)(p); 
                   1748:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1749:   rcurr_time = time(NULL);  
1.126     brouard  1750:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1751:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1752:     ibig=0; 
                   1753:     del=0.0; 
1.157     brouard  1754:     rlast_time=rcurr_time;
                   1755:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1756:     rcurr_time = time(NULL);  
                   1757:     curr_time = *localtime(&rcurr_time);
                   1758:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1759:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1760: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1761:     for (i=1;i<=n;i++) {
1.126     brouard  1762:       printf(" %d %.12f",i, p[i]);
                   1763:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1764:       fprintf(ficrespow," %.12lf", p[i]);
                   1765:     }
                   1766:     printf("\n");
                   1767:     fprintf(ficlog,"\n");
                   1768:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1769:     if(*iter <=3){
1.157     brouard  1770:       tml = *localtime(&rcurr_time);
                   1771:       strcpy(strcurr,asctime(&tml));
                   1772:       rforecast_time=rcurr_time; 
1.126     brouard  1773:       itmp = strlen(strcurr);
                   1774:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1775:        strcurr[itmp-1]='\0';
1.162     brouard  1776:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1777:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1778:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1779:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1780:        forecast_time = *localtime(&rforecast_time);
                   1781:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1782:        itmp = strlen(strfor);
                   1783:        if(strfor[itmp-1]=='\n')
                   1784:        strfor[itmp-1]='\0';
1.157     brouard  1785:        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);
                   1786:        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  1787:       }
                   1788:     }
1.187     brouard  1789:     for (i=1;i<=n;i++) { /* For each direction i */
                   1790:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1791:       fptt=(*fret); 
                   1792: #ifdef DEBUG
1.203     brouard  1793:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1794:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1795: #endif
1.203     brouard  1796:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1797:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1798:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1799:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1800:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1801:        /* because that direction will be replaced unless the gain del is small */
                   1802:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1803:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1804:        /* with the new direction. */
1.126     brouard  1805:        del=fabs(fptt-(*fret)); 
                   1806:        ibig=i; 
                   1807:       } 
                   1808: #ifdef DEBUG
                   1809:       printf("%d %.12e",i,(*fret));
                   1810:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1811:       for (j=1;j<=n;j++) {
                   1812:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1813:        printf(" x(%d)=%.12e",j,xit[j]);
                   1814:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1815:       }
                   1816:       for(j=1;j<=n;j++) {
1.162     brouard  1817:        printf(" p(%d)=%.12e",j,p[j]);
                   1818:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1819:       }
                   1820:       printf("\n");
                   1821:       fprintf(ficlog,"\n");
                   1822: #endif
1.187     brouard  1823:     } /* end loop on each direction i */
                   1824:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1825:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1826:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1827:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1828:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1829:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1830:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1831:       /* decreased of more than 3.84  */
                   1832:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1833:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1834:       /* By adding 10 parameters more the gain should be 18.31 */
                   1835: 
                   1836:       /* Starting the program with initial values given by a former maximization will simply change */
                   1837:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1838:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1839:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1840: #ifdef DEBUG
                   1841:       int k[2],l;
                   1842:       k[0]=1;
                   1843:       k[1]=-1;
                   1844:       printf("Max: %.12e",(*func)(p));
                   1845:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1846:       for (j=1;j<=n;j++) {
                   1847:        printf(" %.12e",p[j]);
                   1848:        fprintf(ficlog," %.12e",p[j]);
                   1849:       }
                   1850:       printf("\n");
                   1851:       fprintf(ficlog,"\n");
                   1852:       for(l=0;l<=1;l++) {
                   1853:        for (j=1;j<=n;j++) {
                   1854:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1855:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1856:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1857:        }
                   1858:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1859:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1860:       }
                   1861: #endif
                   1862: 
                   1863: 
                   1864:       free_vector(xit,1,n); 
                   1865:       free_vector(xits,1,n); 
                   1866:       free_vector(ptt,1,n); 
                   1867:       free_vector(pt,1,n); 
                   1868:       return; 
1.192     brouard  1869:     } /* enough precision */ 
1.126     brouard  1870:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1871:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1872:       ptt[j]=2.0*p[j]-pt[j]; 
                   1873:       xit[j]=p[j]-pt[j]; 
                   1874:       pt[j]=p[j]; 
                   1875:     } 
1.181     brouard  1876:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1877: #ifdef POWELLF1F3
                   1878: #else
1.161     brouard  1879:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1880: #endif
1.162     brouard  1881:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1882:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1883:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1884:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1885:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1886:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1887:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1888: #ifdef NRCORIGINAL
                   1889:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1890: #else
                   1891:       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  1892:       t= t- del*SQR(fp-fptt);
1.183     brouard  1893: #endif
1.202     brouard  1894:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1895: #ifdef DEBUG
1.181     brouard  1896:       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);
                   1897:       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  1898:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1899:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1900:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1901:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1902:       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);
                   1903:       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);
                   1904: #endif
1.183     brouard  1905: #ifdef POWELLORIGINAL
                   1906:       if (t < 0.0) { /* Then we use it for new direction */
                   1907: #else
1.182     brouard  1908:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1909:        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  1910:         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  1911:         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  1912:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1913:       } 
1.181     brouard  1914:       if (directest < 0.0) { /* Then we use it for new direction */
                   1915: #endif
1.191     brouard  1916: #ifdef DEBUGLINMIN
                   1917:        printf("Before linmin in direction P%d-P0\n",n);
                   1918:        for (j=1;j<=n;j++) { 
1.202     brouard  1919:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1920:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1921:          if(j % ncovmodel == 0){
1.191     brouard  1922:            printf("\n");
1.202     brouard  1923:            fprintf(ficlog,"\n");
                   1924:          }
1.191     brouard  1925:        }
                   1926: #endif
1.187     brouard  1927:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1928: #ifdef DEBUGLINMIN
                   1929:        for (j=1;j<=n;j++) { 
                   1930:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1931:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1932:          if(j % ncovmodel == 0){
1.191     brouard  1933:            printf("\n");
1.202     brouard  1934:            fprintf(ficlog,"\n");
                   1935:          }
1.191     brouard  1936:        }
                   1937: #endif
1.126     brouard  1938:        for (j=1;j<=n;j++) { 
1.181     brouard  1939:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1940:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1941:        }
1.181     brouard  1942:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1943:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1944: 
1.126     brouard  1945: #ifdef DEBUG
1.164     brouard  1946:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1947:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1948:        for(j=1;j<=n;j++){
                   1949:          printf(" %.12e",xit[j]);
                   1950:          fprintf(ficlog," %.12e",xit[j]);
                   1951:        }
                   1952:        printf("\n");
                   1953:        fprintf(ficlog,"\n");
                   1954: #endif
1.192     brouard  1955:       } /* end of t or directest negative */
                   1956: #ifdef POWELLF1F3
                   1957: #else
1.162     brouard  1958:     } /* end if (fptt < fp)  */
1.192     brouard  1959: #endif
                   1960:   } /* loop iteration */ 
1.126     brouard  1961: } 
                   1962: 
                   1963: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1964: 
1.203     brouard  1965: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1966: {
                   1967:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  1968:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  1969:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   1970:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   1971:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   1972:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   1973:   /* Initial matrix pimij */
                   1974:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   1975:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   1976:   /*  0,                   0                  , 1} */
                   1977:   /*
                   1978:    * and after some iteration: */
                   1979:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   1980:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   1981:   /*  0,                   0                  , 1} */
                   1982:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   1983:   /* {0.51571254859325999, 0.4842874514067399, */
                   1984:   /*  0.51326036147820708, 0.48673963852179264} */
                   1985:   /* If we start from prlim again, prlim tends to a constant matrix */
                   1986: 
1.126     brouard  1987:   int i, ii,j,k;
                   1988:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1989:   /* double **matprod2(); */ /* test */
1.131     brouard  1990:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1991:   double **newm;
1.208   ! brouard  1992:   double agefin, delaymax=100. ; /* 100 Max number of years to converge */
1.203     brouard  1993:   int ncvloop=0;
1.169     brouard  1994:   
1.126     brouard  1995:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1996:     for (j=1;j<=nlstate+ndeath;j++){
                   1997:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1998:     }
1.169     brouard  1999:   
                   2000:   cov[1]=1.;
                   2001:   
                   2002:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2003:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2004:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2005:     ncvloop++;
1.126     brouard  2006:     newm=savm;
                   2007:     /* Covariates have to be included here again */
1.138     brouard  2008:     cov[2]=agefin;
1.187     brouard  2009:     if(nagesqr==1)
                   2010:       cov[3]= agefin*agefin;;
1.138     brouard  2011:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2012:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2013:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2014:       /* 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  2015:     }
1.186     brouard  2016:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2017:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2018:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2019:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2020:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2021:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2022:     
                   2023:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2024:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2025:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2026:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2027:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2028:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2029:     
1.126     brouard  2030:     savm=oldm;
                   2031:     oldm=newm;
                   2032:     maxmax=0.;
                   2033:     for(j=1;j<=nlstate;j++){
                   2034:       min=1.;
                   2035:       max=0.;
                   2036:       for(i=1; i<=nlstate; i++) {
                   2037:        sumnew=0;
                   2038:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2039:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2040:        max=FMAX(max,prlim[i][j]);
                   2041:        min=FMIN(min,prlim[i][j]);
1.208   ! brouard  2042:         /* 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  2043:       }
1.203     brouard  2044:       maxmin=(max-min)/(max+min)*2;
1.126     brouard  2045:       maxmax=FMAX(maxmax,maxmin);
1.208   ! brouard  2046:       /* for(i=1; i<=nlstate; i++) { */
        !          2047:       /*       sumnew=0.; */
        !          2048:       /*       sumnew+=prlim[i][j]; */
        !          2049:       /* } */
        !          2050:       /* prmimj = sumnew/(float)nlstate; /\* Means of various prevalence limits. */
1.169     brouard  2051:     } /* j loop */
1.203     brouard  2052:     *ncvyear= (int)age- (int)agefin;
1.208   ! brouard  2053:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2054:     if(maxmax < ftolpl){
1.203     brouard  2055:       /* 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  2056:       return prlim;
                   2057:     }
1.169     brouard  2058:   } /* age loop */
1.208   ! brouard  2059:     /* After some age loop it doesn't converge */
        !          2060:   printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g within %.0f years. \n\
        !          2061: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
        !          2062:   /* printf(" age= %d newm\n",(int)age); */
        !          2063:   /* for(i=1; i<=nlstate+ndeath; i++) { */
        !          2064:   /*   for(j=1;j<=nlstate+ndeath;j++){ */
        !          2065:   /*     printf(" %lf", newm[i][j]); */
        !          2066:   /*   } */
        !          2067:   /*   printf("\n"); */
        !          2068:   /* } */
        !          2069:   /* printf("\n"); */
        !          2070:   /* printf("prlim\n"); */
        !          2071:   /* for(i=1; i<=nlstate; i++) { */
        !          2072:   /*   sumnew=0; */
        !          2073:   /*   for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k]; */
        !          2074:   /*   for(j=1;j<=nlstate;j++){ */
        !          2075:   /*     prlim[i][j]= newm[i][j]/(1-sumnew); */
        !          2076:   /*     printf(" %lf", prlim[i][j]); */
        !          2077:   /*   } */
        !          2078:   /*   printf("\n"); */
        !          2079:   /* } */
        !          2080:   /* printf("\n"); */
        !          2081:   
        !          2082:   /* 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  2083:   return prlim; /* should not reach here */
1.126     brouard  2084: }
                   2085: 
                   2086: /*************** transition probabilities ***************/ 
                   2087: 
                   2088: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2089: {
1.138     brouard  2090:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2091:      computes the probability to be observed in state j being in state i by appying the
                   2092:      model to the ncovmodel covariates (including constant and age).
                   2093:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2094:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2095:      ncth covariate in the global vector x is given by the formula:
                   2096:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2097:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2098:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2099:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2100:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2101:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2102:   */
                   2103:   double s1, lnpijopii;
1.126     brouard  2104:   /*double t34;*/
1.164     brouard  2105:   int i,j, nc, ii, jj;
1.126     brouard  2106: 
                   2107:     for(i=1; i<= nlstate; i++){
                   2108:       for(j=1; j<i;j++){
1.138     brouard  2109:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2110:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2111:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2112: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2113:        }
1.138     brouard  2114:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2115: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2116:       }
                   2117:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2118:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2119:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2120:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2121: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2122:        }
1.138     brouard  2123:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2124:       }
                   2125:     }
                   2126:     
                   2127:     for(i=1; i<= nlstate; i++){
                   2128:       s1=0;
1.131     brouard  2129:       for(j=1; j<i; j++){
1.138     brouard  2130:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2131:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2132:       }
                   2133:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2134:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2135:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2136:       }
1.138     brouard  2137:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2138:       ps[i][i]=1./(s1+1.);
1.138     brouard  2139:       /* Computing other pijs */
1.126     brouard  2140:       for(j=1; j<i; j++)
                   2141:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2142:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2143:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2144:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2145:     } /* end i */
                   2146:     
                   2147:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2148:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2149:        ps[ii][jj]=0;
                   2150:        ps[ii][ii]=1;
                   2151:       }
                   2152:     }
                   2153:     
1.145     brouard  2154:     
                   2155:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2156:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2157:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2158:     /*   } */
                   2159:     /*   printf("\n "); */
                   2160:     /* } */
                   2161:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2162:     /*
1.126     brouard  2163:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2164:       goto end;*/
                   2165:     return ps;
                   2166: }
                   2167: 
                   2168: /**************** Product of 2 matrices ******************/
                   2169: 
1.145     brouard  2170: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2171: {
                   2172:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2173:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2174:   /* in, b, out are matrice of pointers which should have been initialized 
                   2175:      before: only the contents of out is modified. The function returns
                   2176:      a pointer to pointers identical to out */
1.145     brouard  2177:   int i, j, k;
1.126     brouard  2178:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2179:     for(k=ncolol; k<=ncoloh; k++){
                   2180:       out[i][k]=0.;
                   2181:       for(j=ncl; j<=nch; j++)
                   2182:        out[i][k] +=in[i][j]*b[j][k];
                   2183:     }
1.126     brouard  2184:   return out;
                   2185: }
                   2186: 
                   2187: 
                   2188: /************* Higher Matrix Product ***************/
                   2189: 
                   2190: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2191: {
                   2192:   /* Computes the transition matrix starting at age 'age' over 
                   2193:      'nhstepm*hstepm*stepm' months (i.e. until
                   2194:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2195:      nhstepm*hstepm matrices. 
                   2196:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2197:      (typically every 2 years instead of every month which is too big 
                   2198:      for the memory).
                   2199:      Model is determined by parameters x and covariates have to be 
                   2200:      included manually here. 
                   2201: 
                   2202:      */
                   2203: 
                   2204:   int i, j, d, h, k;
1.131     brouard  2205:   double **out, cov[NCOVMAX+1];
1.126     brouard  2206:   double **newm;
1.187     brouard  2207:   double agexact;
1.126     brouard  2208: 
                   2209:   /* Hstepm could be zero and should return the unit matrix */
                   2210:   for (i=1;i<=nlstate+ndeath;i++)
                   2211:     for (j=1;j<=nlstate+ndeath;j++){
                   2212:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2213:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2214:     }
                   2215:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2216:   for(h=1; h <=nhstepm; h++){
                   2217:     for(d=1; d <=hstepm; d++){
                   2218:       newm=savm;
                   2219:       /* Covariates have to be included here again */
                   2220:       cov[1]=1.;
1.187     brouard  2221:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2222:       cov[2]=agexact;
                   2223:       if(nagesqr==1)
                   2224:        cov[3]= agexact*agexact;
1.131     brouard  2225:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2226:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2227:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2228:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2229:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2230:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2231:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2232:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2233:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2234:        /* 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  2235: 
                   2236: 
                   2237:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2238:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2239:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2240:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2241:       savm=oldm;
                   2242:       oldm=newm;
                   2243:     }
                   2244:     for(i=1; i<=nlstate+ndeath; i++)
                   2245:       for(j=1;j<=nlstate+ndeath;j++) {
                   2246:        po[i][j][h]=newm[i][j];
1.128     brouard  2247:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2248:       }
1.128     brouard  2249:     /*printf("h=%d ",h);*/
1.126     brouard  2250:   } /* end h */
1.128     brouard  2251: /*     printf("\n H=%d \n",h); */
1.126     brouard  2252:   return po;
                   2253: }
                   2254: 
1.162     brouard  2255: #ifdef NLOPT
                   2256:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2257:   double fret;
                   2258:   double *xt;
                   2259:   int j;
                   2260:   myfunc_data *d2 = (myfunc_data *) pd;
                   2261: /* xt = (p1-1); */
                   2262:   xt=vector(1,n); 
                   2263:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2264: 
                   2265:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2266:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2267:   printf("Function = %.12lf ",fret);
                   2268:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2269:   printf("\n");
                   2270:  free_vector(xt,1,n);
                   2271:   return fret;
                   2272: }
                   2273: #endif
1.126     brouard  2274: 
                   2275: /*************** log-likelihood *************/
                   2276: double func( double *x)
                   2277: {
                   2278:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2279:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2280:   double **out;
                   2281:   double sw; /* Sum of weights */
                   2282:   double lli; /* Individual log likelihood */
                   2283:   int s1, s2;
                   2284:   double bbh, survp;
                   2285:   long ipmx;
1.187     brouard  2286:   double agexact;
1.126     brouard  2287:   /*extern weight */
                   2288:   /* We are differentiating ll according to initial status */
                   2289:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2290:   /*for(i=1;i<imx;i++) 
                   2291:     printf(" %d\n",s[4][i]);
                   2292:   */
1.162     brouard  2293: 
                   2294:   ++countcallfunc;
                   2295: 
1.126     brouard  2296:   cov[1]=1.;
                   2297: 
                   2298:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2299: 
                   2300:   if(mle==1){
                   2301:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2302:       /* Computes the values of the ncovmodel covariates of the model
                   2303:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2304:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2305:         to be observed in j being in i according to the model.
                   2306:        */
1.145     brouard  2307:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2308:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2309:       }
1.137     brouard  2310:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2311:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2312:         has been calculated etc */
1.126     brouard  2313:       for(mi=1; mi<= wav[i]-1; mi++){
                   2314:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2315:          for (j=1;j<=nlstate+ndeath;j++){
                   2316:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2317:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2318:          }
                   2319:        for(d=0; d<dh[mi][i]; d++){
                   2320:          newm=savm;
1.187     brouard  2321:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2322:          cov[2]=agexact;
                   2323:          if(nagesqr==1)
                   2324:            cov[3]= agexact*agexact;
1.126     brouard  2325:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2326:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2327:          }
                   2328:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2329:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2330:          savm=oldm;
                   2331:          oldm=newm;
                   2332:        } /* end mult */
                   2333:       
                   2334:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2335:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2336:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2337:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2338:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2339:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2340:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2341:         * probability in order to take into account the bias as a fraction of the way
                   2342:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2343:         * -stepm/2 to stepm/2 .
                   2344:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2345:         * For stepm > 1 the results are less biased than in previous versions. 
                   2346:         */
                   2347:        s1=s[mw[mi][i]][i];
                   2348:        s2=s[mw[mi+1][i]][i];
                   2349:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2350:        /* bias bh is positive if real duration
                   2351:         * is higher than the multiple of stepm and negative otherwise.
                   2352:         */
                   2353:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2354:        if( s2 > nlstate){ 
                   2355:          /* i.e. if s2 is a death state and if the date of death is known 
                   2356:             then the contribution to the likelihood is the probability to 
                   2357:             die between last step unit time and current  step unit time, 
                   2358:             which is also equal to probability to die before dh 
                   2359:             minus probability to die before dh-stepm . 
                   2360:             In version up to 0.92 likelihood was computed
                   2361:        as if date of death was unknown. Death was treated as any other
                   2362:        health state: the date of the interview describes the actual state
                   2363:        and not the date of a change in health state. The former idea was
                   2364:        to consider that at each interview the state was recorded
                   2365:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2366:        introduced the exact date of death then we should have modified
                   2367:        the contribution of an exact death to the likelihood. This new
                   2368:        contribution is smaller and very dependent of the step unit
                   2369:        stepm. It is no more the probability to die between last interview
                   2370:        and month of death but the probability to survive from last
                   2371:        interview up to one month before death multiplied by the
                   2372:        probability to die within a month. Thanks to Chris
                   2373:        Jackson for correcting this bug.  Former versions increased
                   2374:        mortality artificially. The bad side is that we add another loop
                   2375:        which slows down the processing. The difference can be up to 10%
                   2376:        lower mortality.
                   2377:          */
1.183     brouard  2378:        /* If, at the beginning of the maximization mostly, the
                   2379:           cumulative probability or probability to be dead is
                   2380:           constant (ie = 1) over time d, the difference is equal to
                   2381:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2382:           s1 at precedent wave, to be dead a month before current
                   2383:           wave is equal to probability, being at state s1 at
                   2384:           precedent wave, to be dead at mont of the current
                   2385:           wave. Then the observed probability (that this person died)
                   2386:           is null according to current estimated parameter. In fact,
                   2387:           it should be very low but not zero otherwise the log go to
                   2388:           infinity.
                   2389:        */
                   2390: /* #ifdef INFINITYORIGINAL */
                   2391: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2392: /* #else */
                   2393: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2394: /*         lli=log(mytinydouble); */
                   2395: /*       else */
                   2396: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2397: /* #endif */
                   2398:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2399: 
                   2400:        } else if  (s2==-2) {
                   2401:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2402:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2403:          /*survp += out[s1][j]; */
                   2404:          lli= log(survp);
                   2405:        }
                   2406:        
                   2407:        else if  (s2==-4) { 
                   2408:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2409:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2410:          lli= log(survp); 
                   2411:        } 
                   2412: 
                   2413:        else if  (s2==-5) { 
                   2414:          for (j=1,survp=0. ; j<=2; j++)  
                   2415:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2416:          lli= log(survp); 
                   2417:        } 
                   2418:        
                   2419:        else{
                   2420:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2421:          /*  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 */
                   2422:        } 
                   2423:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2424:        /*if(lli ==000.0)*/
                   2425:        /*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); */
                   2426:        ipmx +=1;
                   2427:        sw += weight[i];
                   2428:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2429:        /* if (lli < log(mytinydouble)){ */
                   2430:        /*   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); */
                   2431:        /*   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]); */
                   2432:        /* } */
1.126     brouard  2433:       } /* end of wave */
                   2434:     } /* end of individual */
                   2435:   }  else if(mle==2){
                   2436:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2437:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2438:       for(mi=1; mi<= wav[i]-1; mi++){
                   2439:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2440:          for (j=1;j<=nlstate+ndeath;j++){
                   2441:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2442:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2443:          }
                   2444:        for(d=0; d<=dh[mi][i]; d++){
                   2445:          newm=savm;
1.187     brouard  2446:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2447:          cov[2]=agexact;
                   2448:          if(nagesqr==1)
                   2449:            cov[3]= agexact*agexact;
1.126     brouard  2450:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2451:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2452:          }
                   2453:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2454:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2455:          savm=oldm;
                   2456:          oldm=newm;
                   2457:        } /* end mult */
                   2458:       
                   2459:        s1=s[mw[mi][i]][i];
                   2460:        s2=s[mw[mi+1][i]][i];
                   2461:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2462:        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 */
                   2463:        ipmx +=1;
                   2464:        sw += weight[i];
                   2465:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2466:       } /* end of wave */
                   2467:     } /* end of individual */
                   2468:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2469:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2470:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2471:       for(mi=1; mi<= wav[i]-1; mi++){
                   2472:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2473:          for (j=1;j<=nlstate+ndeath;j++){
                   2474:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2475:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2476:          }
                   2477:        for(d=0; d<dh[mi][i]; d++){
                   2478:          newm=savm;
1.187     brouard  2479:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2480:          cov[2]=agexact;
                   2481:          if(nagesqr==1)
                   2482:            cov[3]= agexact*agexact;
1.126     brouard  2483:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2484:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2485:          }
                   2486:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2487:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2488:          savm=oldm;
                   2489:          oldm=newm;
                   2490:        } /* end mult */
                   2491:       
                   2492:        s1=s[mw[mi][i]][i];
                   2493:        s2=s[mw[mi+1][i]][i];
                   2494:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2495:        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 */
                   2496:        ipmx +=1;
                   2497:        sw += weight[i];
                   2498:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2499:       } /* end of wave */
                   2500:     } /* end of individual */
                   2501:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2502:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2503:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2504:       for(mi=1; mi<= wav[i]-1; mi++){
                   2505:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2506:          for (j=1;j<=nlstate+ndeath;j++){
                   2507:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2508:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2509:          }
                   2510:        for(d=0; d<dh[mi][i]; d++){
                   2511:          newm=savm;
1.187     brouard  2512:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2513:          cov[2]=agexact;
                   2514:          if(nagesqr==1)
                   2515:            cov[3]= agexact*agexact;
1.126     brouard  2516:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2517:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2518:          }
                   2519:        
                   2520:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2521:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2522:          savm=oldm;
                   2523:          oldm=newm;
                   2524:        } /* end mult */
                   2525:       
                   2526:        s1=s[mw[mi][i]][i];
                   2527:        s2=s[mw[mi+1][i]][i];
                   2528:        if( s2 > nlstate){ 
                   2529:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2530:        }else{
                   2531:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2532:        }
                   2533:        ipmx +=1;
                   2534:        sw += weight[i];
                   2535:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2536: /*     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]); */
                   2537:       } /* end of wave */
                   2538:     } /* end of individual */
                   2539:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2540:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2541:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2542:       for(mi=1; mi<= wav[i]-1; mi++){
                   2543:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2544:          for (j=1;j<=nlstate+ndeath;j++){
                   2545:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2546:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2547:          }
                   2548:        for(d=0; d<dh[mi][i]; d++){
                   2549:          newm=savm;
1.187     brouard  2550:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2551:          cov[2]=agexact;
                   2552:          if(nagesqr==1)
                   2553:            cov[3]= agexact*agexact;
1.126     brouard  2554:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2555:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2556:          }
                   2557:        
                   2558:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2559:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2560:          savm=oldm;
                   2561:          oldm=newm;
                   2562:        } /* end mult */
                   2563:       
                   2564:        s1=s[mw[mi][i]][i];
                   2565:        s2=s[mw[mi+1][i]][i];
                   2566:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2567:        ipmx +=1;
                   2568:        sw += weight[i];
                   2569:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2570:        /*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]);*/
                   2571:       } /* end of wave */
                   2572:     } /* end of individual */
                   2573:   } /* End of if */
                   2574:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2575:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2576:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2577:   return -l;
                   2578: }
                   2579: 
                   2580: /*************** log-likelihood *************/
                   2581: double funcone( double *x)
                   2582: {
                   2583:   /* Same as likeli but slower because of a lot of printf and if */
                   2584:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2585:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2586:   double **out;
                   2587:   double lli; /* Individual log likelihood */
                   2588:   double llt;
                   2589:   int s1, s2;
                   2590:   double bbh, survp;
1.187     brouard  2591:   double agexact;
1.126     brouard  2592:   /*extern weight */
                   2593:   /* We are differentiating ll according to initial status */
                   2594:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2595:   /*for(i=1;i<imx;i++) 
                   2596:     printf(" %d\n",s[4][i]);
                   2597:   */
                   2598:   cov[1]=1.;
                   2599: 
                   2600:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2601: 
                   2602:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2603:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2604:     for(mi=1; mi<= wav[i]-1; mi++){
                   2605:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2606:        for (j=1;j<=nlstate+ndeath;j++){
                   2607:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2608:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2609:        }
                   2610:       for(d=0; d<dh[mi][i]; d++){
                   2611:        newm=savm;
1.187     brouard  2612:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2613:        cov[2]=agexact;
                   2614:        if(nagesqr==1)
                   2615:          cov[3]= agexact*agexact;
1.126     brouard  2616:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2617:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2618:        }
1.187     brouard  2619: 
1.145     brouard  2620:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2621:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2622:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2623:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2624:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2625:        savm=oldm;
                   2626:        oldm=newm;
                   2627:       } /* end mult */
                   2628:       
                   2629:       s1=s[mw[mi][i]][i];
                   2630:       s2=s[mw[mi+1][i]][i];
                   2631:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2632:       /* bias is positive if real duration
                   2633:        * is higher than the multiple of stepm and negative otherwise.
                   2634:        */
                   2635:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2636:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2637:       } else if  (s2==-2) {
                   2638:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2639:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2640:        lli= log(survp);
                   2641:       }else if (mle==1){
                   2642:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2643:       } else if(mle==2){
                   2644:        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 */
                   2645:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2646:        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 */
                   2647:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2648:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2649:       } else{  /* mle=0 back to 1 */
                   2650:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2651:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2652:       } /* End of if */
                   2653:       ipmx +=1;
                   2654:       sw += weight[i];
                   2655:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2656:       /*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  2657:       if(globpr){
1.205     brouard  2658:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2659:  %11.6f %11.6f %11.6f ", \
1.205     brouard  2660:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  2661:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2662:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2663:          llt +=ll[k]*gipmx/gsw;
                   2664:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2665:        }
                   2666:        fprintf(ficresilk," %10.6f\n", -llt);
                   2667:       }
                   2668:     } /* end of wave */
                   2669:   } /* end of individual */
                   2670:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2671:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2672:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2673:   if(globpr==0){ /* First time we count the contributions and weights */
                   2674:     gipmx=ipmx;
                   2675:     gsw=sw;
                   2676:   }
                   2677:   return -l;
                   2678: }
                   2679: 
                   2680: 
                   2681: /*************** function likelione ***********/
                   2682: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2683: {
                   2684:   /* This routine should help understanding what is done with 
                   2685:      the selection of individuals/waves and
                   2686:      to check the exact contribution to the likelihood.
                   2687:      Plotting could be done.
                   2688:    */
                   2689:   int k;
                   2690: 
                   2691:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2692:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2693:     strcat(fileresilk,fileresu);
1.126     brouard  2694:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2695:       printf("Problem with resultfile: %s\n", fileresilk);
                   2696:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2697:     }
1.205     brouard  2698:     fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
1.207     brouard  2699:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2700:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2701:     for(k=1; k<=nlstate; k++) 
                   2702:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2703:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2704:   }
                   2705: 
                   2706:   *fretone=(*funcone)(p);
                   2707:   if(*globpri !=0){
                   2708:     fclose(ficresilk);
1.205     brouard  2709:     if (mle ==0)
                   2710:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2711:     else if(mle >=1)
                   2712:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2713:     fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1.207     brouard  2714:     
1.208   ! brouard  2715:       
        !          2716:     for (k=1; k<= nlstate ; k++) {
        !          2717:       fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
        !          2718: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
        !          2719:     }
1.207     brouard  2720:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.204     brouard  2721: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2722:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2723: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2724:     fflush(fichtm);
1.205     brouard  2725:   }
1.126     brouard  2726:   return;
                   2727: }
                   2728: 
                   2729: 
                   2730: /*********** Maximum Likelihood Estimation ***************/
                   2731: 
                   2732: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2733: {
1.165     brouard  2734:   int i,j, iter=0;
1.126     brouard  2735:   double **xi;
                   2736:   double fret;
                   2737:   double fretone; /* Only one call to likelihood */
                   2738:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2739: 
                   2740: #ifdef NLOPT
                   2741:   int creturn;
                   2742:   nlopt_opt opt;
                   2743:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2744:   double *lb;
                   2745:   double minf; /* the minimum objective value, upon return */
                   2746:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2747:   myfunc_data dinst, *d = &dinst;
                   2748: #endif
                   2749: 
                   2750: 
1.126     brouard  2751:   xi=matrix(1,npar,1,npar);
                   2752:   for (i=1;i<=npar;i++)
                   2753:     for (j=1;j<=npar;j++)
                   2754:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2755:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2756:   strcpy(filerespow,"POW_"); 
1.126     brouard  2757:   strcat(filerespow,fileres);
                   2758:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2759:     printf("Problem with resultfile: %s\n", filerespow);
                   2760:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2761:   }
                   2762:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2763:   for (i=1;i<=nlstate;i++)
                   2764:     for(j=1;j<=nlstate+ndeath;j++)
                   2765:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2766:   fprintf(ficrespow,"\n");
1.162     brouard  2767: #ifdef POWELL
1.126     brouard  2768:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2769: #endif
1.126     brouard  2770: 
1.162     brouard  2771: #ifdef NLOPT
                   2772: #ifdef NEWUOA
                   2773:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2774: #else
                   2775:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2776: #endif
                   2777:   lb=vector(0,npar-1);
                   2778:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2779:   nlopt_set_lower_bounds(opt, lb);
                   2780:   nlopt_set_initial_step1(opt, 0.1);
                   2781:   
                   2782:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2783:   d->function = func;
                   2784:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2785:   nlopt_set_min_objective(opt, myfunc, d);
                   2786:   nlopt_set_xtol_rel(opt, ftol);
                   2787:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2788:     printf("nlopt failed! %d\n",creturn); 
                   2789:   }
                   2790:   else {
                   2791:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2792:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2793:     iter=1; /* not equal */
                   2794:   }
                   2795:   nlopt_destroy(opt);
                   2796: #endif
1.126     brouard  2797:   free_matrix(xi,1,npar,1,npar);
                   2798:   fclose(ficrespow);
1.203     brouard  2799:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2800:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2801:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2802: 
                   2803: }
                   2804: 
                   2805: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2806: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2807: {
                   2808:   double  **a,**y,*x,pd;
1.203     brouard  2809:   /* double **hess; */
1.164     brouard  2810:   int i, j;
1.126     brouard  2811:   int *indx;
                   2812: 
                   2813:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2814:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2815:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2816:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2817:   double gompertz(double p[]);
1.203     brouard  2818:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2819: 
                   2820:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2821:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2822:   for (i=1;i<=npar;i++){
1.203     brouard  2823:     printf("%d-",i);fflush(stdout);
                   2824:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2825:    
                   2826:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2827:     
                   2828:     /*  printf(" %f ",p[i]);
                   2829:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2830:   }
                   2831:   
                   2832:   for (i=1;i<=npar;i++) {
                   2833:     for (j=1;j<=npar;j++)  {
                   2834:       if (j>i) { 
1.203     brouard  2835:        printf(".%d-%d",i,j);fflush(stdout);
                   2836:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2837:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2838:        
                   2839:        hess[j][i]=hess[i][j];    
                   2840:        /*printf(" %lf ",hess[i][j]);*/
                   2841:       }
                   2842:     }
                   2843:   }
                   2844:   printf("\n");
                   2845:   fprintf(ficlog,"\n");
                   2846: 
                   2847:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2848:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2849:   
                   2850:   a=matrix(1,npar,1,npar);
                   2851:   y=matrix(1,npar,1,npar);
                   2852:   x=vector(1,npar);
                   2853:   indx=ivector(1,npar);
                   2854:   for (i=1;i<=npar;i++)
                   2855:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2856:   ludcmp(a,npar,indx,&pd);
                   2857: 
                   2858:   for (j=1;j<=npar;j++) {
                   2859:     for (i=1;i<=npar;i++) x[i]=0;
                   2860:     x[j]=1;
                   2861:     lubksb(a,npar,indx,x);
                   2862:     for (i=1;i<=npar;i++){ 
                   2863:       matcov[i][j]=x[i];
                   2864:     }
                   2865:   }
                   2866: 
                   2867:   printf("\n#Hessian matrix#\n");
                   2868:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2869:   for (i=1;i<=npar;i++) { 
                   2870:     for (j=1;j<=npar;j++) { 
1.203     brouard  2871:       printf("%.6e ",hess[i][j]);
                   2872:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2873:     }
                   2874:     printf("\n");
                   2875:     fprintf(ficlog,"\n");
                   2876:   }
                   2877: 
1.203     brouard  2878:   /* printf("\n#Covariance matrix#\n"); */
                   2879:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2880:   /* for (i=1;i<=npar;i++) {  */
                   2881:   /*   for (j=1;j<=npar;j++) {  */
                   2882:   /*     printf("%.6e ",matcov[i][j]); */
                   2883:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2884:   /*   } */
                   2885:   /*   printf("\n"); */
                   2886:   /*   fprintf(ficlog,"\n"); */
                   2887:   /* } */
                   2888: 
1.126     brouard  2889:   /* Recompute Inverse */
1.203     brouard  2890:   /* for (i=1;i<=npar;i++) */
                   2891:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2892:   /* ludcmp(a,npar,indx,&pd); */
                   2893: 
                   2894:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2895: 
                   2896:   /* for (j=1;j<=npar;j++) { */
                   2897:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2898:   /*   x[j]=1; */
                   2899:   /*   lubksb(a,npar,indx,x); */
                   2900:   /*   for (i=1;i<=npar;i++){  */
                   2901:   /*     y[i][j]=x[i]; */
                   2902:   /*     printf("%.3e ",y[i][j]); */
                   2903:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2904:   /*   } */
                   2905:   /*   printf("\n"); */
                   2906:   /*   fprintf(ficlog,"\n"); */
                   2907:   /* } */
                   2908: 
                   2909:   /* Verifying the inverse matrix */
                   2910: #ifdef DEBUGHESS
                   2911:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2912: 
1.203     brouard  2913:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2914:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2915: 
                   2916:   for (j=1;j<=npar;j++) {
                   2917:     for (i=1;i<=npar;i++){ 
1.203     brouard  2918:       printf("%.2f ",y[i][j]);
                   2919:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2920:     }
                   2921:     printf("\n");
                   2922:     fprintf(ficlog,"\n");
                   2923:   }
1.203     brouard  2924: #endif
1.126     brouard  2925: 
                   2926:   free_matrix(a,1,npar,1,npar);
                   2927:   free_matrix(y,1,npar,1,npar);
                   2928:   free_vector(x,1,npar);
                   2929:   free_ivector(indx,1,npar);
1.203     brouard  2930:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2931: 
                   2932: 
                   2933: }
                   2934: 
                   2935: /*************** hessian matrix ****************/
                   2936: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2937: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2938:   int i;
                   2939:   int l=1, lmax=20;
1.203     brouard  2940:   double k1,k2, res, fx;
1.132     brouard  2941:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2942:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2943:   int k=0,kmax=10;
                   2944:   double l1;
                   2945: 
                   2946:   fx=func(x);
                   2947:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2948:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2949:     l1=pow(10,l);
                   2950:     delts=delt;
                   2951:     for(k=1 ; k <kmax; k=k+1){
                   2952:       delt = delta*(l1*k);
                   2953:       p2[theta]=x[theta] +delt;
1.145     brouard  2954:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2955:       p2[theta]=x[theta]-delt;
                   2956:       k2=func(p2)-fx;
                   2957:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  2958:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2959:       
1.203     brouard  2960: #ifdef DEBUGHESSII
1.126     brouard  2961:       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);
                   2962:       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);
                   2963: #endif
                   2964:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2965:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2966:        k=kmax;
                   2967:       }
                   2968:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2969:        k=kmax; l=lmax*10;
1.126     brouard  2970:       }
                   2971:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2972:        delts=delt;
                   2973:       }
1.203     brouard  2974:     } /* End loop k */
1.126     brouard  2975:   }
                   2976:   delti[theta]=delts;
                   2977:   return res; 
                   2978:   
                   2979: }
                   2980: 
1.203     brouard  2981: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2982: {
                   2983:   int i;
1.164     brouard  2984:   int l=1, lmax=20;
1.126     brouard  2985:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2986:   double p2[MAXPARM+1];
1.203     brouard  2987:   int k, kmax=1;
                   2988:   double v1, v2, cv12, lc1, lc2;
1.208   ! brouard  2989: 
        !          2990:   int firstime=0;
1.203     brouard  2991:   
1.126     brouard  2992:   fx=func(x);
1.203     brouard  2993:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  2994:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  2995:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2996:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2997:     k1=func(p2)-fx;
                   2998:   
1.203     brouard  2999:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3000:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3001:     k2=func(p2)-fx;
                   3002:   
1.203     brouard  3003:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3004:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3005:     k3=func(p2)-fx;
                   3006:   
1.203     brouard  3007:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3008:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3009:     k4=func(p2)-fx;
1.203     brouard  3010:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3011:     if(k1*k2*k3*k4 <0.){
1.208   ! brouard  3012:       firstime=1;
1.203     brouard  3013:       kmax=kmax+10;
1.208   ! brouard  3014:     }
        !          3015:     if(kmax >=10 || firstime ==1){
1.203     brouard  3016:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3017:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3018:       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);
                   3019:       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);
                   3020:     }
                   3021: #ifdef DEBUGHESSIJ
                   3022:     v1=hess[thetai][thetai];
                   3023:     v2=hess[thetaj][thetaj];
                   3024:     cv12=res;
                   3025:     /* Computing eigen value of Hessian matrix */
                   3026:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3027:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3028:     if ((lc2 <0) || (lc1 <0) ){
                   3029:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3030:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3031:       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);
                   3032:       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);
                   3033:     }
1.126     brouard  3034: #endif
                   3035:   }
                   3036:   return res;
                   3037: }
                   3038: 
1.203     brouard  3039:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3040: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3041: /* { */
                   3042: /*   int i; */
                   3043: /*   int l=1, lmax=20; */
                   3044: /*   double k1,k2,k3,k4,res,fx; */
                   3045: /*   double p2[MAXPARM+1]; */
                   3046: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3047: /*   int k=0,kmax=10; */
                   3048: /*   double l1; */
                   3049:   
                   3050: /*   fx=func(x); */
                   3051: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3052: /*     l1=pow(10,l); */
                   3053: /*     delts=delt; */
                   3054: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3055: /*       delt = delti*(l1*k); */
                   3056: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3057: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3058: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3059: /*       k1=func(p2)-fx; */
                   3060:       
                   3061: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3062: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3063: /*       k2=func(p2)-fx; */
                   3064:       
                   3065: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3066: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3067: /*       k3=func(p2)-fx; */
                   3068:       
                   3069: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3070: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3071: /*       k4=func(p2)-fx; */
                   3072: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3073: /* #ifdef DEBUGHESSIJ */
                   3074: /*       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); */
                   3075: /*       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); */
                   3076: /* #endif */
                   3077: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3078: /*     k=kmax; */
                   3079: /*       } */
                   3080: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3081: /*     k=kmax; l=lmax*10; */
                   3082: /*       } */
                   3083: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3084: /*     delts=delt; */
                   3085: /*       } */
                   3086: /*     } /\* End loop k *\/ */
                   3087: /*   } */
                   3088: /*   delti[theta]=delts; */
                   3089: /*   return res;  */
                   3090: /* } */
                   3091: 
                   3092: 
1.126     brouard  3093: /************** Inverse of matrix **************/
                   3094: void ludcmp(double **a, int n, int *indx, double *d) 
                   3095: { 
                   3096:   int i,imax,j,k; 
                   3097:   double big,dum,sum,temp; 
                   3098:   double *vv; 
                   3099:  
                   3100:   vv=vector(1,n); 
                   3101:   *d=1.0; 
                   3102:   for (i=1;i<=n;i++) { 
                   3103:     big=0.0; 
                   3104:     for (j=1;j<=n;j++) 
                   3105:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3106:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3107:     vv[i]=1.0/big; 
                   3108:   } 
                   3109:   for (j=1;j<=n;j++) { 
                   3110:     for (i=1;i<j;i++) { 
                   3111:       sum=a[i][j]; 
                   3112:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3113:       a[i][j]=sum; 
                   3114:     } 
                   3115:     big=0.0; 
                   3116:     for (i=j;i<=n;i++) { 
                   3117:       sum=a[i][j]; 
                   3118:       for (k=1;k<j;k++) 
                   3119:        sum -= a[i][k]*a[k][j]; 
                   3120:       a[i][j]=sum; 
                   3121:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3122:        big=dum; 
                   3123:        imax=i; 
                   3124:       } 
                   3125:     } 
                   3126:     if (j != imax) { 
                   3127:       for (k=1;k<=n;k++) { 
                   3128:        dum=a[imax][k]; 
                   3129:        a[imax][k]=a[j][k]; 
                   3130:        a[j][k]=dum; 
                   3131:       } 
                   3132:       *d = -(*d); 
                   3133:       vv[imax]=vv[j]; 
                   3134:     } 
                   3135:     indx[j]=imax; 
                   3136:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3137:     if (j != n) { 
                   3138:       dum=1.0/(a[j][j]); 
                   3139:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3140:     } 
                   3141:   } 
                   3142:   free_vector(vv,1,n);  /* Doesn't work */
                   3143: ;
                   3144: } 
                   3145: 
                   3146: void lubksb(double **a, int n, int *indx, double b[]) 
                   3147: { 
                   3148:   int i,ii=0,ip,j; 
                   3149:   double sum; 
                   3150:  
                   3151:   for (i=1;i<=n;i++) { 
                   3152:     ip=indx[i]; 
                   3153:     sum=b[ip]; 
                   3154:     b[ip]=b[i]; 
                   3155:     if (ii) 
                   3156:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3157:     else if (sum) ii=i; 
                   3158:     b[i]=sum; 
                   3159:   } 
                   3160:   for (i=n;i>=1;i--) { 
                   3161:     sum=b[i]; 
                   3162:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3163:     b[i]=sum/a[i][i]; 
                   3164:   } 
                   3165: } 
                   3166: 
                   3167: void pstamp(FILE *fichier)
                   3168: {
1.196     brouard  3169:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3170: }
                   3171: 
                   3172: /************ Frequencies ********************/
                   3173: 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[])
                   3174: {  /* Some frequencies */
                   3175:   
1.164     brouard  3176:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3177:   int first;
                   3178:   double ***freq; /* Frequencies */
                   3179:   double *pp, **prop;
                   3180:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3181:   char fileresp[FILENAMELENGTH];
                   3182:   
                   3183:   pp=vector(1,nlstate);
                   3184:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3185:   strcpy(fileresp,"P_");
                   3186:   strcat(fileresp,fileresu);
1.126     brouard  3187:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3188:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3189:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3190:     exit(0);
                   3191:   }
                   3192:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3193:   j1=0;
                   3194:   
                   3195:   j=cptcoveff;
                   3196:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3197: 
                   3198:   first=1;
                   3199: 
1.169     brouard  3200:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3201:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3202:   /*    j1++; */
1.145     brouard  3203:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3204:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3205:        scanf("%d", i);*/
                   3206:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3207:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3208:          for(m=iagemin; m <= iagemax+3; m++)
                   3209:            freq[i][jk][m]=0;
1.143     brouard  3210:       
                   3211:       for (i=1; i<=nlstate; i++)  
                   3212:        for(m=iagemin; m <= iagemax+3; m++)
                   3213:          prop[i][m]=0;
1.126     brouard  3214:       
                   3215:       dateintsum=0;
                   3216:       k2cpt=0;
                   3217:       for (i=1; i<=imx; i++) {
                   3218:        bool=1;
1.144     brouard  3219:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3220:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3221:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3222:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3223:               bool=0;
1.198     brouard  3224:               /* 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", 
                   3225:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3226:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3227:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3228:             } 
1.126     brouard  3229:        }
1.144     brouard  3230:  
1.126     brouard  3231:        if (bool==1){
                   3232:          for(m=firstpass; m<=lastpass; m++){
                   3233:            k2=anint[m][i]+(mint[m][i]/12.);
                   3234:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3235:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3236:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3237:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3238:              if (m<lastpass) {
                   3239:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3240:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3241:              }
                   3242:              
                   3243:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3244:                dateintsum=dateintsum+k2;
                   3245:                k2cpt++;
                   3246:              }
                   3247:              /*}*/
                   3248:          }
                   3249:        }
1.145     brouard  3250:       } /* end i */
1.126     brouard  3251:        
                   3252:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3253:       pstamp(ficresp);
                   3254:       if  (cptcovn>0) {
                   3255:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3256:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3257:        fprintf(ficresp, "**********\n#");
1.143     brouard  3258:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3259:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3260:        fprintf(ficlog, "**********\n#");
1.126     brouard  3261:       }
                   3262:       for(i=1; i<=nlstate;i++) 
                   3263:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3264:       fprintf(ficresp, "\n");
                   3265:       
                   3266:       for(i=iagemin; i <= iagemax+3; i++){
                   3267:        if(i==iagemax+3){
                   3268:          fprintf(ficlog,"Total");
                   3269:        }else{
                   3270:          if(first==1){
                   3271:            first=0;
                   3272:            printf("See log file for details...\n");
                   3273:          }
                   3274:          fprintf(ficlog,"Age %d", i);
                   3275:        }
                   3276:        for(jk=1; jk <=nlstate ; jk++){
                   3277:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3278:            pp[jk] += freq[jk][m][i]; 
                   3279:        }
                   3280:        for(jk=1; jk <=nlstate ; jk++){
                   3281:          for(m=-1, pos=0; m <=0 ; m++)
                   3282:            pos += freq[jk][m][i];
                   3283:          if(pp[jk]>=1.e-10){
                   3284:            if(first==1){
1.132     brouard  3285:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3286:            }
                   3287:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3288:          }else{
                   3289:            if(first==1)
                   3290:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3291:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3292:          }
                   3293:        }
                   3294: 
                   3295:        for(jk=1; jk <=nlstate ; jk++){
                   3296:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3297:            pp[jk] += freq[jk][m][i];
                   3298:        }       
                   3299:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3300:          pos += pp[jk];
                   3301:          posprop += prop[jk][i];
                   3302:        }
                   3303:        for(jk=1; jk <=nlstate ; jk++){
                   3304:          if(pos>=1.e-5){
                   3305:            if(first==1)
                   3306:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3307:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3308:          }else{
                   3309:            if(first==1)
                   3310:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3311:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3312:          }
                   3313:          if( i <= iagemax){
                   3314:            if(pos>=1.e-5){
                   3315:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3316:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3317:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3318:            }
                   3319:            else
                   3320:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3321:          }
                   3322:        }
                   3323:        
                   3324:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3325:          for(m=-1; m <=nlstate+ndeath; m++)
                   3326:            if(freq[jk][m][i] !=0 ) {
                   3327:            if(first==1)
                   3328:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3329:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3330:            }
                   3331:        if(i <= iagemax)
                   3332:          fprintf(ficresp,"\n");
                   3333:        if(first==1)
                   3334:          printf("Others in log...\n");
                   3335:        fprintf(ficlog,"\n");
                   3336:       }
1.145     brouard  3337:       /*}*/
1.126     brouard  3338:   }
                   3339:   dateintmean=dateintsum/k2cpt; 
                   3340:  
                   3341:   fclose(ficresp);
                   3342:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3343:   free_vector(pp,1,nlstate);
                   3344:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3345:   /* End of Freq */
                   3346: }
                   3347: 
                   3348: /************ Prevalence ********************/
                   3349: 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)
                   3350: {  
                   3351:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3352:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3353:      We still use firstpass and lastpass as another selection.
                   3354:   */
                   3355:  
1.164     brouard  3356:   int i, m, jk, j1, bool, z1,j;
                   3357: 
                   3358:   double **prop;
                   3359:   double posprop; 
1.126     brouard  3360:   double  y2; /* in fractional years */
                   3361:   int iagemin, iagemax;
1.145     brouard  3362:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3363: 
                   3364:   iagemin= (int) agemin;
                   3365:   iagemax= (int) agemax;
                   3366:   /*pp=vector(1,nlstate);*/
                   3367:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3368:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3369:   j1=0;
                   3370:   
1.145     brouard  3371:   /*j=cptcoveff;*/
1.126     brouard  3372:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3373:   
1.145     brouard  3374:   first=1;
                   3375:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3376:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3377:       j1++;*/
1.126     brouard  3378:       
                   3379:       for (i=1; i<=nlstate; i++)  
                   3380:        for(m=iagemin; m <= iagemax+3; m++)
                   3381:          prop[i][m]=0.0;
                   3382:      
                   3383:       for (i=1; i<=imx; i++) { /* Each individual */
                   3384:        bool=1;
                   3385:        if  (cptcovn>0) {
                   3386:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3387:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3388:              bool=0;
                   3389:        } 
                   3390:        if (bool==1) { 
                   3391:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3392:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3393:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3394:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3395:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3396:              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); 
                   3397:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3398:                /*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]]);*/
                   3399:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3400:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3401:              } 
                   3402:            }
                   3403:          } /* end selection of waves */
                   3404:        }
                   3405:       }
                   3406:       for(i=iagemin; i <= iagemax+3; i++){  
                   3407:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3408:          posprop += prop[jk][i]; 
                   3409:        } 
1.145     brouard  3410:        
1.126     brouard  3411:        for(jk=1; jk <=nlstate ; jk++){     
                   3412:          if( i <=  iagemax){ 
                   3413:            if(posprop>=1.e-5){ 
                   3414:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3415:            } else{
                   3416:              if(first==1){
                   3417:                first=0;
                   3418:                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]);
                   3419:              }
                   3420:            }
1.126     brouard  3421:          } 
                   3422:        }/* end jk */ 
                   3423:       }/* end i */ 
1.145     brouard  3424:     /*} *//* end i1 */
                   3425:   } /* end j1 */
1.126     brouard  3426:   
                   3427:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3428:   /*free_vector(pp,1,nlstate);*/
                   3429:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3430: }  /* End of prevalence */
                   3431: 
                   3432: /************* Waves Concatenation ***************/
                   3433: 
                   3434: 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)
                   3435: {
                   3436:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3437:      Death is a valid wave (if date is known).
                   3438:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3439:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3440:      and mw[mi+1][i]. dh depends on stepm.
                   3441:      */
                   3442: 
                   3443:   int i, mi, m;
                   3444:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3445:      double sum=0., jmean=0.;*/
                   3446:   int first;
                   3447:   int j, k=0,jk, ju, jl;
                   3448:   double sum=0.;
                   3449:   first=0;
1.164     brouard  3450:   jmin=100000;
1.126     brouard  3451:   jmax=-1;
                   3452:   jmean=0.;
                   3453:   for(i=1; i<=imx; i++){
                   3454:     mi=0;
                   3455:     m=firstpass;
                   3456:     while(s[m][i] <= nlstate){
                   3457:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3458:        mw[++mi][i]=m;
                   3459:       if(m >=lastpass)
                   3460:        break;
                   3461:       else
                   3462:        m++;
                   3463:     }/* end while */
                   3464:     if (s[m][i] > nlstate){
                   3465:       mi++;    /* Death is another wave */
                   3466:       /* if(mi==0)  never been interviewed correctly before death */
                   3467:         /* Only death is a correct wave */
                   3468:       mw[mi][i]=m;
                   3469:     }
                   3470: 
                   3471:     wav[i]=mi;
                   3472:     if(mi==0){
                   3473:       nbwarn++;
                   3474:       if(first==0){
                   3475:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3476:        first=1;
                   3477:       }
                   3478:       if(first==1){
                   3479:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3480:       }
                   3481:     } /* end mi==0 */
                   3482:   } /* End individuals */
                   3483: 
                   3484:   for(i=1; i<=imx; i++){
                   3485:     for(mi=1; mi<wav[i];mi++){
                   3486:       if (stepm <=0)
                   3487:        dh[mi][i]=1;
                   3488:       else{
                   3489:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3490:          if (agedc[i] < 2*AGESUP) {
                   3491:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3492:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3493:            else if(j<0){
                   3494:              nberr++;
                   3495:              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]);
                   3496:              j=1; /* Temporary Dangerous patch */
                   3497:              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);
                   3498:              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]);
                   3499:              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);
                   3500:            }
                   3501:            k=k+1;
                   3502:            if (j >= jmax){
                   3503:              jmax=j;
                   3504:              ijmax=i;
                   3505:            }
                   3506:            if (j <= jmin){
                   3507:              jmin=j;
                   3508:              ijmin=i;
                   3509:            }
                   3510:            sum=sum+j;
                   3511:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3512:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3513:          }
                   3514:        }
                   3515:        else{
                   3516:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3517: /*       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]); */
                   3518: 
                   3519:          k=k+1;
                   3520:          if (j >= jmax) {
                   3521:            jmax=j;
                   3522:            ijmax=i;
                   3523:          }
                   3524:          else if (j <= jmin){
                   3525:            jmin=j;
                   3526:            ijmin=i;
                   3527:          }
                   3528:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3529:          /*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]);*/
                   3530:          if(j<0){
                   3531:            nberr++;
                   3532:            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]);
                   3533:            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]);
                   3534:          }
                   3535:          sum=sum+j;
                   3536:        }
                   3537:        jk= j/stepm;
                   3538:        jl= j -jk*stepm;
                   3539:        ju= j -(jk+1)*stepm;
                   3540:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3541:          if(jl==0){
                   3542:            dh[mi][i]=jk;
                   3543:            bh[mi][i]=0;
                   3544:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3545:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3546:            dh[mi][i]=jk+1;
                   3547:            bh[mi][i]=ju;
                   3548:          }
                   3549:        }else{
                   3550:          if(jl <= -ju){
                   3551:            dh[mi][i]=jk;
                   3552:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3553:                                 * is higher than the multiple of stepm and negative otherwise.
                   3554:                                 */
                   3555:          }
                   3556:          else{
                   3557:            dh[mi][i]=jk+1;
                   3558:            bh[mi][i]=ju;
                   3559:          }
                   3560:          if(dh[mi][i]==0){
                   3561:            dh[mi][i]=1; /* At least one step */
                   3562:            bh[mi][i]=ju; /* At least one step */
                   3563:            /*  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);*/
                   3564:          }
                   3565:        } /* end if mle */
                   3566:       }
                   3567:     } /* end wave */
                   3568:   }
                   3569:   jmean=sum/k;
                   3570:   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  3571:   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  3572:  }
                   3573: 
                   3574: /*********** Tricode ****************************/
1.145     brouard  3575: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3576: {
1.144     brouard  3577:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3578:   /*     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  3579:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3580:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3581:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3582:   */
1.130     brouard  3583: 
1.145     brouard  3584:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3585:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3586:   int cptcode=0; /* Modality max of covariates j */
                   3587:   int modmincovj=0; /* Modality min of covariates j */
                   3588: 
                   3589: 
1.126     brouard  3590:   cptcoveff=0; 
                   3591:  
1.144     brouard  3592:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3593: 
1.145     brouard  3594:   /* Loop on covariates without age and products */
1.186     brouard  3595:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3596:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3597:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3598:                               modality of this covariate Vj*/ 
1.145     brouard  3599:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3600:                                    * If product of Vn*Vm, still boolean *:
                   3601:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3602:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3603:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3604:                                      modality of the nth covariate of individual i. */
1.145     brouard  3605:       if (ij > modmaxcovj)
                   3606:         modmaxcovj=ij; 
                   3607:       else if (ij < modmincovj) 
                   3608:        modmincovj=ij; 
                   3609:       if ((ij < -1) && (ij > NCOVMAX)){
                   3610:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3611:        exit(1);
                   3612:       }else
1.136     brouard  3613:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3614:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3615:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3616:       /* getting the maximum value of the modality of the covariate
                   3617:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3618:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3619:     } /* end for loop on individuals i */
1.145     brouard  3620:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3621:     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  3622:     cptcode=modmaxcovj;
1.137     brouard  3623:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3624:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3625:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3626:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3627:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3628:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3629:        if( k != -1){
                   3630:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3631:                             covariate for which somebody answered excluding 
                   3632:                             undefined. Usually 2: 0 and 1. */
                   3633:        }
                   3634:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3635:                             covariate for which somebody answered including 
                   3636:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3637:       }
                   3638:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3639:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3640:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3641: 
1.136     brouard  3642:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3643:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3644:        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  3645:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3646:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3647:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3648:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3649:        nbcode[Tvar[j]][ij]=k;
                   3650:        nbcode[Tvar[j]][1]=0;
                   3651:        nbcode[Tvar[j]][2]=1;
                   3652:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3653:        To be continued (not working yet).
1.145     brouard  3654:     */
1.197     brouard  3655:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3656:     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*/
                   3657:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3658:          break;
                   3659:        }
                   3660:        ij++;
1.197     brouard  3661:        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  3662:        cptcode = ij; /* New max modality for covar j */
                   3663:     } /* end of loop on modality i=-1 to 1 or more */
                   3664:       
                   3665:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3666:     /*         /\*recode from 0 *\/ */
                   3667:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3668:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3669:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3670:     /*         } */
                   3671:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3672:     /*         if (ij > ncodemax[j]) { */
                   3673:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3674:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3675:     /*           break; */
                   3676:     /*         } */
                   3677:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3678:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3679:   
1.145     brouard  3680:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3681:   
1.187     brouard  3682:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3683:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3684:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3685:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3686:  } 
1.126     brouard  3687: 
1.192     brouard  3688:  ij=0;
1.145     brouard  3689:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3690:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3691:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3692:      ij++;
1.145     brouard  3693:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3694:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3695:    }else{
                   3696:        /* Tvaraff[ij]=0; */
                   3697:    }
1.126     brouard  3698:  }
1.192     brouard  3699:  /* ij--; */
1.144     brouard  3700:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3701: 
1.126     brouard  3702: }
                   3703: 
1.145     brouard  3704: 
1.126     brouard  3705: /*********** Health Expectancies ****************/
                   3706: 
1.127     brouard  3707: 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  3708: 
                   3709: {
                   3710:   /* Health expectancies, no variances */
1.164     brouard  3711:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3712:   int nhstepma, nstepma; /* Decreasing with age */
                   3713:   double age, agelim, hf;
                   3714:   double ***p3mat;
                   3715:   double eip;
                   3716: 
                   3717:   pstamp(ficreseij);
                   3718:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3719:   fprintf(ficreseij,"# Age");
                   3720:   for(i=1; i<=nlstate;i++){
                   3721:     for(j=1; j<=nlstate;j++){
                   3722:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3723:     }
                   3724:     fprintf(ficreseij," e%1d. ",i);
                   3725:   }
                   3726:   fprintf(ficreseij,"\n");
                   3727: 
                   3728:   
                   3729:   if(estepm < stepm){
                   3730:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3731:   }
                   3732:   else  hstepm=estepm;   
                   3733:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3734:    * This is mainly to measure the difference between two models: for example
                   3735:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3736:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3737:    * progression in between and thus overestimating or underestimating according
                   3738:    * to the curvature of the survival function. If, for the same date, we 
                   3739:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3740:    * to compare the new estimate of Life expectancy with the same linear 
                   3741:    * hypothesis. A more precise result, taking into account a more precise
                   3742:    * curvature will be obtained if estepm is as small as stepm. */
                   3743: 
                   3744:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3745:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3746:      nhstepm is the number of hstepm from age to agelim 
                   3747:      nstepm is the number of stepm from age to agelin. 
                   3748:      Look at hpijx to understand the reason of that which relies in memory size
                   3749:      and note for a fixed period like estepm months */
                   3750:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3751:      survival function given by stepm (the optimization length). Unfortunately it
                   3752:      means that if the survival funtion is printed only each two years of age and if
                   3753:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3754:      results. So we changed our mind and took the option of the best precision.
                   3755:   */
                   3756:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3757: 
                   3758:   agelim=AGESUP;
                   3759:   /* If stepm=6 months */
                   3760:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3761:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3762:     
                   3763: /* nhstepm age range expressed in number of stepm */
                   3764:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3765:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3766:   /* if (stepm >= YEARM) hstepm=1;*/
                   3767:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3768:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3769: 
                   3770:   for (age=bage; age<=fage; age ++){ 
                   3771:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3772:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3773:     /* if (stepm >= YEARM) hstepm=1;*/
                   3774:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3775: 
                   3776:     /* If stepm=6 months */
                   3777:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3778:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3779:     
                   3780:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3781:     
                   3782:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3783:     
                   3784:     printf("%d|",(int)age);fflush(stdout);
                   3785:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3786:     
                   3787:     /* Computing expectancies */
                   3788:     for(i=1; i<=nlstate;i++)
                   3789:       for(j=1; j<=nlstate;j++)
                   3790:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3791:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3792:          
                   3793:          /* 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]);*/
                   3794: 
                   3795:        }
                   3796: 
                   3797:     fprintf(ficreseij,"%3.0f",age );
                   3798:     for(i=1; i<=nlstate;i++){
                   3799:       eip=0;
                   3800:       for(j=1; j<=nlstate;j++){
                   3801:        eip +=eij[i][j][(int)age];
                   3802:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3803:       }
                   3804:       fprintf(ficreseij,"%9.4f", eip );
                   3805:     }
                   3806:     fprintf(ficreseij,"\n");
                   3807:     
                   3808:   }
                   3809:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3810:   printf("\n");
                   3811:   fprintf(ficlog,"\n");
                   3812:   
                   3813: }
                   3814: 
1.127     brouard  3815: 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  3816: 
                   3817: {
                   3818:   /* Covariances of health expectancies eij and of total life expectancies according
                   3819:    to initial status i, ei. .
                   3820:   */
                   3821:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3822:   int nhstepma, nstepma; /* Decreasing with age */
                   3823:   double age, agelim, hf;
                   3824:   double ***p3matp, ***p3matm, ***varhe;
                   3825:   double **dnewm,**doldm;
                   3826:   double *xp, *xm;
                   3827:   double **gp, **gm;
                   3828:   double ***gradg, ***trgradg;
                   3829:   int theta;
                   3830: 
                   3831:   double eip, vip;
                   3832: 
                   3833:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3834:   xp=vector(1,npar);
                   3835:   xm=vector(1,npar);
                   3836:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3837:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3838:   
                   3839:   pstamp(ficresstdeij);
                   3840:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3841:   fprintf(ficresstdeij,"# Age");
                   3842:   for(i=1; i<=nlstate;i++){
                   3843:     for(j=1; j<=nlstate;j++)
                   3844:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3845:     fprintf(ficresstdeij," e%1d. ",i);
                   3846:   }
                   3847:   fprintf(ficresstdeij,"\n");
                   3848: 
                   3849:   pstamp(ficrescveij);
                   3850:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3851:   fprintf(ficrescveij,"# Age");
                   3852:   for(i=1; i<=nlstate;i++)
                   3853:     for(j=1; j<=nlstate;j++){
                   3854:       cptj= (j-1)*nlstate+i;
                   3855:       for(i2=1; i2<=nlstate;i2++)
                   3856:        for(j2=1; j2<=nlstate;j2++){
                   3857:          cptj2= (j2-1)*nlstate+i2;
                   3858:          if(cptj2 <= cptj)
                   3859:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3860:        }
                   3861:     }
                   3862:   fprintf(ficrescveij,"\n");
                   3863:   
                   3864:   if(estepm < stepm){
                   3865:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3866:   }
                   3867:   else  hstepm=estepm;   
                   3868:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3869:    * This is mainly to measure the difference between two models: for example
                   3870:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3871:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3872:    * progression in between and thus overestimating or underestimating according
                   3873:    * to the curvature of the survival function. If, for the same date, we 
                   3874:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3875:    * to compare the new estimate of Life expectancy with the same linear 
                   3876:    * hypothesis. A more precise result, taking into account a more precise
                   3877:    * curvature will be obtained if estepm is as small as stepm. */
                   3878: 
                   3879:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3880:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3881:      nhstepm is the number of hstepm from age to agelim 
                   3882:      nstepm is the number of stepm from age to agelin. 
                   3883:      Look at hpijx to understand the reason of that which relies in memory size
                   3884:      and note for a fixed period like estepm months */
                   3885:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3886:      survival function given by stepm (the optimization length). Unfortunately it
                   3887:      means that if the survival funtion is printed only each two years of age and if
                   3888:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3889:      results. So we changed our mind and took the option of the best precision.
                   3890:   */
                   3891:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3892: 
                   3893:   /* If stepm=6 months */
                   3894:   /* nhstepm age range expressed in number of stepm */
                   3895:   agelim=AGESUP;
                   3896:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3897:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3898:   /* if (stepm >= YEARM) hstepm=1;*/
                   3899:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3900:   
                   3901:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3902:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3903:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3904:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3905:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3906:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3907: 
                   3908:   for (age=bage; age<=fage; age ++){ 
                   3909:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3910:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3911:     /* if (stepm >= YEARM) hstepm=1;*/
                   3912:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3913: 
                   3914:     /* If stepm=6 months */
                   3915:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3916:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3917:     
                   3918:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3919: 
                   3920:     /* Computing  Variances of health expectancies */
                   3921:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3922:        decrease memory allocation */
                   3923:     for(theta=1; theta <=npar; theta++){
                   3924:       for(i=1; i<=npar; i++){ 
                   3925:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3926:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3927:       }
                   3928:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3929:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3930:   
                   3931:       for(j=1; j<= nlstate; j++){
                   3932:        for(i=1; i<=nlstate; i++){
                   3933:          for(h=0; h<=nhstepm-1; h++){
                   3934:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3935:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3936:          }
                   3937:        }
                   3938:       }
                   3939:      
                   3940:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3941:        for(h=0; h<=nhstepm-1; h++){
                   3942:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3943:        }
                   3944:     }/* End theta */
                   3945:     
                   3946:     
                   3947:     for(h=0; h<=nhstepm-1; h++)
                   3948:       for(j=1; j<=nlstate*nlstate;j++)
                   3949:        for(theta=1; theta <=npar; theta++)
                   3950:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3951:     
                   3952: 
                   3953:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3954:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3955:        varhe[ij][ji][(int)age] =0.;
                   3956: 
                   3957:      printf("%d|",(int)age);fflush(stdout);
                   3958:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3959:      for(h=0;h<=nhstepm-1;h++){
                   3960:       for(k=0;k<=nhstepm-1;k++){
                   3961:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3962:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3963:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3964:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3965:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3966:       }
                   3967:     }
                   3968: 
                   3969:     /* Computing expectancies */
                   3970:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3971:     for(i=1; i<=nlstate;i++)
                   3972:       for(j=1; j<=nlstate;j++)
                   3973:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3974:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3975:          
                   3976:          /* 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]);*/
                   3977: 
                   3978:        }
                   3979: 
                   3980:     fprintf(ficresstdeij,"%3.0f",age );
                   3981:     for(i=1; i<=nlstate;i++){
                   3982:       eip=0.;
                   3983:       vip=0.;
                   3984:       for(j=1; j<=nlstate;j++){
                   3985:        eip += eij[i][j][(int)age];
                   3986:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3987:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3988:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3989:       }
                   3990:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3991:     }
                   3992:     fprintf(ficresstdeij,"\n");
                   3993: 
                   3994:     fprintf(ficrescveij,"%3.0f",age );
                   3995:     for(i=1; i<=nlstate;i++)
                   3996:       for(j=1; j<=nlstate;j++){
                   3997:        cptj= (j-1)*nlstate+i;
                   3998:        for(i2=1; i2<=nlstate;i2++)
                   3999:          for(j2=1; j2<=nlstate;j2++){
                   4000:            cptj2= (j2-1)*nlstate+i2;
                   4001:            if(cptj2 <= cptj)
                   4002:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4003:          }
                   4004:       }
                   4005:     fprintf(ficrescveij,"\n");
                   4006:    
                   4007:   }
                   4008:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4009:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4010:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4011:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4012:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4013:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4014:   printf("\n");
                   4015:   fprintf(ficlog,"\n");
                   4016: 
                   4017:   free_vector(xm,1,npar);
                   4018:   free_vector(xp,1,npar);
                   4019:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4020:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4021:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4022: }
                   4023: 
                   4024: /************ Variance ******************/
1.203     brouard  4025:  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  4026: {
                   4027:   /* Variance of health expectancies */
                   4028:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4029:   /* double **newm;*/
1.169     brouard  4030:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4031:   
                   4032:   int movingaverage();
1.126     brouard  4033:   double **dnewm,**doldm;
                   4034:   double **dnewmp,**doldmp;
                   4035:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4036:   int k;
1.126     brouard  4037:   double *xp;
                   4038:   double **gp, **gm;  /* for var eij */
                   4039:   double ***gradg, ***trgradg; /*for var eij */
                   4040:   double **gradgp, **trgradgp; /* for var p point j */
                   4041:   double *gpp, *gmp; /* for var p point j */
                   4042:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4043:   double ***p3mat;
                   4044:   double age,agelim, hf;
                   4045:   double ***mobaverage;
                   4046:   int theta;
                   4047:   char digit[4];
                   4048:   char digitp[25];
                   4049: 
                   4050:   char fileresprobmorprev[FILENAMELENGTH];
                   4051: 
                   4052:   if(popbased==1){
                   4053:     if(mobilav!=0)
1.201     brouard  4054:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4055:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4056:   }
                   4057:   else 
1.201     brouard  4058:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4059: 
                   4060:   if (mobilav!=0) {
                   4061:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4062:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4063:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4064:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4065:     }
                   4066:   }
                   4067: 
1.201     brouard  4068:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4069:   sprintf(digit,"%-d",ij);
                   4070:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4071:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4072:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4073:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4074:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4075:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4076:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4077:   }
                   4078:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4079:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4080:   pstamp(ficresprobmorprev);
                   4081:   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);
                   4082:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4083:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4084:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4085:     for(i=1; i<=nlstate;i++)
                   4086:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4087:   }  
                   4088:   fprintf(ficresprobmorprev,"\n");
1.208   ! brouard  4089:   
1.126     brouard  4090:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4091:   fprintf(ficgp,"\nunset title \n");
                   4092: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4093:   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");
                   4094:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4095: /*   } */
                   4096:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4097:   pstamp(ficresvij);
                   4098:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4099:   if(popbased==1)
1.128     brouard  4100:     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  4101:   else
                   4102:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4103:   fprintf(ficresvij,"# Age");
                   4104:   for(i=1; i<=nlstate;i++)
                   4105:     for(j=1; j<=nlstate;j++)
                   4106:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4107:   fprintf(ficresvij,"\n");
                   4108: 
                   4109:   xp=vector(1,npar);
                   4110:   dnewm=matrix(1,nlstate,1,npar);
                   4111:   doldm=matrix(1,nlstate,1,nlstate);
                   4112:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4113:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4114: 
                   4115:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4116:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4117:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4118:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4119:   
                   4120:   if(estepm < stepm){
                   4121:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4122:   }
                   4123:   else  hstepm=estepm;   
                   4124:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4125:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4126:      nhstepm is the number of hstepm from age to agelim 
1.208   ! brouard  4127:      nstepm is the number of stepm from age to agelim. 
        !          4128:      Look at function hpijx to understand why (it is linked to memory size questions) 
        !          4129:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4130:      survival function given by stepm (the optimization length). Unfortunately it
                   4131:      means that if the survival funtion is printed every two years of age and if
                   4132:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4133:      results. So we changed our mind and took the option of the best precision.
                   4134:   */
                   4135:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4136:   agelim = AGESUP;
                   4137:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4138:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4139:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4140:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4141:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4142:     gp=matrix(0,nhstepm,1,nlstate);
                   4143:     gm=matrix(0,nhstepm,1,nlstate);
                   4144: 
                   4145: 
                   4146:     for(theta=1; theta <=npar; theta++){
                   4147:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4148:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4149:       }
                   4150:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4151:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4152: 
                   4153:       if (popbased==1) {
                   4154:        if(mobilav ==0){
                   4155:          for(i=1; i<=nlstate;i++)
                   4156:            prlim[i][i]=probs[(int)age][i][ij];
                   4157:        }else{ /* mobilav */ 
                   4158:          for(i=1; i<=nlstate;i++)
                   4159:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4160:        }
                   4161:       }
                   4162:   
                   4163:       for(j=1; j<= nlstate; j++){
                   4164:        for(h=0; h<=nhstepm; h++){
                   4165:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4166:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4167:        }
                   4168:       }
                   4169:       /* This for computing probability of death (h=1 means
                   4170:          computed over hstepm matrices product = hstepm*stepm months) 
                   4171:          as a weighted average of prlim.
                   4172:       */
                   4173:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4174:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4175:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4176:       }    
                   4177:       /* end probability of death */
                   4178: 
                   4179:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4180:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4181:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4182:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
1.126     brouard  4183:  
                   4184:       if (popbased==1) {
                   4185:        if(mobilav ==0){
                   4186:          for(i=1; i<=nlstate;i++)
                   4187:            prlim[i][i]=probs[(int)age][i][ij];
                   4188:        }else{ /* mobilav */ 
                   4189:          for(i=1; i<=nlstate;i++)
                   4190:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4191:        }
                   4192:       }
                   4193: 
1.128     brouard  4194:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4195:        for(h=0; h<=nhstepm; h++){
                   4196:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4197:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4198:        }
                   4199:       }
                   4200:       /* This for computing probability of death (h=1 means
                   4201:          computed over hstepm matrices product = hstepm*stepm months) 
                   4202:          as a weighted average of prlim.
                   4203:       */
                   4204:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4205:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4206:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4207:       }    
                   4208:       /* end probability of death */
                   4209: 
                   4210:       for(j=1; j<= nlstate; j++) /* vareij */
                   4211:        for(h=0; h<=nhstepm; h++){
                   4212:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4213:        }
                   4214: 
                   4215:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4216:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4217:       }
                   4218: 
                   4219:     } /* End theta */
                   4220: 
                   4221:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4222: 
                   4223:     for(h=0; h<=nhstepm; h++) /* veij */
                   4224:       for(j=1; j<=nlstate;j++)
                   4225:        for(theta=1; theta <=npar; theta++)
                   4226:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4227: 
                   4228:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4229:       for(theta=1; theta <=npar; theta++)
                   4230:        trgradgp[j][theta]=gradgp[theta][j];
                   4231:   
                   4232: 
                   4233:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4234:     for(i=1;i<=nlstate;i++)
                   4235:       for(j=1;j<=nlstate;j++)
                   4236:        vareij[i][j][(int)age] =0.;
                   4237: 
                   4238:     for(h=0;h<=nhstepm;h++){
                   4239:       for(k=0;k<=nhstepm;k++){
                   4240:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4241:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4242:        for(i=1;i<=nlstate;i++)
                   4243:          for(j=1;j<=nlstate;j++)
                   4244:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4245:       }
                   4246:     }
                   4247:   
                   4248:     /* pptj */
                   4249:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4250:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4251:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4252:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4253:        varppt[j][i]=doldmp[j][i];
                   4254:     /* end ppptj */
                   4255:     /*  x centered again */
                   4256:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4257:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4258:  
                   4259:     if (popbased==1) {
                   4260:       if(mobilav ==0){
                   4261:        for(i=1; i<=nlstate;i++)
                   4262:          prlim[i][i]=probs[(int)age][i][ij];
                   4263:       }else{ /* mobilav */ 
                   4264:        for(i=1; i<=nlstate;i++)
                   4265:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4266:       }
                   4267:     }
                   4268:              
                   4269:     /* This for computing probability of death (h=1 means
                   4270:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4271:        as a weighted average of prlim.
                   4272:     */
                   4273:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4274:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4275:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4276:     }    
                   4277:     /* end probability of death */
                   4278: 
                   4279:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4280:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4281:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4282:       for(i=1; i<=nlstate;i++){
                   4283:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4284:       }
                   4285:     } 
                   4286:     fprintf(ficresprobmorprev,"\n");
                   4287: 
                   4288:     fprintf(ficresvij,"%.0f ",age );
                   4289:     for(i=1; i<=nlstate;i++)
                   4290:       for(j=1; j<=nlstate;j++){
                   4291:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4292:       }
                   4293:     fprintf(ficresvij,"\n");
                   4294:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4295:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4296:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4297:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4298:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4299:   } /* End age */
                   4300:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4301:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4302:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4303:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4304:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4305:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4306:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4307:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4308:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4309: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4310: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4311: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4312:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4313:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4314:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4315:   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  4316:   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  4317:   /*  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  4318: */
1.199     brouard  4319: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4320:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4321: 
                   4322:   free_vector(xp,1,npar);
                   4323:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4324:   free_matrix(dnewm,1,nlstate,1,npar);
                   4325:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4326:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4327:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4328:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4329:   fclose(ficresprobmorprev);
                   4330:   fflush(ficgp);
                   4331:   fflush(fichtm); 
                   4332: }  /* end varevsij */
                   4333: 
                   4334: /************ Variance of prevlim ******************/
1.203     brouard  4335:  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  4336: {
1.205     brouard  4337:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4338:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4339: 
1.126     brouard  4340:   double **dnewm,**doldm;
                   4341:   int i, j, nhstepm, hstepm;
                   4342:   double *xp;
                   4343:   double *gp, *gm;
                   4344:   double **gradg, **trgradg;
1.208   ! brouard  4345:   double **mgm, **mgp;
1.126     brouard  4346:   double age,agelim;
                   4347:   int theta;
                   4348:   
                   4349:   pstamp(ficresvpl);
                   4350:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4351:   fprintf(ficresvpl,"# Age");
                   4352:   for(i=1; i<=nlstate;i++)
                   4353:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4354:   fprintf(ficresvpl,"\n");
                   4355: 
                   4356:   xp=vector(1,npar);
                   4357:   dnewm=matrix(1,nlstate,1,npar);
                   4358:   doldm=matrix(1,nlstate,1,nlstate);
                   4359:   
                   4360:   hstepm=1*YEARM; /* Every year of age */
                   4361:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4362:   agelim = AGESUP;
                   4363:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4364:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4365:     if (stepm >= YEARM) hstepm=1;
                   4366:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
1.208   ! brouard  4367:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
1.126     brouard  4368:     gradg=matrix(1,npar,1,nlstate);
1.208   ! brouard  4369:     mgp=matrix(1,npar,1,nlstate);
        !          4370:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4371:     gp=vector(1,nlstate);
                   4372:     gm=vector(1,nlstate);
                   4373: 
                   4374:     for(theta=1; theta <=npar; theta++){
                   4375:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4376:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4377:       }
1.208   ! brouard  4378:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Missing or not useful because 1 year */ 
1.203     brouard  4379:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.208   ! brouard  4380:       for(i=1;i<=nlstate;i++){
1.126     brouard  4381:        gp[i] = prlim[i][i];
1.208   ! brouard  4382:        mgp[theta][i] = prlim[i][i];
        !          4383:       }
1.126     brouard  4384:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4385:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.203     brouard  4386:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.208   ! brouard  4387:       for(i=1;i<=nlstate;i++){
1.126     brouard  4388:        gm[i] = prlim[i][i];
1.208   ! brouard  4389:        mgm[theta][i] = prlim[i][i];
        !          4390:       }
1.126     brouard  4391:       for(i=1;i<=nlstate;i++)
                   4392:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4393:     } /* End theta */
                   4394: 
                   4395:     trgradg =matrix(1,nlstate,1,npar);
                   4396: 
                   4397:     for(j=1; j<=nlstate;j++)
                   4398:       for(theta=1; theta <=npar; theta++)
                   4399:        trgradg[j][theta]=gradg[theta][j];
1.208   ! brouard  4400:     if((int)age==68 ||(int)age== 69 ){
        !          4401:       printf("\nmgm mgp %d ",(int)age);
        !          4402:       for(j=1; j<=nlstate;j++){
        !          4403:        printf("%d ",j);
        !          4404:        for(theta=1; theta <=npar; theta++)
        !          4405:          printf("%d %lf %lf",theta,mgm[theta][j],mgp[theta][j]);
        !          4406:        printf("\n ");
        !          4407:       }
        !          4408:     }
        !          4409:     if((int)age==68 ||(int)age== 69 ){
        !          4410:       printf("\n gradg %d ",(int)age);
        !          4411:       for(j=1; j<=nlstate;j++){
        !          4412:        printf("%d ",j);
        !          4413:        for(theta=1; theta <=npar; theta++)
        !          4414:          printf("%d %lf ",theta,gradg[theta][j]);
        !          4415:        printf("\n ");
        !          4416:       }
        !          4417:     }
1.126     brouard  4418: 
                   4419:     for(i=1;i<=nlstate;i++)
                   4420:       varpl[i][(int)age] =0.;
1.208   ! brouard  4421:     if((int)age==68 ||(int)age== 69 ){
1.205     brouard  4422:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4423:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4424:     }else{
1.126     brouard  4425:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4426:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4427:     }
1.126     brouard  4428:     for(i=1;i<=nlstate;i++)
                   4429:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4430: 
                   4431:     fprintf(ficresvpl,"%.0f ",age );
                   4432:     for(i=1; i<=nlstate;i++)
                   4433:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4434:     fprintf(ficresvpl,"\n");
                   4435:     free_vector(gp,1,nlstate);
                   4436:     free_vector(gm,1,nlstate);
1.208   ! brouard  4437:     free_matrix(mgm,1,npar,1,nlstate);
        !          4438:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4439:     free_matrix(gradg,1,npar,1,nlstate);
                   4440:     free_matrix(trgradg,1,nlstate,1,npar);
                   4441:   } /* End age */
                   4442: 
                   4443:   free_vector(xp,1,npar);
                   4444:   free_matrix(doldm,1,nlstate,1,npar);
                   4445:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4446: 
                   4447: }
                   4448: 
                   4449: /************ Variance of one-step probabilities  ******************/
                   4450: 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[])
                   4451: {
1.164     brouard  4452:   int i, j=0,  k1, l1, tj;
1.126     brouard  4453:   int k2, l2, j1,  z1;
1.164     brouard  4454:   int k=0, l;
1.145     brouard  4455:   int first=1, first1, first2;
1.126     brouard  4456:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4457:   double **dnewm,**doldm;
                   4458:   double *xp;
                   4459:   double *gp, *gm;
                   4460:   double **gradg, **trgradg;
                   4461:   double **mu;
1.164     brouard  4462:   double age, cov[NCOVMAX+1];
1.126     brouard  4463:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4464:   int theta;
                   4465:   char fileresprob[FILENAMELENGTH];
                   4466:   char fileresprobcov[FILENAMELENGTH];
                   4467:   char fileresprobcor[FILENAMELENGTH];
                   4468:   double ***varpij;
                   4469: 
1.201     brouard  4470:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4471:   strcat(fileresprob,fileres);
                   4472:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4473:     printf("Problem with resultfile: %s\n", fileresprob);
                   4474:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4475:   }
1.201     brouard  4476:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4477:   strcat(fileresprobcov,fileresu);
1.126     brouard  4478:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4479:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4480:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4481:   }
1.201     brouard  4482:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4483:   strcat(fileresprobcor,fileresu);
1.126     brouard  4484:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4485:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4486:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4487:   }
                   4488:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4489:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4490:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4491:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4492:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4493:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4494:   pstamp(ficresprob);
                   4495:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4496:   fprintf(ficresprob,"# Age");
                   4497:   pstamp(ficresprobcov);
                   4498:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4499:   fprintf(ficresprobcov,"# Age");
                   4500:   pstamp(ficresprobcor);
                   4501:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4502:   fprintf(ficresprobcor,"# Age");
                   4503: 
                   4504: 
                   4505:   for(i=1; i<=nlstate;i++)
                   4506:     for(j=1; j<=(nlstate+ndeath);j++){
                   4507:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4508:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4509:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4510:     }  
                   4511:  /* fprintf(ficresprob,"\n");
                   4512:   fprintf(ficresprobcov,"\n");
                   4513:   fprintf(ficresprobcor,"\n");
                   4514:  */
1.131     brouard  4515:   xp=vector(1,npar);
1.126     brouard  4516:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4517:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4518:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4519:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4520:   first=1;
                   4521:   fprintf(ficgp,"\n# Routine varprob");
                   4522:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4523:   fprintf(fichtm,"\n");
                   4524: 
1.200     brouard  4525:   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  4526:   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);
                   4527:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4528: and drawn. It helps understanding how is the covariance between two incidences.\
                   4529:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4530:   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. \
                   4531: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4532: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4533: standard deviations wide on each axis. <br>\
                   4534:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4535:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4536: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4537: 
                   4538:   cov[1]=1;
1.145     brouard  4539:   /* tj=cptcoveff; */
                   4540:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4541:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4542:   j1=0;
1.145     brouard  4543:   for(j1=1; j1<=tj;j1++){
                   4544:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4545:     /*j1++;*/
1.126     brouard  4546:       if  (cptcovn>0) {
                   4547:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4548:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4549:        fprintf(ficresprob, "**********\n#\n");
                   4550:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4551:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4552:        fprintf(ficresprobcov, "**********\n#\n");
                   4553:        
                   4554:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4555:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4556:        fprintf(ficgp, "**********\n#\n");
                   4557:        
                   4558:        
                   4559:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4560:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4561:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4562:        
                   4563:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4564:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4565:        fprintf(ficresprobcor, "**********\n#");    
                   4566:       }
                   4567:       
1.145     brouard  4568:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4569:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4570:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4571:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4572:       for (age=bage; age<=fage; age ++){ 
                   4573:        cov[2]=age;
1.187     brouard  4574:        if(nagesqr==1)
                   4575:          cov[3]= age*age;
1.126     brouard  4576:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4577:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4578:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4579:                                                         * 1  1 1 1 1
                   4580:                                                         * 2  2 1 1 1
                   4581:                                                         * 3  1 2 1 1
                   4582:                                                         */
                   4583:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4584:        }
1.186     brouard  4585:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4586:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4587:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4588:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4589:        
                   4590:     
                   4591:        for(theta=1; theta <=npar; theta++){
                   4592:          for(i=1; i<=npar; i++)
                   4593:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4594:          
                   4595:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4596:          
                   4597:          k=0;
                   4598:          for(i=1; i<= (nlstate); i++){
                   4599:            for(j=1; j<=(nlstate+ndeath);j++){
                   4600:              k=k+1;
                   4601:              gp[k]=pmmij[i][j];
                   4602:            }
                   4603:          }
                   4604:          
                   4605:          for(i=1; i<=npar; i++)
                   4606:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4607:     
                   4608:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4609:          k=0;
                   4610:          for(i=1; i<=(nlstate); i++){
                   4611:            for(j=1; j<=(nlstate+ndeath);j++){
                   4612:              k=k+1;
                   4613:              gm[k]=pmmij[i][j];
                   4614:            }
                   4615:          }
                   4616:      
                   4617:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4618:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4619:        }
                   4620: 
                   4621:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4622:          for(theta=1; theta <=npar; theta++)
                   4623:            trgradg[j][theta]=gradg[theta][j];
                   4624:        
                   4625:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4626:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4627: 
                   4628:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4629:        
                   4630:        k=0;
                   4631:        for(i=1; i<=(nlstate); i++){
                   4632:          for(j=1; j<=(nlstate+ndeath);j++){
                   4633:            k=k+1;
                   4634:            mu[k][(int) age]=pmmij[i][j];
                   4635:          }
                   4636:        }
                   4637:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4638:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4639:            varpij[i][j][(int)age] = doldm[i][j];
                   4640: 
                   4641:        /*printf("\n%d ",(int)age);
                   4642:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4643:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4644:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4645:          }*/
                   4646: 
                   4647:        fprintf(ficresprob,"\n%d ",(int)age);
                   4648:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4649:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4650: 
                   4651:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4652:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4653:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4654:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4655:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4656:        }
                   4657:        i=0;
                   4658:        for (k=1; k<=(nlstate);k++){
                   4659:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4660:            i++;
1.126     brouard  4661:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4662:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4663:            for (j=1; j<=i;j++){
1.145     brouard  4664:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4665:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4666:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4667:            }
                   4668:          }
                   4669:        }/* end of loop for state */
                   4670:       } /* end of loop for age */
1.145     brouard  4671:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4672:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4673:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4674:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4675:       
1.126     brouard  4676:       /* Confidence intervalle of pij  */
                   4677:       /*
1.131     brouard  4678:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4679:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4680:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4681:        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);
                   4682:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4683:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4684:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4685:       */
                   4686: 
                   4687:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4688:       first1=1;first2=2;
1.126     brouard  4689:       for (k2=1; k2<=(nlstate);k2++){
                   4690:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4691:          if(l2==k2) continue;
                   4692:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4693:          for (k1=1; k1<=(nlstate);k1++){
                   4694:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4695:              if(l1==k1) continue;
                   4696:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4697:              if(i<=j) continue;
                   4698:              for (age=bage; age<=fage; age ++){ 
                   4699:                if ((int)age %5==0){
                   4700:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4701:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4702:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4703:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4704:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4705:                  c12=cv12/sqrt(v1*v2);
                   4706:                  /* Computing eigen value of matrix of covariance */
                   4707:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4708:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4709:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4710:                    if(first2==1){
                   4711:                      first1=0;
                   4712:                    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);
                   4713:                    }
                   4714:                    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);
                   4715:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4716:                    /* lc2=fabs(lc2); */
1.135     brouard  4717:                  }
                   4718: 
1.126     brouard  4719:                  /* Eigen vectors */
                   4720:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4721:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4722:                  v21=(lc1-v1)/cv12*v11;
                   4723:                  v12=-v21;
                   4724:                  v22=v11;
                   4725:                  tnalp=v21/v11;
                   4726:                  if(first1==1){
                   4727:                    first1=0;
                   4728:                    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);
                   4729:                  }
                   4730:                  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);
                   4731:                  /*printf(fignu*/
                   4732:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4733:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4734:                  if(first==1){
                   4735:                    first=0;
1.200     brouard  4736:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4737:                    fprintf(ficgp,"\nset parametric;unset label");
                   4738:                    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  4739:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4740:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4741:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4742: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4743:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4744:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4745:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4746:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4747:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4748:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4749:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4750:                    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",\
                   4751:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4752:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4753:                  }else{
                   4754:                    first=0;
                   4755:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4756:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4757:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4758:                    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",\
                   4759:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4760:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4761:                  }/* if first */
                   4762:                } /* age mod 5 */
                   4763:              } /* end loop age */
1.201     brouard  4764:              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  4765:              first=1;
                   4766:            } /*l12 */
                   4767:          } /* k12 */
                   4768:        } /*l1 */
                   4769:       }/* k1 */
1.169     brouard  4770:       /* } */ /* loop covariates */
1.126     brouard  4771:   }
                   4772:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4773:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4774:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4775:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4776:   free_vector(xp,1,npar);
                   4777:   fclose(ficresprob);
                   4778:   fclose(ficresprobcov);
                   4779:   fclose(ficresprobcor);
                   4780:   fflush(ficgp);
                   4781:   fflush(fichtmcov);
                   4782: }
                   4783: 
                   4784: 
                   4785: /******************* Printing html file ***********/
1.201     brouard  4786: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4787:                  int lastpass, int stepm, int weightopt, char model[],\
                   4788:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4789:                  int popforecast, int estepm ,\
                   4790:                  double jprev1, double mprev1,double anprev1, \
                   4791:                  double jprev2, double mprev2,double anprev2){
                   4792:   int jj1, k1, i1, cpt;
                   4793: 
                   4794:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4795:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4796: </ul>");
                   4797:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4798:  - 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  4799:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4800:    fprintf(fichtm,"\
                   4801:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4802:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4803:    fprintf(fichtm,"\
                   4804:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4805:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4806:    fprintf(fichtm,"\
1.128     brouard  4807:  - (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  4808:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4809:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4810:    fprintf(fichtm,"\
                   4811:  - Population projections by age and states: \
1.201     brouard  4812:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4813: 
                   4814: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4815: 
1.145     brouard  4816:  m=pow(2,cptcoveff);
1.126     brouard  4817:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4818: 
                   4819:  jj1=0;
                   4820:  for(k1=1; k1<=m;k1++){
1.192     brouard  4821:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4822:      jj1++;
                   4823:      if (cptcovn > 0) {
                   4824:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4825:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4826:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4827:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4828:        }
1.126     brouard  4829:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4830:      }
1.201     brouard  4831:      /* aij, bij */
                   4832:      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> \
                   4833: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4834:      /* Pij */
1.202     brouard  4835:      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  4836: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4837:      /* Quasi-incidences */
1.201     brouard  4838:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4839:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4840:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4841: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4842: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4843:      /* Survival functions (period) in state j */
                   4844:      for(cpt=1; cpt<=nlstate;cpt++){
                   4845:        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> \
                   4846: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4847:      }
                   4848:      /* State specific survival functions (period) */
                   4849:      for(cpt=1; cpt<=nlstate;cpt++){
1.208   ! brouard  4850:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  4851:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4852:  <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);
                   4853:      }
                   4854:      /* Period (stable) prevalence in each health state */
                   4855:      for(cpt=1; cpt<=nlstate;cpt++){
                   4856:        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> \
                   4857: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4858:      }
1.126     brouard  4859:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  4860:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
1.201     brouard  4861: <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  4862:      }
1.192     brouard  4863:    /* } /\* end i1 *\/ */
1.126     brouard  4864:  }/* End k1 */
                   4865:  fprintf(fichtm,"</ul>");
                   4866: 
                   4867:  fprintf(fichtm,"\
                   4868: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4869:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  4870:  - 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  4871: But because parameters are usually highly correlated (a higher incidence of disability \
                   4872: and a higher incidence of recovery can give very close observed transition) it might \
                   4873: be very useful to look not only at linear confidence intervals estimated from the \
                   4874: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4875: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4876: covariance matrix of the one-step probabilities. \
                   4877: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4878: 
1.193     brouard  4879:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4880:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4881:  fprintf(fichtm,"\
                   4882:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4883:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4884: 
                   4885:  fprintf(fichtm,"\
                   4886:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4887:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4888:  fprintf(fichtm,"\
                   4889:  - 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): \
                   4890:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4891:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4892:  fprintf(fichtm,"\
                   4893:  - (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): \
                   4894:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4895:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4896:  fprintf(fichtm,"\
1.128     brouard  4897:  - 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  4898:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4899:  fprintf(fichtm,"\
1.128     brouard  4900:  - 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  4901:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4902:  fprintf(fichtm,"\
                   4903:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4904:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4905: 
                   4906: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4907: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4908: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4909: /*     <br>",fileres,fileres,fileres,fileres); */
                   4910: /*  else  */
                   4911: /*    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); */
                   4912:  fflush(fichtm);
                   4913:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4914: 
1.145     brouard  4915:  m=pow(2,cptcoveff);
1.126     brouard  4916:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4917: 
                   4918:  jj1=0;
                   4919:  for(k1=1; k1<=m;k1++){
1.192     brouard  4920:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4921:      jj1++;
                   4922:      if (cptcovn > 0) {
                   4923:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4924:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4925:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4926:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4927:      }
                   4928:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4929:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  4930: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   4931: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  4932:      }
                   4933:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4934: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4935: true period expectancies (those weighted with period prevalences are also\
                   4936:  drawn in addition to the population based expectancies computed using\
1.205     brouard  4937:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   4938: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4939:    /* } /\* end i1 *\/ */
1.126     brouard  4940:  }/* End k1 */
                   4941:  fprintf(fichtm,"</ul>");
                   4942:  fflush(fichtm);
                   4943: }
                   4944: 
                   4945: /******************* Gnuplot file **************/
1.201     brouard  4946: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4947: 
                   4948:   char dirfileres[132],optfileres[132];
1.164     brouard  4949:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4950:   int ng=0;
1.201     brouard  4951:   int vpopbased;
1.126     brouard  4952: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4953: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4954: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4955: /*   } */
                   4956: 
                   4957:   /*#ifdef windows */
                   4958:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4959:     /*#endif */
                   4960:   m=pow(2,cptcoveff);
                   4961: 
1.202     brouard  4962:   /* Contribution to likelihood */
                   4963:   /* Plot the probability implied in the likelihood */
                   4964:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4965:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4966:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  4967:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  4968: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  4969:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   4970: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   4971:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  4972:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4973:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
1.204     brouard  4974:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4975:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
1.204     brouard  4976:     for (i=1; i<= nlstate ; i ++) {
                   4977:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  4978:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   4979:       fprintf(ficgp,"  u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
1.204     brouard  4980:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.205     brouard  4981:        fprintf(ficgp,",\\\n \"\" u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
1.204     brouard  4982:       }
                   4983:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   4984:     }
                   4985:     /* 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 */             
                   4986:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   4987:     /* 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  4988:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  4989:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   4990: 
1.126     brouard  4991:   strcpy(dirfileres,optionfilefiname);
                   4992:   strcpy(optfileres,"vpl");
                   4993:  /* 1eme*/
1.201     brouard  4994:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4995:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4996:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  4997:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   4998:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4999:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5000: set ylabel \"Probability\" \n\
1.199     brouard  5001: set ter svg size 640, 480\n\
1.201     brouard  5002: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5003: 
                   5004:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5005:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5006:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5007:      }
1.201     brouard  5008:      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  5009:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5010:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5011:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5012:      } 
1.201     brouard  5013:      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  5014:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5015:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5016:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5017:      }  
1.201     brouard  5018:      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));
                   5019:      fprintf(ficgp,"\nset out \n");
                   5020:     } /* k1 */
                   5021:   } /* cpt */
1.126     brouard  5022:   /*2 eme*/
1.153     brouard  5023:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  5024:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  5025:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5026:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5027:       if(vpopbased==0)
                   5028:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5029:       else
                   5030:        fprintf(ficgp,"\nreplot ");
                   5031:       for (i=1; i<= nlstate+1 ; i ++) {
                   5032:        k=2*i;
                   5033:        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);
                   5034:        for (j=1; j<= nlstate+1 ; j ++) {
                   5035:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5036:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5037:        }   
                   5038:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5039:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5040:        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);
                   5041:        for (j=1; j<= nlstate+1 ; j ++) {
                   5042:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5043:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5044:        }   
                   5045:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5046:        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);
                   5047:        for (j=1; j<= nlstate+1 ; j ++) {
                   5048:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5049:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5050:        }   
                   5051:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5052:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5053:       } /* state */
                   5054:     } /* vpopbased */
                   5055:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5056:   } /* k1 */
1.126     brouard  5057:   /*3eme*/
                   5058:   
                   5059:   for (k1=1; k1<= m ; k1 ++) { 
                   5060:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   5061:       /*       k=2+nlstate*(2*cpt-2); */
                   5062:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5063:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5064:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5065: 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  5066:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5067:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5068:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5069:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5070:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5071:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5072:        
                   5073:       */
                   5074:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5075:        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  5076:        /*      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);*/
                   5077:        
                   5078:       } 
1.201     brouard  5079:       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  5080:     }
                   5081:   }
                   5082:   
1.201     brouard  5083:   /* Survival functions (period) from state i in state j by initial state i */
                   5084:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5085:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5086:       k=3;
                   5087:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   5088:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5089:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5090: set ter svg size 640, 480\n\
                   5091: unset log y\n\
                   5092: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5093:       for (i=1; i<= nlstate ; i ++){
                   5094:        if(i==1)
                   5095:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5096:        else
                   5097:          fprintf(ficgp,", '' ");
                   5098:        l=(nlstate+ndeath)*(i-1)+1;
                   5099:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5100:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5101:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5102:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5103:       } /* nlstate */
                   5104:       fprintf(ficgp,"\nset out\n");
                   5105:     } /* end cpt state*/ 
                   5106:   } /* end covariate */  
                   5107: 
                   5108:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5109:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5110:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5111:       k=3;
                   5112:       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);
                   5113:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5114:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5115: set ter svg size 640, 480\n\
                   5116: unset log y\n\
                   5117: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5118:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5119:        if(j==1)
                   5120:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5121:        else
                   5122:          fprintf(ficgp,", '' ");
                   5123:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5124:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5125:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5126:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5127:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5128:       } /* nlstate */
                   5129:       fprintf(ficgp,", '' ");
                   5130:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5131:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5132:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5133:        if(j < nlstate)
                   5134:          fprintf(ficgp,"$%d +",k+l);
                   5135:        else
                   5136:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5137:       }
                   5138:       fprintf(ficgp,"\nset out\n");
                   5139:     } /* end cpt state*/ 
                   5140:   } /* end covariate */  
                   5141: 
1.202     brouard  5142:   /* CV preval stable (period) for each covariate */
                   5143:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  5144:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  5145:       k=3;
1.153     brouard  5146:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  5147:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5148:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5149: set ter svg size 640, 480\n\
1.126     brouard  5150: unset log y\n\
1.153     brouard  5151: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5152:       for (i=1; i<= nlstate ; i ++){
                   5153:        if(i==1)
1.201     brouard  5154:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5155:        else
                   5156:          fprintf(ficgp,", '' ");
1.154     brouard  5157:        l=(nlstate+ndeath)*(i-1)+1;
                   5158:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5159:        for (j=2; j<= nlstate ; j ++)
                   5160:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5161:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5162:       } /* nlstate */
1.201     brouard  5163:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5164:     } /* end cpt state*/ 
                   5165:   } /* end covariate */  
1.201     brouard  5166: 
1.126     brouard  5167:   /* proba elementaires */
1.187     brouard  5168:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5169:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5170:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5171:     for(k=1; k <=(nlstate+ndeath); k++){
                   5172:       if (k != i) {
1.187     brouard  5173:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5174:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5175:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5176:          jk++; 
                   5177:        }
1.187     brouard  5178:        fprintf(ficgp,"\n");
1.126     brouard  5179:       }
                   5180:     }
                   5181:    }
1.187     brouard  5182:   fprintf(ficgp,"##############\n#\n");
                   5183: 
1.145     brouard  5184:   /*goto avoid;*/
1.200     brouard  5185:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5186:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5187:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5188:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5189:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5190:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5191:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5192:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5193:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5194:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5195:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5196:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5197:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5198:   fprintf(ficgp,"#\n");
1.201     brouard  5199:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5200:      fprintf(ficgp,"# ng=%d\n",ng);
                   5201:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5202:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5203:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5204:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5205:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5206:        if (ng==1){
                   5207:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5208:         fprintf(ficgp,"\nunset log y");
                   5209:        }else if (ng==2){
                   5210:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5211:         fprintf(ficgp,"\nset log y");
                   5212:        }else if (ng==3){
1.126     brouard  5213:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5214:         fprintf(ficgp,"\nset log y");
                   5215:        }else
                   5216:         fprintf(ficgp,"\nunset title ");
                   5217:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5218:        i=1;
                   5219:        for(k2=1; k2<=nlstate; k2++) {
                   5220:         k3=i;
                   5221:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5222:           if (k != k2){
1.201     brouard  5223:             switch( ng) {
                   5224:             case 1:
1.187     brouard  5225:               if(nagesqr==0)
1.201     brouard  5226:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5227:               else /* nagesqr =1 */
1.201     brouard  5228:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5229:               break;
                   5230:             case 2: /* ng=2 */
1.187     brouard  5231:               if(nagesqr==0)
                   5232:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5233:               else /* nagesqr =1 */
1.201     brouard  5234:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5235:               break;
                   5236:             case 3:
                   5237:               if(nagesqr==0)
                   5238:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5239:               else /* nagesqr =1 */
                   5240:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5241:               break;
                   5242:             }
1.141     brouard  5243:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5244:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5245:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5246:               if(ij <=cptcovage) { /* Bug valgrind */
                   5247:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5248:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5249:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5250:                   ij++;
                   5251:                 }
1.186     brouard  5252:               }
                   5253:               else
1.198     brouard  5254:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5255:             }
1.201     brouard  5256:             if(ng != 1){
                   5257:               fprintf(ficgp,")/(1");
1.126     brouard  5258:             
1.201     brouard  5259:               for(k1=1; k1 <=nlstate; k1++){ 
                   5260:                 if(nagesqr==0)
                   5261:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5262:                 else /* nagesqr =1 */
                   5263:                   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);
                   5264:                 
                   5265:                 ij=1;
                   5266:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5267:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5268:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5269:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5270:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5271:                       ij++;
                   5272:                     }
1.197     brouard  5273:                   }
1.201     brouard  5274:                   else
                   5275:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5276:                 }
1.201     brouard  5277:                 fprintf(ficgp,")");
1.126     brouard  5278:               }
                   5279:               fprintf(ficgp,")");
1.201     brouard  5280:               if(ng ==2)
                   5281:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5282:               else /* ng= 3 */
                   5283:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5284:             }else{ /* end ng <> 1 */
                   5285:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5286:             }
                   5287:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5288:             i=i+ncovmodel;
                   5289:           }
                   5290:         } /* end k */
                   5291:        } /* end k2 */
1.201     brouard  5292:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5293:      } /* end jk */
                   5294:    } /* end ng */
1.164     brouard  5295:  /* avoid: */
1.126     brouard  5296:    fflush(ficgp); 
                   5297: }  /* end gnuplot */
                   5298: 
                   5299: 
                   5300: /*************** Moving average **************/
                   5301: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5302: 
                   5303:   int i, cpt, cptcod;
                   5304:   int modcovmax =1;
                   5305:   int mobilavrange, mob;
                   5306:   double age;
                   5307: 
                   5308:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5309:                           a covariate has 2 modalities */
                   5310:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5311: 
                   5312:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5313:     if(mobilav==1) mobilavrange=5; /* default */
                   5314:     else mobilavrange=mobilav;
                   5315:     for (age=bage; age<=fage; age++)
                   5316:       for (i=1; i<=nlstate;i++)
                   5317:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5318:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5319:     /* We keep the original values on the extreme ages bage, fage and for 
                   5320:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5321:        we use a 5 terms etc. until the borders are no more concerned. 
                   5322:     */ 
                   5323:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5324:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5325:        for (i=1; i<=nlstate;i++){
                   5326:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5327:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5328:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5329:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5330:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5331:              }
                   5332:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5333:          }
                   5334:        }
                   5335:       }/* end age */
                   5336:     }/* end mob */
                   5337:   }else return -1;
                   5338:   return 0;
                   5339: }/* End movingaverage */
                   5340: 
                   5341: 
                   5342: /************** Forecasting ******************/
1.169     brouard  5343: 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  5344:   /* proj1, year, month, day of starting projection 
                   5345:      agemin, agemax range of age
                   5346:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5347:      anproj2 year of en of projection (same day and month as proj1).
                   5348:   */
1.164     brouard  5349:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5350:   double agec; /* generic age */
                   5351:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5352:   double *popeffectif,*popcount;
                   5353:   double ***p3mat;
                   5354:   double ***mobaverage;
                   5355:   char fileresf[FILENAMELENGTH];
                   5356: 
                   5357:   agelim=AGESUP;
                   5358:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5359:  
1.201     brouard  5360:   strcpy(fileresf,"F_"); 
                   5361:   strcat(fileresf,fileresu);
1.126     brouard  5362:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5363:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5364:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5365:   }
                   5366:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5367:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5368: 
                   5369:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5370: 
                   5371:   if (mobilav!=0) {
                   5372:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5373:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5374:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5375:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5376:     }
                   5377:   }
                   5378: 
                   5379:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5380:   if (stepm<=12) stepsize=1;
                   5381:   if(estepm < stepm){
                   5382:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5383:   }
                   5384:   else  hstepm=estepm;   
                   5385: 
                   5386:   hstepm=hstepm/stepm; 
                   5387:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5388:                                fractional in yp1 */
                   5389:   anprojmean=yp;
                   5390:   yp2=modf((yp1*12),&yp);
                   5391:   mprojmean=yp;
                   5392:   yp1=modf((yp2*30.5),&yp);
                   5393:   jprojmean=yp;
                   5394:   if(jprojmean==0) jprojmean=1;
                   5395:   if(mprojmean==0) jprojmean=1;
                   5396: 
                   5397:   i1=cptcoveff;
                   5398:   if (cptcovn < 1){i1=1;}
                   5399:   
                   5400:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5401:   
                   5402:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5403: 
                   5404: /*           if (h==(int)(YEARM*yearp)){ */
                   5405:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5406:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5407:       k=k+1;
                   5408:       fprintf(ficresf,"\n#******");
                   5409:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5410:        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  5411:       }
                   5412:       fprintf(ficresf,"******\n");
                   5413:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5414:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5415:        for(i=1; i<=nlstate;i++)              
                   5416:           fprintf(ficresf," p%d%d",i,j);
                   5417:        fprintf(ficresf," p.%d",j);
                   5418:       }
                   5419:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5420:        fprintf(ficresf,"\n");
                   5421:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5422: 
                   5423:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5424:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5425:          nhstepm = nhstepm/hstepm; 
                   5426:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5427:          oldm=oldms;savm=savms;
                   5428:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5429:        
                   5430:          for (h=0; h<=nhstepm; h++){
                   5431:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5432:               fprintf(ficresf,"\n");
                   5433:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5434:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5435:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5436:            } 
                   5437:            for(j=1; j<=nlstate+ndeath;j++) {
                   5438:              ppij=0.;
                   5439:              for(i=1; i<=nlstate;i++) {
                   5440:                if (mobilav==1) 
                   5441:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5442:                else {
                   5443:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5444:                }
                   5445:                if (h*hstepm/YEARM*stepm== yearp) {
                   5446:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5447:                }
                   5448:              } /* end i */
                   5449:              if (h*hstepm/YEARM*stepm==yearp) {
                   5450:                fprintf(ficresf," %.3f", ppij);
                   5451:              }
                   5452:            }/* end j */
                   5453:          } /* end h */
                   5454:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5455:        } /* end agec */
                   5456:       } /* end yearp */
                   5457:     } /* end cptcod */
                   5458:   } /* end  cptcov */
                   5459:        
                   5460:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5461: 
                   5462:   fclose(ficresf);
                   5463: }
                   5464: 
                   5465: /************** Forecasting *****not tested NB*************/
1.169     brouard  5466: 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  5467:   
                   5468:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5469:   int *popage;
                   5470:   double calagedatem, agelim, kk1, kk2;
                   5471:   double *popeffectif,*popcount;
                   5472:   double ***p3mat,***tabpop,***tabpopprev;
                   5473:   double ***mobaverage;
                   5474:   char filerespop[FILENAMELENGTH];
                   5475: 
                   5476:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5477:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5478:   agelim=AGESUP;
                   5479:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5480:   
                   5481:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5482:   
                   5483:   
1.201     brouard  5484:   strcpy(filerespop,"POP_"); 
                   5485:   strcat(filerespop,fileresu);
1.126     brouard  5486:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5487:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5488:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5489:   }
                   5490:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5491:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5492: 
                   5493:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5494: 
                   5495:   if (mobilav!=0) {
                   5496:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5497:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5498:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5499:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5500:     }
                   5501:   }
                   5502: 
                   5503:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5504:   if (stepm<=12) stepsize=1;
                   5505:   
                   5506:   agelim=AGESUP;
                   5507:   
                   5508:   hstepm=1;
                   5509:   hstepm=hstepm/stepm; 
                   5510:   
                   5511:   if (popforecast==1) {
                   5512:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5513:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5514:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5515:     } 
                   5516:     popage=ivector(0,AGESUP);
                   5517:     popeffectif=vector(0,AGESUP);
                   5518:     popcount=vector(0,AGESUP);
                   5519:     
                   5520:     i=1;   
                   5521:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5522:    
                   5523:     imx=i;
                   5524:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5525:   }
                   5526: 
                   5527:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5528:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5529:       k=k+1;
                   5530:       fprintf(ficrespop,"\n#******");
                   5531:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5532:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5533:       }
                   5534:       fprintf(ficrespop,"******\n");
                   5535:       fprintf(ficrespop,"# Age");
                   5536:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5537:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5538:       
                   5539:       for (cpt=0; cpt<=0;cpt++) { 
                   5540:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5541:        
                   5542:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5543:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5544:          nhstepm = nhstepm/hstepm; 
                   5545:          
                   5546:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5547:          oldm=oldms;savm=savms;
                   5548:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5549:        
                   5550:          for (h=0; h<=nhstepm; h++){
                   5551:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5552:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5553:            } 
                   5554:            for(j=1; j<=nlstate+ndeath;j++) {
                   5555:              kk1=0.;kk2=0;
                   5556:              for(i=1; i<=nlstate;i++) {              
                   5557:                if (mobilav==1) 
                   5558:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5559:                else {
                   5560:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5561:                }
                   5562:              }
                   5563:              if (h==(int)(calagedatem+12*cpt)){
                   5564:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5565:                  /*fprintf(ficrespop," %.3f", kk1);
                   5566:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5567:              }
                   5568:            }
                   5569:            for(i=1; i<=nlstate;i++){
                   5570:              kk1=0.;
                   5571:                for(j=1; j<=nlstate;j++){
                   5572:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5573:                }
                   5574:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5575:            }
                   5576: 
                   5577:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5578:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5579:          }
                   5580:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5581:        }
                   5582:       }
                   5583:  
                   5584:   /******/
                   5585: 
                   5586:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5587:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5588:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5589:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5590:          nhstepm = nhstepm/hstepm; 
                   5591:          
                   5592:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5593:          oldm=oldms;savm=savms;
                   5594:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5595:          for (h=0; h<=nhstepm; h++){
                   5596:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5597:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5598:            } 
                   5599:            for(j=1; j<=nlstate+ndeath;j++) {
                   5600:              kk1=0.;kk2=0;
                   5601:              for(i=1; i<=nlstate;i++) {              
                   5602:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5603:              }
                   5604:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5605:            }
                   5606:          }
                   5607:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5608:        }
                   5609:       }
                   5610:    } 
                   5611:   }
                   5612:  
                   5613:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5614: 
                   5615:   if (popforecast==1) {
                   5616:     free_ivector(popage,0,AGESUP);
                   5617:     free_vector(popeffectif,0,AGESUP);
                   5618:     free_vector(popcount,0,AGESUP);
                   5619:   }
                   5620:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5621:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5622:   fclose(ficrespop);
                   5623: } /* End of popforecast */
                   5624: 
                   5625: int fileappend(FILE *fichier, char *optionfich)
                   5626: {
                   5627:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5628:     printf("Problem with file: %s\n", optionfich);
                   5629:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5630:     return (0);
                   5631:   }
                   5632:   fflush(fichier);
                   5633:   return (1);
                   5634: }
                   5635: 
                   5636: 
                   5637: /**************** function prwizard **********************/
                   5638: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5639: {
                   5640: 
                   5641:   /* Wizard to print covariance matrix template */
                   5642: 
1.164     brouard  5643:   char ca[32], cb[32];
                   5644:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5645:   int numlinepar;
                   5646: 
                   5647:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5648:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5649:   for(i=1; i <=nlstate; i++){
                   5650:     jj=0;
                   5651:     for(j=1; j <=nlstate+ndeath; j++){
                   5652:       if(j==i) continue;
                   5653:       jj++;
                   5654:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5655:       printf("%1d%1d",i,j);
                   5656:       fprintf(ficparo,"%1d%1d",i,j);
                   5657:       for(k=1; k<=ncovmodel;k++){
                   5658:        /*        printf(" %lf",param[i][j][k]); */
                   5659:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5660:        printf(" 0.");
                   5661:        fprintf(ficparo," 0.");
                   5662:       }
                   5663:       printf("\n");
                   5664:       fprintf(ficparo,"\n");
                   5665:     }
                   5666:   }
                   5667:   printf("# Scales (for hessian or gradient estimation)\n");
                   5668:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5669:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5670:   for(i=1; i <=nlstate; i++){
                   5671:     jj=0;
                   5672:     for(j=1; j <=nlstate+ndeath; j++){
                   5673:       if(j==i) continue;
                   5674:       jj++;
                   5675:       fprintf(ficparo,"%1d%1d",i,j);
                   5676:       printf("%1d%1d",i,j);
                   5677:       fflush(stdout);
                   5678:       for(k=1; k<=ncovmodel;k++){
                   5679:        /*      printf(" %le",delti3[i][j][k]); */
                   5680:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5681:        printf(" 0.");
                   5682:        fprintf(ficparo," 0.");
                   5683:       }
                   5684:       numlinepar++;
                   5685:       printf("\n");
                   5686:       fprintf(ficparo,"\n");
                   5687:     }
                   5688:   }
                   5689:   printf("# Covariance matrix\n");
                   5690: /* # 121 Var(a12)\n\ */
                   5691: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5692: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5693: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5694: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5695: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5696: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5697: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5698:   fflush(stdout);
                   5699:   fprintf(ficparo,"# Covariance matrix\n");
                   5700:   /* # 121 Var(a12)\n\ */
                   5701:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5702:   /* #   ...\n\ */
                   5703:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5704:   
                   5705:   for(itimes=1;itimes<=2;itimes++){
                   5706:     jj=0;
                   5707:     for(i=1; i <=nlstate; i++){
                   5708:       for(j=1; j <=nlstate+ndeath; j++){
                   5709:        if(j==i) continue;
                   5710:        for(k=1; k<=ncovmodel;k++){
                   5711:          jj++;
                   5712:          ca[0]= k+'a'-1;ca[1]='\0';
                   5713:          if(itimes==1){
                   5714:            printf("#%1d%1d%d",i,j,k);
                   5715:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5716:          }else{
                   5717:            printf("%1d%1d%d",i,j,k);
                   5718:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5719:            /*  printf(" %.5le",matcov[i][j]); */
                   5720:          }
                   5721:          ll=0;
                   5722:          for(li=1;li <=nlstate; li++){
                   5723:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5724:              if(lj==li) continue;
                   5725:              for(lk=1;lk<=ncovmodel;lk++){
                   5726:                ll++;
                   5727:                if(ll<=jj){
                   5728:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5729:                  if(ll<jj){
                   5730:                    if(itimes==1){
                   5731:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5732:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5733:                    }else{
                   5734:                      printf(" 0.");
                   5735:                      fprintf(ficparo," 0.");
                   5736:                    }
                   5737:                  }else{
                   5738:                    if(itimes==1){
                   5739:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5740:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5741:                    }else{
                   5742:                      printf(" 0.");
                   5743:                      fprintf(ficparo," 0.");
                   5744:                    }
                   5745:                  }
                   5746:                }
                   5747:              } /* end lk */
                   5748:            } /* end lj */
                   5749:          } /* end li */
                   5750:          printf("\n");
                   5751:          fprintf(ficparo,"\n");
                   5752:          numlinepar++;
                   5753:        } /* end k*/
                   5754:       } /*end j */
                   5755:     } /* end i */
                   5756:   } /* end itimes */
                   5757: 
                   5758: } /* end of prwizard */
                   5759: /******************* Gompertz Likelihood ******************************/
                   5760: double gompertz(double x[])
                   5761: { 
                   5762:   double A,B,L=0.0,sump=0.,num=0.;
                   5763:   int i,n=0; /* n is the size of the sample */
                   5764: 
                   5765:   for (i=0;i<=imx-1 ; i++) {
                   5766:     sump=sump+weight[i];
                   5767:     /*    sump=sump+1;*/
                   5768:     num=num+1;
                   5769:   }
                   5770:  
                   5771:  
                   5772:   /* for (i=0; i<=imx; i++) 
                   5773:      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]);*/
                   5774: 
                   5775:   for (i=1;i<=imx ; i++)
                   5776:     {
                   5777:       if (cens[i] == 1 && wav[i]>1)
                   5778:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5779:       
                   5780:       if (cens[i] == 0 && wav[i]>1)
                   5781:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5782:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5783:       
                   5784:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5785:       if (wav[i] > 1 ) { /* ??? */
                   5786:        L=L+A*weight[i];
                   5787:        /*      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]);*/
                   5788:       }
                   5789:     }
                   5790: 
                   5791:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5792:  
                   5793:   return -2*L*num/sump;
                   5794: }
                   5795: 
1.136     brouard  5796: #ifdef GSL
                   5797: /******************* Gompertz_f Likelihood ******************************/
                   5798: double gompertz_f(const gsl_vector *v, void *params)
                   5799: { 
                   5800:   double A,B,LL=0.0,sump=0.,num=0.;
                   5801:   double *x= (double *) v->data;
                   5802:   int i,n=0; /* n is the size of the sample */
                   5803: 
                   5804:   for (i=0;i<=imx-1 ; i++) {
                   5805:     sump=sump+weight[i];
                   5806:     /*    sump=sump+1;*/
                   5807:     num=num+1;
                   5808:   }
                   5809:  
                   5810:  
                   5811:   /* for (i=0; i<=imx; i++) 
                   5812:      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]);*/
                   5813:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5814:   for (i=1;i<=imx ; i++)
                   5815:     {
                   5816:       if (cens[i] == 1 && wav[i]>1)
                   5817:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5818:       
                   5819:       if (cens[i] == 0 && wav[i]>1)
                   5820:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5821:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5822:       
                   5823:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5824:       if (wav[i] > 1 ) { /* ??? */
                   5825:        LL=LL+A*weight[i];
                   5826:        /*      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]);*/
                   5827:       }
                   5828:     }
                   5829: 
                   5830:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5831:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5832:  
                   5833:   return -2*LL*num/sump;
                   5834: }
                   5835: #endif
                   5836: 
1.126     brouard  5837: /******************* Printing html file ***********/
1.201     brouard  5838: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5839:                  int lastpass, int stepm, int weightopt, char model[],\
                   5840:                  int imx,  double p[],double **matcov,double agemortsup){
                   5841:   int i,k;
                   5842: 
                   5843:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5844:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5845:   for (i=1;i<=2;i++) 
                   5846:     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  5847:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5848:   fprintf(fichtm,"</ul>");
                   5849: 
                   5850: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5851: 
                   5852:  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>");
                   5853: 
                   5854:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5855:    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]);
                   5856: 
                   5857:  
                   5858:   fflush(fichtm);
                   5859: }
                   5860: 
                   5861: /******************* Gnuplot file **************/
1.201     brouard  5862: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5863: 
                   5864:   char dirfileres[132],optfileres[132];
1.164     brouard  5865: 
1.126     brouard  5866:   int ng;
                   5867: 
                   5868: 
                   5869:   /*#ifdef windows */
                   5870:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5871:     /*#endif */
                   5872: 
                   5873: 
                   5874:   strcpy(dirfileres,optionfilefiname);
                   5875:   strcpy(optfileres,"vpl");
1.199     brouard  5876:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5877:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5878:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5879:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5880:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5881: 
                   5882: } 
                   5883: 
1.136     brouard  5884: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5885: {
1.126     brouard  5886: 
1.136     brouard  5887:   /*-------- data file ----------*/
                   5888:   FILE *fic;
                   5889:   char dummy[]="                         ";
1.164     brouard  5890:   int i=0, j=0, n=0;
1.136     brouard  5891:   int linei, month, year,iout;
                   5892:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5893:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5894:   char *stratrunc;
                   5895:   int lstra;
1.126     brouard  5896: 
                   5897: 
1.136     brouard  5898:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5899:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5900:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5901:   }
1.126     brouard  5902: 
1.136     brouard  5903:   i=1;
                   5904:   linei=0;
                   5905:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5906:     linei=linei+1;
                   5907:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5908:       if(line[j] == '\t')
                   5909:        line[j] = ' ';
                   5910:     }
                   5911:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5912:       ;
                   5913:     };
                   5914:     line[j+1]=0;  /* Trims blanks at end of line */
                   5915:     if(line[0]=='#'){
                   5916:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5917:       printf("Comment line\n%s\n",line);
                   5918:       continue;
                   5919:     }
                   5920:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5921:     strcpy(line, linetmp);
1.136     brouard  5922:   
1.126     brouard  5923: 
1.136     brouard  5924:     for (j=maxwav;j>=1;j--){
1.137     brouard  5925:       cutv(stra, strb, line, ' '); 
1.136     brouard  5926:       if(strb[0]=='.') { /* Missing status */
                   5927:        lval=-1;
                   5928:       }else{
                   5929:        errno=0;
                   5930:        lval=strtol(strb,&endptr,10); 
                   5931:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5932:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5933:          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);
                   5934:          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  5935:          return 1;
                   5936:        }
                   5937:       }
                   5938:       s[j][i]=lval;
                   5939:       
                   5940:       strcpy(line,stra);
                   5941:       cutv(stra, strb,line,' ');
1.169     brouard  5942:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5943:       }
1.169     brouard  5944:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5945:        month=99;
                   5946:        year=9999;
                   5947:       }else{
1.141     brouard  5948:        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);
                   5949:        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  5950:        return 1;
                   5951:       }
                   5952:       anint[j][i]= (double) year; 
                   5953:       mint[j][i]= (double)month; 
                   5954:       strcpy(line,stra);
                   5955:     } /* ENd Waves */
                   5956:     
                   5957:     cutv(stra, strb,line,' '); 
1.169     brouard  5958:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5959:     }
1.169     brouard  5960:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5961:       month=99;
                   5962:       year=9999;
                   5963:     }else{
1.141     brouard  5964:       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);
                   5965:        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  5966:        return 1;
                   5967:     }
                   5968:     andc[i]=(double) year; 
                   5969:     moisdc[i]=(double) month; 
                   5970:     strcpy(line,stra);
                   5971:     
                   5972:     cutv(stra, strb,line,' '); 
1.169     brouard  5973:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5974:     }
1.169     brouard  5975:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5976:       month=99;
                   5977:       year=9999;
                   5978:     }else{
1.141     brouard  5979:       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);
                   5980:       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  5981:        return 1;
                   5982:     }
                   5983:     if (year==9999) {
1.141     brouard  5984:       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);
                   5985:       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  5986:        return 1;
1.126     brouard  5987: 
1.136     brouard  5988:     }
                   5989:     annais[i]=(double)(year);
                   5990:     moisnais[i]=(double)(month); 
                   5991:     strcpy(line,stra);
                   5992:     
                   5993:     cutv(stra, strb,line,' '); 
                   5994:     errno=0;
                   5995:     dval=strtod(strb,&endptr); 
                   5996:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5997:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5998:       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  5999:       fflush(ficlog);
                   6000:       return 1;
                   6001:     }
                   6002:     weight[i]=dval; 
                   6003:     strcpy(line,stra);
                   6004:     
                   6005:     for (j=ncovcol;j>=1;j--){
                   6006:       cutv(stra, strb,line,' '); 
                   6007:       if(strb[0]=='.') { /* Missing status */
                   6008:        lval=-1;
                   6009:       }else{
                   6010:        errno=0;
                   6011:        lval=strtol(strb,&endptr,10); 
                   6012:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6013:          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);
                   6014:          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  6015:          return 1;
                   6016:        }
                   6017:       }
                   6018:       if(lval <-1 || lval >1){
1.141     brouard  6019:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6020:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6021:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6022:  For example, for multinomial values like 1, 2 and 3,\n \
                   6023:  build V1=0 V2=0 for the reference value (1),\n \
                   6024:         V1=1 V2=0 for (2) \n \
                   6025:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6026:  output of IMaCh is often meaningless.\n \
                   6027:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6028:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6029:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6030:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6031:  For example, for multinomial values like 1, 2 and 3,\n \
                   6032:  build V1=0 V2=0 for the reference value (1),\n \
                   6033:         V1=1 V2=0 for (2) \n \
                   6034:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6035:  output of IMaCh is often meaningless.\n \
                   6036:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6037:        return 1;
                   6038:       }
                   6039:       covar[j][i]=(double)(lval);
                   6040:       strcpy(line,stra);
                   6041:     }  
                   6042:     lstra=strlen(stra);
                   6043:      
                   6044:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6045:       stratrunc = &(stra[lstra-9]);
                   6046:       num[i]=atol(stratrunc);
                   6047:     }
                   6048:     else
                   6049:       num[i]=atol(stra);
                   6050:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6051:       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;}*/
                   6052:     
                   6053:     i=i+1;
                   6054:   } /* End loop reading  data */
1.126     brouard  6055: 
1.136     brouard  6056:   *imax=i-1; /* Number of individuals */
                   6057:   fclose(fic);
                   6058:  
                   6059:   return (0);
1.164     brouard  6060:   /* endread: */
1.136     brouard  6061:     printf("Exiting readdata: ");
                   6062:     fclose(fic);
                   6063:     return (1);
1.126     brouard  6064: 
                   6065: 
                   6066: 
1.136     brouard  6067: }
1.145     brouard  6068: void removespace(char *str) {
                   6069:   char *p1 = str, *p2 = str;
                   6070:   do
                   6071:     while (*p2 == ' ')
                   6072:       p2++;
1.169     brouard  6073:   while (*p1++ == *p2++);
1.145     brouard  6074: }
                   6075: 
                   6076: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6077:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6078:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6079:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6080:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6081:    * - cptcovage number of covariates with age*products =2
                   6082:    * - cptcovs number of simple covariates
                   6083:    * - 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
                   6084:    *     which is a new column after the 9 (ncovcol) variables. 
                   6085:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6086:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6087:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6088:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6089:  */
1.136     brouard  6090: {
1.145     brouard  6091:   int i, j, k, ks;
1.164     brouard  6092:   int  j1, k1, k2;
1.136     brouard  6093:   char modelsav[80];
1.145     brouard  6094:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6095:   char *strpt;
1.136     brouard  6096: 
1.145     brouard  6097:   /*removespace(model);*/
1.136     brouard  6098:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6099:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6100:     if (strstr(model,"AGE") !=0){
1.192     brouard  6101:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6102:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6103:       return 1;
                   6104:     }
1.141     brouard  6105:     if (strstr(model,"v") !=0){
                   6106:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6107:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6108:       return 1;
                   6109:     }
1.187     brouard  6110:     strcpy(modelsav,model); 
                   6111:     if ((strpt=strstr(model,"age*age")) !=0){
                   6112:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6113:       if(strpt != model){
                   6114:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6115:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6116:  corresponding column of parameters.\n",model);
                   6117:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6118:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6119:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6120:       return 1;
                   6121:     }
                   6122: 
                   6123:       nagesqr=1;
                   6124:       if (strstr(model,"+age*age") !=0)
                   6125:        substrchaine(modelsav, model, "+age*age");
                   6126:       else if (strstr(model,"age*age+") !=0)
                   6127:        substrchaine(modelsav, model, "age*age+");
                   6128:       else 
                   6129:        substrchaine(modelsav, model, "age*age");
                   6130:     }else
                   6131:       nagesqr=0;
                   6132:     if (strlen(modelsav) >1){
                   6133:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6134:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6135:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6136:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6137:                   * cst, age and age*age 
                   6138:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6139:                   /* including age products which are counted in cptcovage.
                   6140:                  * but the covariates which are products must be treated 
                   6141:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6142:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6143:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6144: 
                   6145:     
                   6146:       /*   Design
                   6147:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6148:        *  <          ncovcol=8                >
                   6149:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6150:        *   k=  1    2      3       4     5       6      7        8
                   6151:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6152:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6153:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6154:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6155:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6156:        *  Tage[++cptcovage]=k
                   6157:        *       if products, new covar are created after ncovcol with k1
                   6158:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6159:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6160:        *  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
                   6161:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6162:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6163:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6164:        *  <          ncovcol=8                >
                   6165:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6166:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6167:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6168:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6169:        * p Tprod[1]@2={                         6, 5}
                   6170:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6171:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6172:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6173:        *How to reorganize?
                   6174:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6175:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6176:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6177:        * Struct []
                   6178:        */
1.145     brouard  6179: 
1.187     brouard  6180:       /* This loop fills the array Tvar from the string 'model'.*/
                   6181:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6182:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6183:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6184:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6185:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6186:       /*       k=1 Tvar[1]=2 (from V2) */
                   6187:       /*       k=5 Tvar[5] */
                   6188:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6189:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6190:       /*       } */
1.198     brouard  6191:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6192:       /*
                   6193:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6194:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6195:         Tvar[k]=0;
1.187     brouard  6196:       cptcovage=0;
                   6197:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6198:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6199:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6200:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6201:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6202:        /*scanf("%d",i);*/
                   6203:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6204:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6205:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6206:            /* covar is not filled and then is empty */
                   6207:            cptcovprod--;
                   6208:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6209:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6210:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6211:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6212:            /*printf("stre=%s ", stre);*/
                   6213:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6214:            cptcovprod--;
                   6215:            cutl(stre,strb,strc,'V');
                   6216:            Tvar[k]=atoi(stre);
                   6217:            cptcovage++;
                   6218:            Tage[cptcovage]=k;
                   6219:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6220:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6221:            cptcovn++;
                   6222:            cptcovprodnoage++;k1++;
                   6223:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6224:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6225:                                   because this model-covariate is a construction we invent a new column
                   6226:                                   ncovcol + k1
                   6227:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6228:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6229:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6230:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6231:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6232:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6233:            k2=k2+2;
                   6234:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6235:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6236:            for (i=1; i<=lastobs;i++){
                   6237:              /* Computes the new covariate which is a product of
                   6238:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6239:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6240:            }
                   6241:          } /* End age is not in the model */
                   6242:        } /* End if model includes a product */
                   6243:        else { /* no more sum */
                   6244:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6245:          /*  scanf("%d",i);*/
                   6246:          cutl(strd,strc,strb,'V');
                   6247:          ks++; /**< Number of simple covariates */
1.145     brouard  6248:          cptcovn++;
1.187     brouard  6249:          Tvar[k]=atoi(strd);
                   6250:        }
                   6251:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6252:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6253:          scanf("%d",i);*/
                   6254:       } /* end of loop + on total covariates */
                   6255:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6256:   } /* end if strlen(model == 0) */
1.136     brouard  6257:   
                   6258:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6259:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6260: 
                   6261:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6262:   printf("cptcovprod=%d ", cptcovprod);
                   6263:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6264: 
                   6265:   scanf("%d ",i);*/
                   6266: 
                   6267: 
1.137     brouard  6268:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6269:   /*endread:*/
1.136     brouard  6270:     printf("Exiting decodemodel: ");
                   6271:     return (1);
                   6272: }
                   6273: 
1.169     brouard  6274: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6275: {
                   6276:   int i, m;
                   6277: 
                   6278:   for (i=1; i<=imx; i++) {
                   6279:     for(m=2; (m<= maxwav); m++) {
                   6280:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6281:        anint[m][i]=9999;
                   6282:        s[m][i]=-1;
                   6283:       }
                   6284:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6285:        *nberr = *nberr + 1;
                   6286:        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);
                   6287:        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  6288:        s[m][i]=-1;
                   6289:       }
                   6290:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6291:        (*nberr)++;
1.136     brouard  6292:        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]); 
                   6293:        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]); 
                   6294:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6295:       }
                   6296:     }
                   6297:   }
                   6298: 
                   6299:   for (i=1; i<=imx; i++)  {
                   6300:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6301:     for(m=firstpass; (m<= lastpass); m++){
                   6302:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6303:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6304:          if(agedc[i]>0){
                   6305:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6306:              agev[m][i]=agedc[i];
                   6307:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6308:            }else {
1.136     brouard  6309:              if ((int)andc[i]!=9999){
                   6310:                nbwarn++;
                   6311:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6312:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6313:                agev[m][i]=-1;
                   6314:              }
                   6315:            }
1.169     brouard  6316:          } /* agedc > 0 */
1.136     brouard  6317:        }
                   6318:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6319:                                 years but with the precision of a month */
                   6320:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6321:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6322:            agev[m][i]=1;
                   6323:          else if(agev[m][i] < *agemin){ 
                   6324:            *agemin=agev[m][i];
                   6325:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6326:          }
                   6327:          else if(agev[m][i] >*agemax){
                   6328:            *agemax=agev[m][i];
1.156     brouard  6329:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6330:          }
                   6331:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6332:          /*     agev[m][i] = age[i]+2*m;*/
                   6333:        }
                   6334:        else { /* =9 */
                   6335:          agev[m][i]=1;
                   6336:          s[m][i]=-1;
                   6337:        }
                   6338:       }
                   6339:       else /*= 0 Unknown */
                   6340:        agev[m][i]=1;
                   6341:     }
                   6342:     
                   6343:   }
                   6344:   for (i=1; i<=imx; i++)  {
                   6345:     for(m=firstpass; (m<=lastpass); m++){
                   6346:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6347:        (*nberr)++;
1.136     brouard  6348:        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);     
                   6349:        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);     
                   6350:        return 1;
                   6351:       }
                   6352:     }
                   6353:   }
                   6354: 
                   6355:   /*for (i=1; i<=imx; i++){
                   6356:   for (m=firstpass; (m<lastpass); m++){
                   6357:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6358: }
                   6359: 
                   6360: }*/
                   6361: 
                   6362: 
1.139     brouard  6363:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6364:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6365: 
                   6366:   return (0);
1.164     brouard  6367:  /* endread:*/
1.136     brouard  6368:     printf("Exiting calandcheckages: ");
                   6369:     return (1);
                   6370: }
                   6371: 
1.172     brouard  6372: #if defined(_MSC_VER)
                   6373: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6374: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6375: //#include "stdafx.h"
                   6376: //#include <stdio.h>
                   6377: //#include <tchar.h>
                   6378: //#include <windows.h>
                   6379: //#include <iostream>
                   6380: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6381: 
                   6382: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6383: 
                   6384: BOOL IsWow64()
                   6385: {
                   6386:        BOOL bIsWow64 = FALSE;
                   6387: 
                   6388:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6389:        //  (HANDLE, PBOOL);
                   6390: 
                   6391:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6392: 
                   6393:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6394:        const char funcName[] = "IsWow64Process";
                   6395:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6396:                GetProcAddress(module, funcName);
                   6397: 
                   6398:        if (NULL != fnIsWow64Process)
                   6399:        {
                   6400:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6401:                        &bIsWow64))
                   6402:                        //throw std::exception("Unknown error");
                   6403:                        printf("Unknown error\n");
                   6404:        }
                   6405:        return bIsWow64 != FALSE;
                   6406: }
                   6407: #endif
1.177     brouard  6408: 
1.191     brouard  6409: void syscompilerinfo(int logged)
1.167     brouard  6410:  {
                   6411:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6412:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6413:    /* /GS /W3 /Gy
                   6414:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6415:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6416:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6417:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6418:    */ 
                   6419:    /* 64 bits */
1.185     brouard  6420:    /*
                   6421:      /GS /W3 /Gy
                   6422:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6423:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6424:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6425:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6426:    /* Optimization are useless and O3 is slower than O2 */
                   6427:    /*
                   6428:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6429:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6430:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6431:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6432:    */
1.186     brouard  6433:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6434:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6435:       /PDB:"visual studio
                   6436:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6437:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6438:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6439:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6440:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6441:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6442:       uiAccess='false'"
                   6443:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6444:       /NOLOGO /TLBID:1
                   6445:    */
1.177     brouard  6446: #if defined __INTEL_COMPILER
1.178     brouard  6447: #if defined(__GNUC__)
                   6448:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6449: #endif
1.177     brouard  6450: #elif defined(__GNUC__) 
1.179     brouard  6451: #ifndef  __APPLE__
1.174     brouard  6452: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6453: #endif
1.177     brouard  6454:    struct utsname sysInfo;
1.178     brouard  6455:    int cross = CROSS;
                   6456:    if (cross){
                   6457:           printf("Cross-");
1.191     brouard  6458:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6459:    }
1.174     brouard  6460: #endif
                   6461: 
1.171     brouard  6462: #include <stdint.h>
1.178     brouard  6463: 
1.191     brouard  6464:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6465: #if defined(__clang__)
1.191     brouard  6466:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6467: #endif
                   6468: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6469:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6470: #endif
                   6471: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6472:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6473: #endif
                   6474: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6475:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6476: #endif
                   6477: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6478:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6479: #endif
                   6480: #if defined(_MSC_VER)
1.191     brouard  6481:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6482: #endif
                   6483: #if defined(__PGI)
1.191     brouard  6484:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6485: #endif
                   6486: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6487:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6488: #endif
1.191     brouard  6489:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6490:    
1.167     brouard  6491: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6492: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6493:     // Windows (x64 and x86)
1.191     brouard  6494:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6495: #elif __unix__ // all unices, not all compilers
                   6496:     // Unix
1.191     brouard  6497:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6498: #elif __linux__
                   6499:     // linux
1.191     brouard  6500:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6501: #elif __APPLE__
1.174     brouard  6502:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6503:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6504: #endif
                   6505: 
                   6506: /*  __MINGW32__          */
                   6507: /*  __CYGWIN__  */
                   6508: /* __MINGW64__  */
                   6509: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6510: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6511: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6512: /* _WIN64  // Defined for applications for Win64. */
                   6513: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6514: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6515: 
1.167     brouard  6516: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6517:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6518: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6519:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6520: #else
1.191     brouard  6521:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6522: #endif
                   6523: 
1.169     brouard  6524: #if defined(__GNUC__)
                   6525: # if defined(__GNUC_PATCHLEVEL__)
                   6526: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6527:                             + __GNUC_MINOR__ * 100 \
                   6528:                             + __GNUC_PATCHLEVEL__)
                   6529: # else
                   6530: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6531:                             + __GNUC_MINOR__ * 100)
                   6532: # endif
1.174     brouard  6533:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6534:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6535: 
                   6536:    if (uname(&sysInfo) != -1) {
                   6537:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6538:         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  6539:    }
                   6540:    else
                   6541:       perror("uname() error");
1.179     brouard  6542:    //#ifndef __INTEL_COMPILER 
                   6543: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6544:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6545:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6546: #endif
1.169     brouard  6547: #endif
1.172     brouard  6548: 
                   6549:    //   void main()
                   6550:    //   {
1.169     brouard  6551: #if defined(_MSC_VER)
1.174     brouard  6552:    if (IsWow64()){
1.191     brouard  6553:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6554:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6555:    }
                   6556:    else{
1.191     brouard  6557:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6558:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6559:    }
1.172     brouard  6560:    //     printf("\nPress Enter to continue...");
                   6561:    //     getchar();
                   6562:    //   }
                   6563: 
1.169     brouard  6564: #endif
                   6565:    
1.167     brouard  6566: 
                   6567:  }
1.136     brouard  6568: 
1.203     brouard  6569:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
1.180     brouard  6570:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6571:   int i, j, k, i1 ;
1.202     brouard  6572:   /* double ftolpl = 1.e-10; */
1.180     brouard  6573:   double age, agebase, agelim;
1.203     brouard  6574:   double tot;
1.180     brouard  6575: 
1.202     brouard  6576:   strcpy(filerespl,"PL_");
                   6577:   strcat(filerespl,fileresu);
                   6578:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6579:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6580:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6581:   }
                   6582:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6583:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6584:   pstamp(ficrespl);
1.203     brouard  6585:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6586:   fprintf(ficrespl,"#Age ");
                   6587:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6588:   fprintf(ficrespl,"\n");
1.180     brouard  6589:   
                   6590:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6591: 
                   6592:     agebase=ageminpar;
                   6593:     agelim=agemaxpar;
                   6594: 
                   6595:     i1=pow(2,cptcoveff);
                   6596:     if (cptcovn < 1){i1=1;}
                   6597: 
                   6598:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6599:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6600:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6601:        k=k+1;
                   6602:        /* to clean */
1.198     brouard  6603:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6604:        fprintf(ficrespl,"#******");
                   6605:        printf("#******");
                   6606:        fprintf(ficlog,"#******");
1.180     brouard  6607:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6608:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6609:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6610:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6611:        }
                   6612:        fprintf(ficrespl,"******\n");
                   6613:        printf("******\n");
                   6614:        fprintf(ficlog,"******\n");
                   6615: 
                   6616:        fprintf(ficrespl,"#Age ");
                   6617:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6618:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6619:        }
1.203     brouard  6620:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6621:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6622:        
                   6623:        for (age=agebase; age<=agelim; age++){
                   6624:        /* for (age=agebase; age<=agebase; age++){ */
1.203     brouard  6625:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
1.180     brouard  6626:          fprintf(ficrespl,"%.0f ",age );
                   6627:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6628:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6629:          tot=0.;
                   6630:          for(i=1; i<=nlstate;i++){
                   6631:            tot +=  prlim[i][i];
1.180     brouard  6632:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6633:          }
                   6634:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
1.180     brouard  6635:        } /* Age */
                   6636:        /* was end of cptcod */
                   6637:     } /* cptcov */
1.184     brouard  6638:        return 0;
1.180     brouard  6639: }
                   6640: 
                   6641: int hPijx(double *p, int bage, int fage){
                   6642:     /*------------- h Pij x at various ages ------------*/
                   6643: 
                   6644:   int stepsize;
                   6645:   int agelim;
                   6646:   int hstepm;
                   6647:   int nhstepm;
                   6648:   int h, i, i1, j, k;
                   6649: 
                   6650:   double agedeb;
                   6651:   double ***p3mat;
                   6652: 
1.201     brouard  6653:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6654:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6655:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6656:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6657:     }
                   6658:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6659:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6660:   
                   6661:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6662:     /*if (stepm<=24) stepsize=2;*/
                   6663: 
                   6664:     agelim=AGESUP;
                   6665:     hstepm=stepsize*YEARM; /* Every year of age */
                   6666:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6667: 
                   6668:     /* hstepm=1;   aff par mois*/
                   6669:     pstamp(ficrespij);
                   6670:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6671:     i1= pow(2,cptcoveff);
1.183     brouard  6672:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6673:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6674:    /*          k=k+1;  */
                   6675:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6676:       fprintf(ficrespij,"\n#****** ");
                   6677:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6678:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6679:       fprintf(ficrespij,"******\n");
                   6680:       
                   6681:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6682:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6683:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6684:        
                   6685:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6686:        
1.183     brouard  6687:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6688:        oldm=oldms;savm=savms;
                   6689:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6690:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6691:        for(i=1; i<=nlstate;i++)
                   6692:          for(j=1; j<=nlstate+ndeath;j++)
                   6693:            fprintf(ficrespij," %1d-%1d",i,j);
                   6694:        fprintf(ficrespij,"\n");
                   6695:        for (h=0; h<=nhstepm; h++){
                   6696:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6697:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6698:          for(i=1; i<=nlstate;i++)
                   6699:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6700:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6701:          fprintf(ficrespij,"\n");
                   6702:        }
1.183     brouard  6703:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6704:        fprintf(ficrespij,"\n");
                   6705:       }
1.180     brouard  6706:       /*}*/
                   6707:     }
1.184     brouard  6708:        return 0;
1.180     brouard  6709: }
                   6710: 
                   6711: 
1.136     brouard  6712: /***********************************************/
                   6713: /**************** Main Program *****************/
                   6714: /***********************************************/
                   6715: 
                   6716: int main(int argc, char *argv[])
                   6717: {
                   6718: #ifdef GSL
                   6719:   const gsl_multimin_fminimizer_type *T;
                   6720:   size_t iteri = 0, it;
                   6721:   int rval = GSL_CONTINUE;
                   6722:   int status = GSL_SUCCESS;
                   6723:   double ssval;
                   6724: #endif
                   6725:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6726:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.203     brouard  6727:   int ncvyearnp=0;
                   6728:   int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6729:   int jj, ll, li, lj, lk;
1.136     brouard  6730:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6731:   int num_filled;
1.136     brouard  6732:   int itimes;
                   6733:   int NDIM=2;
                   6734:   int vpopbased=0;
                   6735: 
1.164     brouard  6736:   char ca[32], cb[32];
1.136     brouard  6737:   /*  FILE *fichtm; *//* Html File */
                   6738:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6739:   struct stat info;
1.191     brouard  6740:   double agedeb=0.;
1.194     brouard  6741: 
                   6742:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6743: 
1.165     brouard  6744:   double fret;
1.191     brouard  6745:   double dum=0.; /* Dummy variable */
1.136     brouard  6746:   double ***p3mat;
                   6747:   double ***mobaverage;
1.164     brouard  6748: 
                   6749:   char line[MAXLINE];
1.197     brouard  6750:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6751: 
                   6752:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6753:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6754:   char *tok, *val; /* pathtot */
1.136     brouard  6755:   int firstobs=1, lastobs=10;
1.195     brouard  6756:   int c,  h , cpt, c2;
1.191     brouard  6757:   int jl=0;
                   6758:   int i1, j1, jk, stepsize=0;
1.194     brouard  6759:   int count=0;
                   6760: 
1.164     brouard  6761:   int *tab; 
1.136     brouard  6762:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6763:   int mobilav=0,popforecast=0;
1.191     brouard  6764:   int hstepm=0, nhstepm=0;
1.136     brouard  6765:   int agemortsup;
                   6766:   float  sumlpop=0.;
                   6767:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6768:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6769: 
1.191     brouard  6770:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6771:   double ftolpl=FTOL;
                   6772:   double **prlim;
                   6773:   double ***param; /* Matrix of parameters */
                   6774:   double  *p;
                   6775:   double **matcov; /* Matrix of covariance */
1.203     brouard  6776:   double **hess; /* Hessian matrix */
1.136     brouard  6777:   double ***delti3; /* Scale */
                   6778:   double *delti; /* Scale */
                   6779:   double ***eij, ***vareij;
                   6780:   double **varpl; /* Variances of prevalence limits by age */
                   6781:   double *epj, vepp;
1.164     brouard  6782: 
1.136     brouard  6783:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6784:   double **ximort;
1.145     brouard  6785:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6786:   int *dcwave;
                   6787: 
1.164     brouard  6788:   char z[1]="c";
1.136     brouard  6789: 
                   6790:   /*char  *strt;*/
                   6791:   char strtend[80];
1.126     brouard  6792: 
1.164     brouard  6793: 
1.126     brouard  6794: /*   setlocale (LC_ALL, ""); */
                   6795: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6796: /*   textdomain (PACKAGE); */
                   6797: /*   setlocale (LC_CTYPE, ""); */
                   6798: /*   setlocale (LC_MESSAGES, ""); */
                   6799: 
                   6800:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6801:   rstart_time = time(NULL);  
                   6802:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6803:   start_time = *localtime(&rstart_time);
1.126     brouard  6804:   curr_time=start_time;
1.157     brouard  6805:   /*tml = *localtime(&start_time.tm_sec);*/
                   6806:   /* strcpy(strstart,asctime(&tml)); */
                   6807:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6808: 
                   6809: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6810: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6811: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6812: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6813: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6814: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6815: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6816: /*   strt=asctime(&tmg); */
                   6817: /*   printf("Time(after) =%s",strstart);  */
                   6818: /*  (void) time (&time_value);
                   6819: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6820: *  tm = *localtime(&time_value);
                   6821: *  strstart=asctime(&tm);
                   6822: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6823: */
                   6824: 
                   6825:   nberr=0; /* Number of errors and warnings */
                   6826:   nbwarn=0;
1.184     brouard  6827: #ifdef WIN32
                   6828:   _getcwd(pathcd, size);
                   6829: #else
1.126     brouard  6830:   getcwd(pathcd, size);
1.184     brouard  6831: #endif
1.191     brouard  6832:   syscompilerinfo(0);
1.196     brouard  6833:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6834:   if(argc <=1){
                   6835:     printf("\nEnter the parameter file name: ");
1.205     brouard  6836:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   6837:       printf("ERROR Empty parameter file name\n");
                   6838:       goto end;
                   6839:     }
1.126     brouard  6840:     i=strlen(pathr);
                   6841:     if(pathr[i-1]=='\n')
                   6842:       pathr[i-1]='\0';
1.156     brouard  6843:     i=strlen(pathr);
1.205     brouard  6844:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  6845:       pathr[i-1]='\0';
1.205     brouard  6846:     }
                   6847:     i=strlen(pathr);
                   6848:     if( i==0 ){
                   6849:       printf("ERROR Empty parameter file name\n");
                   6850:       goto end;
                   6851:     }
                   6852:     for (tok = pathr; tok != NULL; ){
1.126     brouard  6853:       printf("Pathr |%s|\n",pathr);
                   6854:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6855:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6856:       strcpy (pathtot, val);
                   6857:       if(pathr[0] == '\0') break; /* Dirty */
                   6858:     }
                   6859:   }
                   6860:   else{
                   6861:     strcpy(pathtot,argv[1]);
                   6862:   }
                   6863:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6864:   /*cygwin_split_path(pathtot,path,optionfile);
                   6865:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6866:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6867: 
                   6868:   /* Split argv[0], imach program to get pathimach */
                   6869:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6870:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6871:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6872:  /*   strcpy(pathimach,argv[0]); */
                   6873:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6874:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6875:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6876: #ifdef WIN32
                   6877:   _chdir(path); /* Can be a relative path */
                   6878:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6879: #else
1.126     brouard  6880:   chdir(path); /* Can be a relative path */
1.184     brouard  6881:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6882: #endif
                   6883:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6884:   strcpy(command,"mkdir ");
                   6885:   strcat(command,optionfilefiname);
                   6886:   if((outcmd=system(command)) != 0){
1.169     brouard  6887:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6888:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6889:     /* fclose(ficlog); */
                   6890: /*     exit(1); */
                   6891:   }
                   6892: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6893: /*     perror("mkdir"); */
                   6894: /*   } */
                   6895: 
                   6896:   /*-------- arguments in the command line --------*/
                   6897: 
1.186     brouard  6898:   /* Main Log file */
1.126     brouard  6899:   strcat(filelog, optionfilefiname);
                   6900:   strcat(filelog,".log");    /* */
                   6901:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6902:     printf("Problem with logfile %s\n",filelog);
                   6903:     goto end;
                   6904:   }
                   6905:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6906:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6907:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6908:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6909:  path=%s \n\
                   6910:  optionfile=%s\n\
                   6911:  optionfilext=%s\n\
1.156     brouard  6912:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6913: 
1.197     brouard  6914:   syscompilerinfo(1);
1.167     brouard  6915: 
1.126     brouard  6916:   printf("Local time (at start):%s",strstart);
                   6917:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6918:   fflush(ficlog);
                   6919: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6920: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6921: 
                   6922:   /* */
                   6923:   strcpy(fileres,"r");
                   6924:   strcat(fileres, optionfilefiname);
1.201     brouard  6925:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6926:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6927:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6928: 
1.186     brouard  6929:   /* Main ---------arguments file --------*/
1.126     brouard  6930: 
                   6931:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6932:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6933:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6934:     fflush(ficlog);
1.149     brouard  6935:     /* goto end; */
                   6936:     exit(70); 
1.126     brouard  6937:   }
                   6938: 
                   6939: 
                   6940: 
                   6941:   strcpy(filereso,"o");
1.201     brouard  6942:   strcat(filereso,fileresu);
1.126     brouard  6943:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6944:     printf("Problem with Output resultfile: %s\n", filereso);
                   6945:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6946:     fflush(ficlog);
                   6947:     goto end;
                   6948:   }
                   6949: 
                   6950:   /* Reads comments: lines beginning with '#' */
                   6951:   numlinepar=0;
1.197     brouard  6952: 
                   6953:     /* First parameter line */
                   6954:   while(fgets(line, MAXLINE, ficpar)) {
                   6955:     /* If line starts with a # it is a comment */
                   6956:     if (line[0] == '#') {
                   6957:       numlinepar++;
                   6958:       fputs(line,stdout);
                   6959:       fputs(line,ficparo);
                   6960:       fputs(line,ficlog);
                   6961:       continue;
                   6962:     }else
                   6963:       break;
                   6964:   }
                   6965:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6966:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6967:     if (num_filled != 5) {
                   6968:       printf("Should be 5 parameters\n");
                   6969:     }
1.126     brouard  6970:     numlinepar++;
1.197     brouard  6971:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6972:   }
                   6973:   /* Second parameter line */
                   6974:   while(fgets(line, MAXLINE, ficpar)) {
                   6975:     /* If line starts with a # it is a comment */
                   6976:     if (line[0] == '#') {
                   6977:       numlinepar++;
                   6978:       fputs(line,stdout);
                   6979:       fputs(line,ficparo);
                   6980:       fputs(line,ficlog);
                   6981:       continue;
                   6982:     }else
                   6983:       break;
                   6984:   }
                   6985:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6986:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6987:     if (num_filled != 8) {
                   6988:       printf("Not 8\n");
                   6989:     }
                   6990:     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  6991:   }
1.203     brouard  6992:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   6993:   ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  6994:   /* Third parameter line */
                   6995:   while(fgets(line, MAXLINE, ficpar)) {
                   6996:     /* If line starts with a # it is a comment */
                   6997:     if (line[0] == '#') {
                   6998:       numlinepar++;
                   6999:       fputs(line,stdout);
                   7000:       fputs(line,ficparo);
                   7001:       fputs(line,ficlog);
                   7002:       continue;
                   7003:     }else
                   7004:       break;
                   7005:   }
1.201     brouard  7006:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7007:     if (num_filled == 0)
                   7008:             model[0]='\0';
                   7009:     else if (num_filled != 1){
1.197     brouard  7010:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7011:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7012:       model[0]='\0';
                   7013:       goto end;
                   7014:     }
                   7015:     else{
                   7016:       if (model[0]=='+'){
                   7017:        for(i=1; i<=strlen(model);i++)
                   7018:          modeltemp[i-1]=model[i];
1.201     brouard  7019:        strcpy(model,modeltemp); 
1.197     brouard  7020:       }
                   7021:     }
1.199     brouard  7022:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7023:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7024:   }
                   7025:   /* 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); */
                   7026:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7027:   /* 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  7028:   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);
                   7029:   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  7030:   fflush(ficlog);
1.190     brouard  7031:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7032:   if(model[0]=='#'){
1.187     brouard  7033:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7034:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7035:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7036:     if(mle != -1){
                   7037:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7038:       exit(1);
                   7039:     }
                   7040:   }
1.126     brouard  7041:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7042:     ungetc(c,ficpar);
                   7043:     fgets(line, MAXLINE, ficpar);
                   7044:     numlinepar++;
1.195     brouard  7045:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7046:       z[0]=line[1];
                   7047:     }
                   7048:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7049:     fputs(line, stdout);
                   7050:     //puts(line);
1.126     brouard  7051:     fputs(line,ficparo);
                   7052:     fputs(line,ficlog);
                   7053:   }
                   7054:   ungetc(c,ficpar);
                   7055: 
                   7056:    
1.145     brouard  7057:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7058:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7059:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7060:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7061:   */
                   7062:   if (strlen(model)>1) 
1.187     brouard  7063:     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  7064:   else
1.187     brouard  7065:     ncovmodel=2; /* Constant and age */
1.133     brouard  7066:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7067:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7068:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7069:     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);
                   7070:     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);
                   7071:     fflush(stdout);
                   7072:     fclose (ficlog);
                   7073:     goto end;
                   7074:   }
1.126     brouard  7075:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7076:   delti=delti3[1][1];
                   7077:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7078:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7079:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7080:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7081:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7082:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7083:     fclose (ficparo);
                   7084:     fclose (ficlog);
                   7085:     goto end;
                   7086:     exit(0);
                   7087:   }
1.186     brouard  7088:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7089:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7090:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7091:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7092:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7093:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7094:     hess=matrix(1,npar,1,npar);
1.126     brouard  7095:   }
                   7096:   else{
1.145     brouard  7097:     /* Read guessed parameters */
1.126     brouard  7098:     /* Reads comments: lines beginning with '#' */
                   7099:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7100:       ungetc(c,ficpar);
                   7101:       fgets(line, MAXLINE, ficpar);
                   7102:       numlinepar++;
1.141     brouard  7103:       fputs(line,stdout);
1.126     brouard  7104:       fputs(line,ficparo);
                   7105:       fputs(line,ficlog);
                   7106:     }
                   7107:     ungetc(c,ficpar);
                   7108:     
                   7109:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7110:     for(i=1; i <=nlstate; i++){
                   7111:       j=0;
                   7112:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7113:        if(jj==i) continue;
                   7114:        j++;
                   7115:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7116:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7117:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7118: It might be a problem of design; if ncovcol and the model are correct\n \
                   7119: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7120:          exit(1);
                   7121:        }
                   7122:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7123:        if(mle==1)
1.193     brouard  7124:          printf("%1d%1d",i,jj);
                   7125:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7126:        for(k=1; k<=ncovmodel;k++){
                   7127:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7128:          if(mle==1){
                   7129:            printf(" %lf",param[i][j][k]);
                   7130:            fprintf(ficlog," %lf",param[i][j][k]);
                   7131:          }
                   7132:          else
                   7133:            fprintf(ficlog," %lf",param[i][j][k]);
                   7134:          fprintf(ficparo," %lf",param[i][j][k]);
                   7135:        }
                   7136:        fscanf(ficpar,"\n");
                   7137:        numlinepar++;
                   7138:        if(mle==1)
                   7139:          printf("\n");
                   7140:        fprintf(ficlog,"\n");
                   7141:        fprintf(ficparo,"\n");
                   7142:       }
                   7143:     }  
                   7144:     fflush(ficlog);
                   7145: 
1.145     brouard  7146:     /* Reads scales values */
1.126     brouard  7147:     p=param[1][1];
                   7148:     
                   7149:     /* Reads comments: lines beginning with '#' */
                   7150:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7151:       ungetc(c,ficpar);
                   7152:       fgets(line, MAXLINE, ficpar);
                   7153:       numlinepar++;
1.141     brouard  7154:       fputs(line,stdout);
1.126     brouard  7155:       fputs(line,ficparo);
                   7156:       fputs(line,ficlog);
                   7157:     }
                   7158:     ungetc(c,ficpar);
                   7159: 
                   7160:     for(i=1; i <=nlstate; i++){
                   7161:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7162:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7163:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7164:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7165:          exit(1);
                   7166:        }
                   7167:        printf("%1d%1d",i,j);
                   7168:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7169:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7170:        for(k=1; k<=ncovmodel;k++){
                   7171:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7172:          printf(" %le",delti3[i][j][k]);
                   7173:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7174:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7175:        }
                   7176:        fscanf(ficpar,"\n");
                   7177:        numlinepar++;
                   7178:        printf("\n");
                   7179:        fprintf(ficparo,"\n");
                   7180:        fprintf(ficlog,"\n");
                   7181:       }
                   7182:     }
                   7183:     fflush(ficlog);
                   7184: 
1.145     brouard  7185:     /* Reads covariance matrix */
1.126     brouard  7186:     delti=delti3[1][1];
                   7187: 
                   7188: 
                   7189:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7190:   
                   7191:     /* Reads comments: lines beginning with '#' */
                   7192:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7193:       ungetc(c,ficpar);
                   7194:       fgets(line, MAXLINE, ficpar);
                   7195:       numlinepar++;
1.141     brouard  7196:       fputs(line,stdout);
1.126     brouard  7197:       fputs(line,ficparo);
                   7198:       fputs(line,ficlog);
                   7199:     }
                   7200:     ungetc(c,ficpar);
                   7201:   
                   7202:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7203:     hess=matrix(1,npar,1,npar);
1.131     brouard  7204:     for(i=1; i <=npar; i++)
                   7205:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7206:       
1.194     brouard  7207:     /* Scans npar lines */
1.126     brouard  7208:     for(i=1; i <=npar; i++){
1.194     brouard  7209:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7210:       if(count != 3){
                   7211:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7212: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7213: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7214:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7215: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7216: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7217:        exit(1);
                   7218:       }else
1.126     brouard  7219:       if(mle==1)
1.194     brouard  7220:        printf("%1d%1d%1d",i1,j1,jk);
                   7221:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7222:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7223:       for(j=1; j <=i; j++){
                   7224:        fscanf(ficpar," %le",&matcov[i][j]);
                   7225:        if(mle==1){
                   7226:          printf(" %.5le",matcov[i][j]);
                   7227:        }
                   7228:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7229:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7230:       }
                   7231:       fscanf(ficpar,"\n");
                   7232:       numlinepar++;
                   7233:       if(mle==1)
                   7234:        printf("\n");
                   7235:       fprintf(ficlog,"\n");
                   7236:       fprintf(ficparo,"\n");
                   7237:     }
1.194     brouard  7238:     /* End of read covariance matrix npar lines */
1.126     brouard  7239:     for(i=1; i <=npar; i++)
                   7240:       for(j=i+1;j<=npar;j++)
                   7241:        matcov[i][j]=matcov[j][i];
                   7242:     
                   7243:     if(mle==1)
                   7244:       printf("\n");
                   7245:     fprintf(ficlog,"\n");
                   7246:     
                   7247:     fflush(ficlog);
                   7248:     
                   7249:     /*-------- Rewriting parameter file ----------*/
                   7250:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7251:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7252:     strcat(rfileres,".");    /* */
                   7253:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7254:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7255:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7256:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7257:     }
                   7258:     fprintf(ficres,"#%s\n",version);
                   7259:   }    /* End of mle != -3 */
                   7260: 
1.186     brouard  7261:   /*  Main data
                   7262:    */
1.126     brouard  7263:   n= lastobs;
                   7264:   num=lvector(1,n);
                   7265:   moisnais=vector(1,n);
                   7266:   annais=vector(1,n);
                   7267:   moisdc=vector(1,n);
                   7268:   andc=vector(1,n);
                   7269:   agedc=vector(1,n);
                   7270:   cod=ivector(1,n);
                   7271:   weight=vector(1,n);
                   7272:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7273:   mint=matrix(1,maxwav,1,n);
                   7274:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7275:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7276:   tab=ivector(1,NCOVMAX);
1.144     brouard  7277:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7278:   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  7279: 
1.136     brouard  7280:   /* Reads data from file datafile */
                   7281:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7282:     goto end;
                   7283: 
                   7284:   /* Calculation of the number of parameters from char model */
1.137     brouard  7285:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7286:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7287:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7288:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7289:        k=1 Tvar[1]=2 (from V2)
                   7290:     */
                   7291:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7292:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7293:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7294:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7295:   */
                   7296:   /* For model-covariate k tells which data-covariate to use but
                   7297:     because this model-covariate is a construction we invent a new column
                   7298:     ncovcol + k1
                   7299:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7300:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7301:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7302:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7303:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7304:   */
1.145     brouard  7305:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7306:   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  7307:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7308:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7309:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7310:                         4 covariates (3 plus signs)
                   7311:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7312:                      */  
1.136     brouard  7313: 
1.186     brouard  7314: /* Main decodemodel */
                   7315: 
1.187     brouard  7316: 
1.136     brouard  7317:   if(decodemodel(model, lastobs) == 1)
                   7318:     goto end;
                   7319: 
1.137     brouard  7320:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7321:     nbwarn++;
                   7322:     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); 
                   7323:     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); 
                   7324:   }
1.136     brouard  7325:     /*  if(mle==1){*/
1.137     brouard  7326:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7327:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7328:   }
                   7329: 
                   7330:     /*-calculation of age at interview from date of interview and age at death -*/
                   7331:   agev=matrix(1,maxwav,1,imx);
                   7332: 
                   7333:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7334:     goto end;
                   7335: 
1.126     brouard  7336: 
1.136     brouard  7337:   agegomp=(int)agemin;
                   7338:   free_vector(moisnais,1,n);
                   7339:   free_vector(annais,1,n);
1.126     brouard  7340:   /* free_matrix(mint,1,maxwav,1,n);
                   7341:      free_matrix(anint,1,maxwav,1,n);*/
                   7342:   free_vector(moisdc,1,n);
                   7343:   free_vector(andc,1,n);
1.145     brouard  7344:   /* */
                   7345:   
1.126     brouard  7346:   wav=ivector(1,imx);
                   7347:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7348:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7349:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7350:    
                   7351:   /* Concatenates waves */
                   7352:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7353:   /* */
                   7354:  
1.126     brouard  7355:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7356: 
                   7357:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7358:   ncodemax[1]=1;
1.145     brouard  7359:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7360:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7361:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7362:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7363:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7364:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7365: 
1.200     brouard  7366:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7367:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7368:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7369:   h=0;
                   7370: 
                   7371: 
                   7372:   /*if (cptcovn > 0) */
1.126     brouard  7373:       
1.145     brouard  7374:  
1.126     brouard  7375:   m=pow(2,cptcoveff);
                   7376:  
1.144     brouard  7377:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7378:           * For k=4 covariates, h goes from 1 to 2**k
                   7379:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7380:           *     h\k   1     2     3     4
1.143     brouard  7381:           *______________________________  
                   7382:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7383:           *     2     2     1     1     1
                   7384:           *     3 i=2 1     2     1     1
                   7385:           *     4     2     2     1     1
                   7386:           *     5 i=3 1 i=2 1     2     1
                   7387:           *     6     2     1     2     1
                   7388:           *     7 i=4 1     2     2     1
                   7389:           *     8     2     2     2     1
1.197     brouard  7390:           *     9 i=5 1 i=3 1 i=2 1     2
                   7391:           *    10     2     1     1     2
                   7392:           *    11 i=6 1     2     1     2
                   7393:           *    12     2     2     1     2
                   7394:           *    13 i=7 1 i=4 1     2     2    
                   7395:           *    14     2     1     2     2
                   7396:           *    15 i=8 1     2     2     2
                   7397:           *    16     2     2     2     2
1.143     brouard  7398:           */
1.202     brouard  7399:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7400:   /*   /\* printf("h=%2d ", h); *\/ */
                   7401:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7402:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7403:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7404:   /*    /\* } *\/ */
                   7405:   /*    /\* printf("\n"); *\/ */
                   7406:   /* } */
1.197     brouard  7407:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7408:   /*   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 *\/  */
                   7409:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7410:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7411:   /*     h++; */
                   7412:   /*     if (h>m)  */
                   7413:   /*       h=1; */
                   7414:   /*     codtab[h][k]=j; */
                   7415:   /*     /\* codtab[12][3]=1; *\/ */
                   7416:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7417:   /*     /\* 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]]); *\/ */
                   7418:   /*   }  */
                   7419:   /*     } */
                   7420:   /*   } */
                   7421:   /* }  */
1.126     brouard  7422:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7423:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7424:   /* for(i=1; i <=m ;i++){  */
                   7425:   /*    for(k=1; k <=cptcovn; k++){ */
                   7426:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7427:   /*    } */
                   7428:   /*    printf("\n"); */
                   7429:   /* } */
                   7430:   /*   scanf("%d",i);*/
1.145     brouard  7431: 
                   7432:  free_ivector(Ndum,-1,NCOVMAX);
                   7433: 
                   7434: 
1.126     brouard  7435:     
1.186     brouard  7436:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7437:   strcpy(optionfilegnuplot,optionfilefiname);
                   7438:   if(mle==-3)
1.201     brouard  7439:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7440:   strcat(optionfilegnuplot,".gp");
                   7441: 
                   7442:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7443:     printf("Problem with file %s",optionfilegnuplot);
                   7444:   }
                   7445:   else{
1.204     brouard  7446:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7447:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7448:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7449:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7450:   }
                   7451:   /*  fclose(ficgp);*/
1.186     brouard  7452: 
                   7453: 
                   7454:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7455: 
                   7456:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7457:   if(mle==-3)
1.201     brouard  7458:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7459:   strcat(optionfilehtm,".htm");
                   7460:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7461:     printf("Problem with %s \n",optionfilehtm);
                   7462:     exit(0);
1.126     brouard  7463:   }
                   7464: 
                   7465:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7466:   strcat(optionfilehtmcov,"-cov.htm");
                   7467:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7468:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7469:   }
                   7470:   else{
                   7471:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7472: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7473: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7474:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7475:   }
                   7476: 
1.204     brouard  7477:   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>  \
                   7478: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7479: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7480: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7481: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7482: \n\
                   7483: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7484:  <ul><li><h4>Parameter files</h4>\n\
                   7485:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7486:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7487:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7488:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7489:  - Date and time at start: %s</ul>\n",\
                   7490:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7491:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7492:          fileres,fileres,\
                   7493:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7494:   fflush(fichtm);
                   7495: 
                   7496:   strcpy(pathr,path);
                   7497:   strcat(pathr,optionfilefiname);
1.184     brouard  7498: #ifdef WIN32
                   7499:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7500: #else
1.126     brouard  7501:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7502: #endif
                   7503:          
1.126     brouard  7504:   
                   7505:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7506:      and prints on file fileres'p'. */
                   7507:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7508: 
                   7509:   fprintf(fichtm,"\n");
                   7510:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7511: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7512: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7513:          imx,agemin,agemax,jmin,jmax,jmean);
                   7514:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7515:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7516:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7517:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7518:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7519:     
                   7520:    
                   7521:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7522:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7523:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7524: 
                   7525:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7526:   /* For mortality only */
1.126     brouard  7527:   if (mle==-3){
1.136     brouard  7528:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7529:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7530:     cens=ivector(1,n);
                   7531:     ageexmed=vector(1,n);
                   7532:     agecens=vector(1,n);
                   7533:     dcwave=ivector(1,n);
                   7534:  
                   7535:     for (i=1; i<=imx; i++){
                   7536:       dcwave[i]=-1;
                   7537:       for (m=firstpass; m<=lastpass; m++)
                   7538:        if (s[m][i]>nlstate) {
                   7539:          dcwave[i]=m;
                   7540:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7541:          break;
                   7542:        }
                   7543:     }
                   7544: 
                   7545:     for (i=1; i<=imx; i++) {
                   7546:       if (wav[i]>0){
                   7547:        ageexmed[i]=agev[mw[1][i]][i];
                   7548:        j=wav[i];
                   7549:        agecens[i]=1.; 
                   7550: 
                   7551:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7552:          agecens[i]=agev[mw[j][i]][i];
                   7553:          cens[i]= 1;
                   7554:        }else if (ageexmed[i]< 1) 
                   7555:          cens[i]= -1;
                   7556:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7557:          cens[i]=0 ;
                   7558:       }
                   7559:       else cens[i]=-1;
                   7560:     }
                   7561:     
                   7562:     for (i=1;i<=NDIM;i++) {
                   7563:       for (j=1;j<=NDIM;j++)
                   7564:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7565:     }
                   7566:     
1.145     brouard  7567:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7568:     /*printf("%lf %lf", p[1], p[2]);*/
                   7569:     
                   7570:     
1.136     brouard  7571: #ifdef GSL
                   7572:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7573: #else
1.126     brouard  7574:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7575: #endif
1.201     brouard  7576:     strcpy(filerespow,"POW-MORT_"); 
                   7577:     strcat(filerespow,fileresu);
1.126     brouard  7578:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7579:       printf("Problem with resultfile: %s\n", filerespow);
                   7580:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7581:     }
1.136     brouard  7582: #ifdef GSL
                   7583:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7584: #else
1.126     brouard  7585:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7586: #endif
1.126     brouard  7587:     /*  for (i=1;i<=nlstate;i++)
                   7588:        for(j=1;j<=nlstate+ndeath;j++)
                   7589:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7590:     */
                   7591:     fprintf(ficrespow,"\n");
1.136     brouard  7592: #ifdef GSL
                   7593:     /* gsl starts here */ 
                   7594:     T = gsl_multimin_fminimizer_nmsimplex;
                   7595:     gsl_multimin_fminimizer *sfm = NULL;
                   7596:     gsl_vector *ss, *x;
                   7597:     gsl_multimin_function minex_func;
                   7598: 
                   7599:     /* Initial vertex size vector */
                   7600:     ss = gsl_vector_alloc (NDIM);
                   7601:     
                   7602:     if (ss == NULL){
                   7603:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7604:     }
                   7605:     /* Set all step sizes to 1 */
                   7606:     gsl_vector_set_all (ss, 0.001);
                   7607: 
                   7608:     /* Starting point */
1.126     brouard  7609:     
1.136     brouard  7610:     x = gsl_vector_alloc (NDIM);
                   7611:     
                   7612:     if (x == NULL){
                   7613:       gsl_vector_free(ss);
                   7614:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7615:     }
                   7616:   
                   7617:     /* Initialize method and iterate */
                   7618:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7619:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7620:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7621:     gsl_vector_set(x, 0, p[1]);
                   7622:     gsl_vector_set(x, 1, p[2]);
                   7623: 
                   7624:     minex_func.f = &gompertz_f;
                   7625:     minex_func.n = NDIM;
                   7626:     minex_func.params = (void *)&p; /* ??? */
                   7627:     
                   7628:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7629:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7630:     
                   7631:     printf("Iterations beginning .....\n\n");
                   7632:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7633: 
                   7634:     iteri=0;
                   7635:     while (rval == GSL_CONTINUE){
                   7636:       iteri++;
                   7637:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7638:       
                   7639:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7640:       fflush(0);
                   7641:       
                   7642:       if (status) 
                   7643:         break;
                   7644:       
                   7645:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7646:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7647:       
                   7648:       if (rval == GSL_SUCCESS)
                   7649:         printf ("converged to a local maximum at\n");
                   7650:       
                   7651:       printf("%5d ", iteri);
                   7652:       for (it = 0; it < NDIM; it++){
                   7653:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7654:       }
                   7655:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7656:     }
                   7657:     
                   7658:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7659:     
                   7660:     gsl_vector_free(x); /* initial values */
                   7661:     gsl_vector_free(ss); /* inital step size */
                   7662:     for (it=0; it<NDIM; it++){
                   7663:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7664:       fprintf(ficrespow," %.12lf", p[it]);
                   7665:     }
                   7666:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7667: #endif
                   7668: #ifdef POWELL
                   7669:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7670: #endif  
1.126     brouard  7671:     fclose(ficrespow);
                   7672:     
1.203     brouard  7673:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7674: 
                   7675:     for(i=1; i <=NDIM; i++)
                   7676:       for(j=i+1;j<=NDIM;j++)
                   7677:        matcov[i][j]=matcov[j][i];
                   7678:     
                   7679:     printf("\nCovariance matrix\n ");
1.203     brouard  7680:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7681:     for(i=1; i <=NDIM; i++) {
                   7682:       for(j=1;j<=NDIM;j++){ 
                   7683:        printf("%f ",matcov[i][j]);
1.203     brouard  7684:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7685:       }
1.203     brouard  7686:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7687:     }
                   7688:     
                   7689:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7690:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7691:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7692:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7693:     }
1.126     brouard  7694:     lsurv=vector(1,AGESUP);
                   7695:     lpop=vector(1,AGESUP);
                   7696:     tpop=vector(1,AGESUP);
                   7697:     lsurv[agegomp]=100000;
                   7698:     
                   7699:     for (k=agegomp;k<=AGESUP;k++) {
                   7700:       agemortsup=k;
                   7701:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7702:     }
                   7703:     
                   7704:     for (k=agegomp;k<agemortsup;k++)
                   7705:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7706:     
                   7707:     for (k=agegomp;k<agemortsup;k++){
                   7708:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7709:       sumlpop=sumlpop+lpop[k];
                   7710:     }
                   7711:     
                   7712:     tpop[agegomp]=sumlpop;
                   7713:     for (k=agegomp;k<(agemortsup-3);k++){
                   7714:       /*  tpop[k+1]=2;*/
                   7715:       tpop[k+1]=tpop[k]-lpop[k];
                   7716:     }
                   7717:     
                   7718:     
                   7719:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7720:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7721:       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]);
                   7722:     
                   7723:     
                   7724:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7725:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7726:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7727: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7728: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7729:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7730: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7731: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7732:     }else
1.201     brouard  7733:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7734:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7735:                     stepm, weightopt,\
                   7736:                     model,imx,p,matcov,agemortsup);
                   7737:     
                   7738:     free_vector(lsurv,1,AGESUP);
                   7739:     free_vector(lpop,1,AGESUP);
                   7740:     free_vector(tpop,1,AGESUP);
1.136     brouard  7741: #ifdef GSL
                   7742:     free_ivector(cens,1,n);
                   7743:     free_vector(agecens,1,n);
                   7744:     free_ivector(dcwave,1,n);
                   7745:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7746: #endif
1.186     brouard  7747:   } /* Endof if mle==-3 mortality only */
1.205     brouard  7748:   /* Standard  */
                   7749:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   7750:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7751:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  7752:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7753:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7754:     for (k=1; k<=npar;k++)
                   7755:       printf(" %d %8.5f",k,p[k]);
                   7756:     printf("\n");
1.205     brouard  7757:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   7758:       /* mlikeli uses func not funcone */
                   7759:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7760:     }
                   7761:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   7762:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7763:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   7764:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7765:     }
                   7766:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  7767:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7768:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7769:     for (k=1; k<=npar;k++)
                   7770:       printf(" %d %8.5f",k,p[k]);
                   7771:     printf("\n");
                   7772:     
                   7773:     /*--------- results files --------------*/
1.192     brouard  7774:     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  7775:     
                   7776:     
                   7777:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7778:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7779:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7780:     for(i=1,jk=1; i <=nlstate; i++){
                   7781:       for(k=1; k <=(nlstate+ndeath); k++){
                   7782:        if (k != i) {
                   7783:          printf("%d%d ",i,k);
                   7784:          fprintf(ficlog,"%d%d ",i,k);
                   7785:          fprintf(ficres,"%1d%1d ",i,k);
                   7786:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7787:            printf("%12.7f ",p[jk]);
                   7788:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7789:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7790:            jk++; 
                   7791:          }
                   7792:          printf("\n");
                   7793:          fprintf(ficlog,"\n");
                   7794:          fprintf(ficres,"\n");
                   7795:        }
                   7796:       }
                   7797:     }
1.203     brouard  7798:     if(mle != 0){
                   7799:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  7800:       ftolhess=ftol; /* Usually correct */
1.203     brouard  7801:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   7802:       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");
                   7803:       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");
                   7804:       for(i=1,jk=1; i <=nlstate; i++){
                   7805:        for(k=1; k <=(nlstate+ndeath); k++){
                   7806:          if (k != i) {
                   7807:            printf("%d%d ",i,k);
                   7808:            fprintf(ficlog,"%d%d ",i,k);
                   7809:            for(j=1; j <=ncovmodel; j++){
                   7810:              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]));
                   7811:              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]));
                   7812:              jk++; 
                   7813:            }
                   7814:            printf("\n");
                   7815:            fprintf(ficlog,"\n");
1.193     brouard  7816:          }
                   7817:        }
                   7818:       }
1.203     brouard  7819:     } /* end of hesscov and Wald tests */
1.193     brouard  7820: 
1.203     brouard  7821:     /*  */
1.126     brouard  7822:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7823:     printf("# Scales (for hessian or gradient estimation)\n");
                   7824:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7825:     for(i=1,jk=1; i <=nlstate; i++){
                   7826:       for(j=1; j <=nlstate+ndeath; j++){
                   7827:        if (j!=i) {
                   7828:          fprintf(ficres,"%1d%1d",i,j);
                   7829:          printf("%1d%1d",i,j);
                   7830:          fprintf(ficlog,"%1d%1d",i,j);
                   7831:          for(k=1; k<=ncovmodel;k++){
                   7832:            printf(" %.5e",delti[jk]);
                   7833:            fprintf(ficlog," %.5e",delti[jk]);
                   7834:            fprintf(ficres," %.5e",delti[jk]);
                   7835:            jk++;
                   7836:          }
                   7837:          printf("\n");
                   7838:          fprintf(ficlog,"\n");
                   7839:          fprintf(ficres,"\n");
                   7840:        }
                   7841:       }
                   7842:     }
                   7843:     
                   7844:     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  7845:     if(mle >= 1) /* To big for the screen */
1.126     brouard  7846:       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");
                   7847:     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");
                   7848:     /* # 121 Var(a12)\n\ */
                   7849:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7850:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7851:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7852:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7853:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7854:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7855:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7856:     
                   7857:     
                   7858:     /* Just to have a covariance matrix which will be more understandable
                   7859:        even is we still don't want to manage dictionary of variables
                   7860:     */
                   7861:     for(itimes=1;itimes<=2;itimes++){
                   7862:       jj=0;
                   7863:       for(i=1; i <=nlstate; i++){
                   7864:        for(j=1; j <=nlstate+ndeath; j++){
                   7865:          if(j==i) continue;
                   7866:          for(k=1; k<=ncovmodel;k++){
                   7867:            jj++;
                   7868:            ca[0]= k+'a'-1;ca[1]='\0';
                   7869:            if(itimes==1){
                   7870:              if(mle>=1)
                   7871:                printf("#%1d%1d%d",i,j,k);
                   7872:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7873:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7874:            }else{
                   7875:              if(mle>=1)
                   7876:                printf("%1d%1d%d",i,j,k);
                   7877:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7878:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7879:            }
                   7880:            ll=0;
                   7881:            for(li=1;li <=nlstate; li++){
                   7882:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7883:                if(lj==li) continue;
                   7884:                for(lk=1;lk<=ncovmodel;lk++){
                   7885:                  ll++;
                   7886:                  if(ll<=jj){
                   7887:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7888:                    if(ll<jj){
                   7889:                      if(itimes==1){
                   7890:                        if(mle>=1)
                   7891:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7892:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7893:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7894:                      }else{
                   7895:                        if(mle>=1)
                   7896:                          printf(" %.5e",matcov[jj][ll]); 
                   7897:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7898:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7899:                      }
                   7900:                    }else{
                   7901:                      if(itimes==1){
                   7902:                        if(mle>=1)
                   7903:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7904:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7905:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7906:                      }else{
                   7907:                        if(mle>=1)
1.203     brouard  7908:                          printf(" %.7e",matcov[jj][ll]); 
                   7909:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   7910:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  7911:                      }
                   7912:                    }
                   7913:                  }
                   7914:                } /* end lk */
                   7915:              } /* end lj */
                   7916:            } /* end li */
                   7917:            if(mle>=1)
                   7918:              printf("\n");
                   7919:            fprintf(ficlog,"\n");
                   7920:            fprintf(ficres,"\n");
                   7921:            numlinepar++;
                   7922:          } /* end k*/
                   7923:        } /*end j */
                   7924:       } /* end i */
                   7925:     } /* end itimes */
                   7926:     
                   7927:     fflush(ficlog);
                   7928:     fflush(ficres);
                   7929:     
                   7930:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7931:       ungetc(c,ficpar);
                   7932:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7933:       fputs(line,stdout);
1.126     brouard  7934:       fputs(line,ficparo);
                   7935:     }
                   7936:     ungetc(c,ficpar);
                   7937:     
                   7938:     estepm=0;
                   7939:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7940:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7941:     if (fage <= 2) {
                   7942:       bage = ageminpar;
                   7943:       fage = agemaxpar;
                   7944:     }
                   7945:     
                   7946:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7947:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7948:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7949: 
                   7950:     /* Other stuffs, more or less useful */    
1.126     brouard  7951:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7952:       ungetc(c,ficpar);
                   7953:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7954:       fputs(line,stdout);
1.126     brouard  7955:       fputs(line,ficparo);
                   7956:     }
                   7957:     ungetc(c,ficpar);
                   7958:     
                   7959:     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);
                   7960:     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);
                   7961:     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);
                   7962:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7963:     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);
                   7964:     
                   7965:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7966:       ungetc(c,ficpar);
                   7967:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7968:       fputs(line,stdout);
1.126     brouard  7969:       fputs(line,ficparo);
                   7970:     }
                   7971:     ungetc(c,ficpar);
                   7972:     
                   7973:     
                   7974:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7975:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7976:     
                   7977:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7978:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7979:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7980:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7981:     
                   7982:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7983:       ungetc(c,ficpar);
                   7984:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7985:       fputs(line,stdout);
1.126     brouard  7986:       fputs(line,ficparo);
                   7987:     }
                   7988:     ungetc(c,ficpar);
                   7989:     
                   7990:     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);
                   7991:     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);
                   7992:     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);
                   7993:     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);
                   7994:     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);
                   7995:     /* day and month of proj2 are not used but only year anproj2.*/
                   7996:     
                   7997:     
                   7998:     
1.145     brouard  7999:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8000:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8001:     
                   8002:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8003:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8004:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8005: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8006: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8007:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8008: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8009: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8010:     }else
1.201     brouard  8011:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  8012:     
1.201     brouard  8013:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  8014:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   8015:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   8016:       
                   8017:    /*------------ free_vector  -------------*/
                   8018:    /*  chdir(path); */
                   8019:  
                   8020:     free_ivector(wav,1,imx);
                   8021:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   8022:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   8023:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   8024:     free_lvector(num,1,n);
                   8025:     free_vector(agedc,1,n);
                   8026:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8027:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8028:     fclose(ficparo);
                   8029:     fclose(ficres);
                   8030: 
                   8031: 
1.186     brouard  8032:     /* Other results (useful)*/
                   8033: 
                   8034: 
1.126     brouard  8035:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8036:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8037:     prlim=matrix(1,nlstate,1,nlstate);
1.203     brouard  8038:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, ncvyear);
1.126     brouard  8039:     fclose(ficrespl);
                   8040: 
1.145     brouard  8041: #ifdef FREEEXIT2
                   8042: #include "freeexit2.h"
                   8043: #endif
                   8044: 
1.126     brouard  8045:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8046:     /*#include "hpijx.h"*/
                   8047:     hPijx(p, bage, fage);
1.145     brouard  8048:     fclose(ficrespij);
1.126     brouard  8049: 
1.145     brouard  8050:   /*-------------- Variance of one-step probabilities---*/
                   8051:     k=1;
1.126     brouard  8052:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8053: 
                   8054: 
                   8055:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8056:     for(i=1;i<=AGESUP;i++)
                   8057:       for(j=1;j<=NCOVMAX;j++)
                   8058:        for(k=1;k<=NCOVMAX;k++)
                   8059:          probs[i][j][k]=0.;
                   8060: 
                   8061:     /*---------- Forecasting ------------------*/
                   8062:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8063:     if(prevfcast==1){
                   8064:       /*    if(stepm ==1){*/
1.201     brouard  8065:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8066:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8067:       /*      }  */
                   8068:       /*      else{ */
                   8069:       /*        erreur=108; */
                   8070:       /*        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); */
                   8071:       /*        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); */
                   8072:       /*      } */
                   8073:     }
1.186     brouard  8074:  
                   8075:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8076: 
1.127     brouard  8077:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8078: 
                   8079:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8080:     /*  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",\
                   8081:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8082:     */
1.126     brouard  8083: 
1.127     brouard  8084:     if (mobilav!=0) {
                   8085:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8086:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8087:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8088:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8089:       }
1.126     brouard  8090:     }
                   8091: 
                   8092: 
1.127     brouard  8093:     /*---------- Health expectancies, no variances ------------*/
                   8094: 
1.201     brouard  8095:     strcpy(filerese,"E_");
                   8096:     strcat(filerese,fileresu);
1.126     brouard  8097:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8098:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8099:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8100:     }
1.208   ! brouard  8101:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
        !          8102:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8103:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8104:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8105:           
                   8106:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8107:        fprintf(ficreseij,"\n#****** ");
                   8108:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8109:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8110:        }
                   8111:        fprintf(ficreseij,"******\n");
                   8112: 
                   8113:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8114:        oldm=oldms;savm=savms;
                   8115:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8116:       
                   8117:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8118:       /*}*/
1.127     brouard  8119:     }
                   8120:     fclose(ficreseij);
1.208   ! brouard  8121:     printf("done evsij\n");fflush(stdout);
        !          8122:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8123: 
                   8124:     /*---------- Health expectancies and variances ------------*/
                   8125: 
                   8126: 
1.201     brouard  8127:     strcpy(filerest,"T_");
                   8128:     strcat(filerest,fileresu);
1.127     brouard  8129:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8130:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8131:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8132:     }
1.208   ! brouard  8133:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
        !          8134:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8135: 
1.126     brouard  8136: 
1.201     brouard  8137:     strcpy(fileresstde,"STDE_");
                   8138:     strcat(fileresstde,fileresu);
1.126     brouard  8139:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8140:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8141:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8142:     }
1.208   ! brouard  8143:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
        !          8144:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8145: 
1.201     brouard  8146:     strcpy(filerescve,"CVE_");
                   8147:     strcat(filerescve,fileresu);
1.126     brouard  8148:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8149:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8150:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8151:     }
1.208   ! brouard  8152:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
        !          8153:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8154: 
1.201     brouard  8155:     strcpy(fileresv,"V_");
                   8156:     strcat(fileresv,fileresu);
1.126     brouard  8157:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8158:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8159:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8160:     }
1.208   ! brouard  8161:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
        !          8162:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  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++){
1.208   ! brouard  8168:       fprintf(ficrest,"\n#****** ");
        !          8169:       for(j=1;j<=cptcoveff;j++) 
        !          8170:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          8171:       fprintf(ficrest,"******\n");
        !          8172:       
        !          8173:       fprintf(ficresstdeij,"\n#****** ");
        !          8174:       fprintf(ficrescveij,"\n#****** ");
        !          8175:       for(j=1;j<=cptcoveff;j++) {
        !          8176:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          8177:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          8178:       }
        !          8179:       fprintf(ficresstdeij,"******\n");
        !          8180:       fprintf(ficrescveij,"******\n");
        !          8181:       
        !          8182:       fprintf(ficresvij,"\n#****** ");
        !          8183:       for(j=1;j<=cptcoveff;j++) 
        !          8184:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          8185:       fprintf(ficresvij,"******\n");
        !          8186:       
        !          8187:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
        !          8188:       oldm=oldms;savm=savms;
        !          8189:       printf(" cvevsij %d, ",k);
        !          8190:       fprintf(ficlog, " cvevsij %d, ",k);
        !          8191:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
        !          8192:       printf(" end cvevsij \n ");
        !          8193:       fprintf(ficlog, " end cvevsij \n ");
        !          8194:       
        !          8195:       /*
        !          8196:        */
        !          8197:       /* goto endfree; */
        !          8198:       
        !          8199:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
        !          8200:       pstamp(ficrest);
        !          8201:       
        !          8202:       
        !          8203:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
        !          8204:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
        !          8205:        cptcod= 0; /* To be deleted */
        !          8206:        printf("varevsij %d \n",vpopbased);
        !          8207:        fprintf(ficlog, "varevsij %d \n",vpopbased);
        !          8208:        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 */
        !          8209:        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 ");
        !          8210:        if(vpopbased==1)
        !          8211:          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);
        !          8212:        else
        !          8213:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
        !          8214:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
        !          8215:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
        !          8216:        fprintf(ficrest,"\n");
        !          8217:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
        !          8218:        epj=vector(1,nlstate+1);
        !          8219:        printf("Computing age specific period (stable) prevalences in each health state \n");
        !          8220:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
        !          8221:        for(age=bage; age <=fage ;age++){
        !          8222:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
        !          8223:          if (vpopbased==1) {
        !          8224:            if(mobilav ==0){
        !          8225:              for(i=1; i<=nlstate;i++)
        !          8226:                prlim[i][i]=probs[(int)age][i][k];
        !          8227:            }else{ /* mobilav */ 
        !          8228:              for(i=1; i<=nlstate;i++)
        !          8229:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8230:            }
1.208   ! brouard  8231:          }
        !          8232:          
        !          8233:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
        !          8234:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
        !          8235:          /* printf(" age %4.0f ",age); */
        !          8236:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
        !          8237:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
        !          8238:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
        !          8239:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
        !          8240:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8241:            }
1.208   ! brouard  8242:            epj[nlstate+1] +=epj[j];
        !          8243:          }
        !          8244:          /* printf(" age %4.0f \n",age); */
        !          8245:          
        !          8246:          for(i=1, vepp=0.;i <=nlstate;i++)
        !          8247:            for(j=1;j <=nlstate;j++)
        !          8248:              vepp += vareij[i][j][(int)age];
        !          8249:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
        !          8250:          for(j=1;j <=nlstate;j++){
        !          8251:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8252:          }
1.208   ! brouard  8253:          fprintf(ficrest,"\n");
1.126     brouard  8254:        }
1.208   ! brouard  8255:       } /* End vpopbased */
        !          8256:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
        !          8257:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
        !          8258:       free_vector(epj,1,nlstate+1);
        !          8259:       printf("done \n");fflush(stdout);
        !          8260:       fprintf(ficlog,"done\n");fflush(ficlog);
        !          8261:       
1.145     brouard  8262:       /*}*/
1.208   ! brouard  8263:     } /* End k */
1.126     brouard  8264:     free_vector(weight,1,n);
1.145     brouard  8265:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8266:     free_imatrix(s,1,maxwav+1,1,n);
                   8267:     free_matrix(anint,1,maxwav,1,n); 
                   8268:     free_matrix(mint,1,maxwav,1,n);
                   8269:     free_ivector(cod,1,n);
                   8270:     free_ivector(tab,1,NCOVMAX);
                   8271:     fclose(ficresstdeij);
                   8272:     fclose(ficrescveij);
                   8273:     fclose(ficresvij);
                   8274:     fclose(ficrest);
1.208   ! brouard  8275:     printf("done Health expectancies\n");fflush(stdout);
        !          8276:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8277:     fclose(ficpar);
                   8278:   
                   8279:     /*------- Variance of period (stable) prevalence------*/   
                   8280: 
1.201     brouard  8281:     strcpy(fileresvpl,"VPL_");
                   8282:     strcat(fileresvpl,fileresu);
1.126     brouard  8283:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8284:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8285:       exit(0);
                   8286:     }
1.208   ! brouard  8287:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
        !          8288:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8289: 
1.145     brouard  8290:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8291:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8292:           
                   8293:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8294:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8295:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8296:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8297:        fprintf(ficresvpl,"******\n");
                   8298:       
                   8299:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8300:        oldm=oldms;savm=savms;
1.203     brouard  8301:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
1.126     brouard  8302:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8303:       /*}*/
1.126     brouard  8304:     }
                   8305: 
                   8306:     fclose(ficresvpl);
1.208   ! brouard  8307:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
        !          8308:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8309: 
                   8310:     /*---------- End : free ----------------*/
                   8311:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8312:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8313:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8314:  /* endfree:*/
1.141     brouard  8315:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8316:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8317:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8318:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8319:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8320:     free_matrix(covar,0,NCOVMAX,1,n);
                   8321:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8322:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8323:     /*free_vector(delti,1,npar);*/
                   8324:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8325:     free_matrix(agev,1,maxwav,1,imx);
                   8326:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8327: 
1.145     brouard  8328:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8329:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8330:     free_ivector(Tvar,1,NCOVMAX);
                   8331:     free_ivector(Tprod,1,NCOVMAX);
                   8332:     free_ivector(Tvaraff,1,NCOVMAX);
                   8333:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8334: 
                   8335:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8336:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8337:   fflush(fichtm);
                   8338:   fflush(ficgp);
                   8339:   
                   8340: 
                   8341:   if((nberr >0) || (nbwarn>0)){
                   8342:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8343:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8344:   }else{
                   8345:     printf("End of Imach\n");
                   8346:     fprintf(ficlog,"End of Imach\n");
                   8347:   }
                   8348:   printf("See log file on %s\n",filelog);
                   8349:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8350:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8351:   rend_time = time(NULL);  
                   8352:   end_time = *localtime(&rend_time);
                   8353:   /* tml = *localtime(&end_time.tm_sec); */
                   8354:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8355:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8356:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8357:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8358: 
1.157     brouard  8359:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8360:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8361:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8362:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8363: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8364:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8365:   fclose(fichtm);
                   8366:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8367:   fclose(fichtmcov);
                   8368:   fclose(ficgp);
                   8369:   fclose(ficlog);
                   8370:   /*------ End -----------*/
                   8371: 
                   8372: 
                   8373:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8374: #ifdef WIN32
                   8375:    if (_chdir(pathcd) != 0)
                   8376:           printf("Can't move to directory %s!\n",path);
                   8377:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8378: #else
1.126     brouard  8379:    if(chdir(pathcd) != 0)
1.184     brouard  8380:           printf("Can't move to directory %s!\n", path);
                   8381:    if (getcwd(pathcd, MAXLINE) > 0)
                   8382: #endif 
1.126     brouard  8383:     printf("Current directory %s!\n",pathcd);
                   8384:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8385:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8386: #ifdef _WIN32
1.126     brouard  8387:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8388: #endif
                   8389:   if(!stat(plotcmd,&info)){
1.158     brouard  8390:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8391:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8392:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8393:     }else
                   8394:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8395: #ifdef __unix
1.126     brouard  8396:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8397:     if(!stat(plotcmd,&info)){
1.158     brouard  8398:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8399:     }else
                   8400:       strcpy(pplotcmd,plotcmd);
                   8401: #endif
                   8402:   }else
                   8403:     strcpy(pplotcmd,plotcmd);
                   8404:   
                   8405:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8406:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8407: 
                   8408:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8409:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8410:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8411:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8412:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8413:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8414:   }
1.158     brouard  8415:   printf(" Successful, please wait...");
1.126     brouard  8416:   while (z[0] != 'q') {
                   8417:     /* chdir(path); */
1.154     brouard  8418:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8419:     scanf("%s",z);
                   8420: /*     if (z[0] == 'c') system("./imach"); */
                   8421:     if (z[0] == 'e') {
1.158     brouard  8422: #ifdef __APPLE__
1.152     brouard  8423:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8424: #elif __linux
                   8425:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8426: #else
1.152     brouard  8427:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8428: #endif
                   8429:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8430:       system(pplotcmd);
1.126     brouard  8431:     }
                   8432:     else if (z[0] == 'g') system(plotcmd);
                   8433:     else if (z[0] == 'q') exit(0);
                   8434:   }
                   8435:   end:
                   8436:   while (z[0] != 'q') {
1.195     brouard  8437:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8438:     scanf("%s",z);
                   8439:   }
                   8440: }

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