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

1.219   ! brouard     1: /* $Id: imach.c,v 1.218 2016/02/12 11:29:23 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.219   ! brouard     4:   Revision 1.218  2016/02/12 11:29:23  brouard
        !             5:   Summary: 0.99 Back projections
        !             6: 
1.218     brouard     7:   Revision 1.217  2015/12/23 17:18:31  brouard
                      8:   Summary: Experimental backcast
                      9: 
1.217     brouard    10:   Revision 1.216  2015/12/18 17:32:11  brouard
                     11:   Summary: 0.98r4 Warning and status=-2
                     12: 
                     13:   Version 0.98r4 is now:
                     14:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     15:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     16:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     17: 
1.216     brouard    18:   Revision 1.215  2015/12/16 08:52:24  brouard
                     19:   Summary: 0.98r4 working
                     20: 
1.215     brouard    21:   Revision 1.214  2015/12/16 06:57:54  brouard
                     22:   Summary: temporary not working
                     23: 
1.214     brouard    24:   Revision 1.213  2015/12/11 18:22:17  brouard
                     25:   Summary: 0.98r4
                     26: 
1.213     brouard    27:   Revision 1.212  2015/11/21 12:47:24  brouard
                     28:   Summary: minor typo
                     29: 
1.212     brouard    30:   Revision 1.211  2015/11/21 12:41:11  brouard
                     31:   Summary: 0.98r3 with some graph of projected cross-sectional
                     32: 
                     33:   Author: Nicolas Brouard
                     34: 
1.211     brouard    35:   Revision 1.210  2015/11/18 17:41:20  brouard
                     36:   Summary: Start working on projected prevalences
                     37: 
1.210     brouard    38:   Revision 1.209  2015/11/17 22:12:03  brouard
                     39:   Summary: Adding ftolpl parameter
                     40:   Author: N Brouard
                     41: 
                     42:   We had difficulties to get smoothed confidence intervals. It was due
                     43:   to the period prevalence which wasn't computed accurately. The inner
                     44:   parameter ftolpl is now an outer parameter of the .imach parameter
                     45:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     46:   computation are long.
                     47: 
1.209     brouard    48:   Revision 1.208  2015/11/17 14:31:57  brouard
                     49:   Summary: temporary
                     50: 
1.208     brouard    51:   Revision 1.207  2015/10/27 17:36:57  brouard
                     52:   *** empty log message ***
                     53: 
1.207     brouard    54:   Revision 1.206  2015/10/24 07:14:11  brouard
                     55:   *** empty log message ***
                     56: 
1.206     brouard    57:   Revision 1.205  2015/10/23 15:50:53  brouard
                     58:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     59: 
1.205     brouard    60:   Revision 1.204  2015/10/01 16:20:26  brouard
                     61:   Summary: Some new graphs of contribution to likelihood
                     62: 
1.204     brouard    63:   Revision 1.203  2015/09/30 17:45:14  brouard
                     64:   Summary: looking at better estimation of the hessian
                     65: 
                     66:   Also a better criteria for convergence to the period prevalence And
                     67:   therefore adding the number of years needed to converge. (The
                     68:   prevalence in any alive state shold sum to one
                     69: 
1.203     brouard    70:   Revision 1.202  2015/09/22 19:45:16  brouard
                     71:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     72: 
1.202     brouard    73:   Revision 1.201  2015/09/15 17:34:58  brouard
                     74:   Summary: 0.98r0
                     75: 
                     76:   - Some new graphs like suvival functions
                     77:   - Some bugs fixed like model=1+age+V2.
                     78: 
1.201     brouard    79:   Revision 1.200  2015/09/09 16:53:55  brouard
                     80:   Summary: Big bug thanks to Flavia
                     81: 
                     82:   Even model=1+age+V2. did not work anymore
                     83: 
1.200     brouard    84:   Revision 1.199  2015/09/07 14:09:23  brouard
                     85:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     86: 
1.199     brouard    87:   Revision 1.198  2015/09/03 07:14:39  brouard
                     88:   Summary: 0.98q5 Flavia
                     89: 
1.198     brouard    90:   Revision 1.197  2015/09/01 18:24:39  brouard
                     91:   *** empty log message ***
                     92: 
1.197     brouard    93:   Revision 1.196  2015/08/18 23:17:52  brouard
                     94:   Summary: 0.98q5
                     95: 
1.196     brouard    96:   Revision 1.195  2015/08/18 16:28:39  brouard
                     97:   Summary: Adding a hack for testing purpose
                     98: 
                     99:   After reading the title, ftol and model lines, if the comment line has
                    100:   a q, starting with #q, the answer at the end of the run is quit. It
                    101:   permits to run test files in batch with ctest. The former workaround was
                    102:   $ echo q | imach foo.imach
                    103: 
1.195     brouard   104:   Revision 1.194  2015/08/18 13:32:00  brouard
                    105:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    106: 
1.194     brouard   107:   Revision 1.193  2015/08/04 07:17:42  brouard
                    108:   Summary: 0.98q4
                    109: 
1.193     brouard   110:   Revision 1.192  2015/07/16 16:49:02  brouard
                    111:   Summary: Fixing some outputs
                    112: 
1.192     brouard   113:   Revision 1.191  2015/07/14 10:00:33  brouard
                    114:   Summary: Some fixes
                    115: 
1.191     brouard   116:   Revision 1.190  2015/05/05 08:51:13  brouard
                    117:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    118: 
                    119:   Fix 1+age+.
                    120: 
1.190     brouard   121:   Revision 1.189  2015/04/30 14:45:16  brouard
                    122:   Summary: 0.98q2
                    123: 
1.189     brouard   124:   Revision 1.188  2015/04/30 08:27:53  brouard
                    125:   *** empty log message ***
                    126: 
1.188     brouard   127:   Revision 1.187  2015/04/29 09:11:15  brouard
                    128:   *** empty log message ***
                    129: 
1.187     brouard   130:   Revision 1.186  2015/04/23 12:01:52  brouard
                    131:   Summary: V1*age is working now, version 0.98q1
                    132: 
                    133:   Some codes had been disabled in order to simplify and Vn*age was
                    134:   working in the optimization phase, ie, giving correct MLE parameters,
                    135:   but, as usual, outputs were not correct and program core dumped.
                    136: 
1.186     brouard   137:   Revision 1.185  2015/03/11 13:26:42  brouard
                    138:   Summary: Inclusion of compile and links command line for Intel Compiler
                    139: 
1.185     brouard   140:   Revision 1.184  2015/03/11 11:52:39  brouard
                    141:   Summary: Back from Windows 8. Intel Compiler
                    142: 
1.184     brouard   143:   Revision 1.183  2015/03/10 20:34:32  brouard
                    144:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    145: 
                    146:   We use directest instead of original Powell test; probably no
                    147:   incidence on the results, but better justifications;
                    148:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    149:   wrong results.
                    150: 
1.183     brouard   151:   Revision 1.182  2015/02/12 08:19:57  brouard
                    152:   Summary: Trying to keep directest which seems simpler and more general
                    153:   Author: Nicolas Brouard
                    154: 
1.182     brouard   155:   Revision 1.181  2015/02/11 23:22:24  brouard
                    156:   Summary: Comments on Powell added
                    157: 
                    158:   Author:
                    159: 
1.181     brouard   160:   Revision 1.180  2015/02/11 17:33:45  brouard
                    161:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    162: 
1.180     brouard   163:   Revision 1.179  2015/01/04 09:57:06  brouard
                    164:   Summary: back to OS/X
                    165: 
1.179     brouard   166:   Revision 1.178  2015/01/04 09:35:48  brouard
                    167:   *** empty log message ***
                    168: 
1.178     brouard   169:   Revision 1.177  2015/01/03 18:40:56  brouard
                    170:   Summary: Still testing ilc32 on OSX
                    171: 
1.177     brouard   172:   Revision 1.176  2015/01/03 16:45:04  brouard
                    173:   *** empty log message ***
                    174: 
1.176     brouard   175:   Revision 1.175  2015/01/03 16:33:42  brouard
                    176:   *** empty log message ***
                    177: 
1.175     brouard   178:   Revision 1.174  2015/01/03 16:15:49  brouard
                    179:   Summary: Still in cross-compilation
                    180: 
1.174     brouard   181:   Revision 1.173  2015/01/03 12:06:26  brouard
                    182:   Summary: trying to detect cross-compilation
                    183: 
1.173     brouard   184:   Revision 1.172  2014/12/27 12:07:47  brouard
                    185:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    186: 
1.172     brouard   187:   Revision 1.171  2014/12/23 13:26:59  brouard
                    188:   Summary: Back from Visual C
                    189: 
                    190:   Still problem with utsname.h on Windows
                    191: 
1.171     brouard   192:   Revision 1.170  2014/12/23 11:17:12  brouard
                    193:   Summary: Cleaning some \%% back to %%
                    194: 
                    195:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    196: 
1.170     brouard   197:   Revision 1.169  2014/12/22 23:08:31  brouard
                    198:   Summary: 0.98p
                    199: 
                    200:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    201: 
1.169     brouard   202:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   203:   Summary: update
1.169     brouard   204: 
1.168     brouard   205:   Revision 1.167  2014/12/22 13:50:56  brouard
                    206:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    207: 
                    208:   Testing on Linux 64
                    209: 
1.167     brouard   210:   Revision 1.166  2014/12/22 11:40:47  brouard
                    211:   *** empty log message ***
                    212: 
1.166     brouard   213:   Revision 1.165  2014/12/16 11:20:36  brouard
                    214:   Summary: After compiling on Visual C
                    215: 
                    216:   * imach.c (Module): Merging 1.61 to 1.162
                    217: 
1.165     brouard   218:   Revision 1.164  2014/12/16 10:52:11  brouard
                    219:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    220: 
                    221:   * imach.c (Module): Merging 1.61 to 1.162
                    222: 
1.164     brouard   223:   Revision 1.163  2014/12/16 10:30:11  brouard
                    224:   * imach.c (Module): Merging 1.61 to 1.162
                    225: 
1.163     brouard   226:   Revision 1.162  2014/09/25 11:43:39  brouard
                    227:   Summary: temporary backup 0.99!
                    228: 
1.162     brouard   229:   Revision 1.1  2014/09/16 11:06:58  brouard
                    230:   Summary: With some code (wrong) for nlopt
                    231: 
                    232:   Author:
                    233: 
                    234:   Revision 1.161  2014/09/15 20:41:41  brouard
                    235:   Summary: Problem with macro SQR on Intel compiler
                    236: 
1.161     brouard   237:   Revision 1.160  2014/09/02 09:24:05  brouard
                    238:   *** empty log message ***
                    239: 
1.160     brouard   240:   Revision 1.159  2014/09/01 10:34:10  brouard
                    241:   Summary: WIN32
                    242:   Author: Brouard
                    243: 
1.159     brouard   244:   Revision 1.158  2014/08/27 17:11:51  brouard
                    245:   *** empty log message ***
                    246: 
1.158     brouard   247:   Revision 1.157  2014/08/27 16:26:55  brouard
                    248:   Summary: Preparing windows Visual studio version
                    249:   Author: Brouard
                    250: 
                    251:   In order to compile on Visual studio, time.h is now correct and time_t
                    252:   and tm struct should be used. difftime should be used but sometimes I
                    253:   just make the differences in raw time format (time(&now).
                    254:   Trying to suppress #ifdef LINUX
                    255:   Add xdg-open for __linux in order to open default browser.
                    256: 
1.157     brouard   257:   Revision 1.156  2014/08/25 20:10:10  brouard
                    258:   *** empty log message ***
                    259: 
1.156     brouard   260:   Revision 1.155  2014/08/25 18:32:34  brouard
                    261:   Summary: New compile, minor changes
                    262:   Author: Brouard
                    263: 
1.155     brouard   264:   Revision 1.154  2014/06/20 17:32:08  brouard
                    265:   Summary: Outputs now all graphs of convergence to period prevalence
                    266: 
1.154     brouard   267:   Revision 1.153  2014/06/20 16:45:46  brouard
                    268:   Summary: If 3 live state, convergence to period prevalence on same graph
                    269:   Author: Brouard
                    270: 
1.153     brouard   271:   Revision 1.152  2014/06/18 17:54:09  brouard
                    272:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    273: 
1.152     brouard   274:   Revision 1.151  2014/06/18 16:43:30  brouard
                    275:   *** empty log message ***
                    276: 
1.151     brouard   277:   Revision 1.150  2014/06/18 16:42:35  brouard
                    278:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    279:   Author: brouard
                    280: 
1.150     brouard   281:   Revision 1.149  2014/06/18 15:51:14  brouard
                    282:   Summary: Some fixes in parameter files errors
                    283:   Author: Nicolas Brouard
                    284: 
1.149     brouard   285:   Revision 1.148  2014/06/17 17:38:48  brouard
                    286:   Summary: Nothing new
                    287:   Author: Brouard
                    288: 
                    289:   Just a new packaging for OS/X version 0.98nS
                    290: 
1.148     brouard   291:   Revision 1.147  2014/06/16 10:33:11  brouard
                    292:   *** empty log message ***
                    293: 
1.147     brouard   294:   Revision 1.146  2014/06/16 10:20:28  brouard
                    295:   Summary: Merge
                    296:   Author: Brouard
                    297: 
                    298:   Merge, before building revised version.
                    299: 
1.146     brouard   300:   Revision 1.145  2014/06/10 21:23:15  brouard
                    301:   Summary: Debugging with valgrind
                    302:   Author: Nicolas Brouard
                    303: 
                    304:   Lot of changes in order to output the results with some covariates
                    305:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    306:   improve the code.
                    307:   No more memory valgrind error but a lot has to be done in order to
                    308:   continue the work of splitting the code into subroutines.
                    309:   Also, decodemodel has been improved. Tricode is still not
                    310:   optimal. nbcode should be improved. Documentation has been added in
                    311:   the source code.
                    312: 
1.144     brouard   313:   Revision 1.143  2014/01/26 09:45:38  brouard
                    314:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    315: 
                    316:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    317:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    318: 
1.143     brouard   319:   Revision 1.142  2014/01/26 03:57:36  brouard
                    320:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    321: 
                    322:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    323: 
1.142     brouard   324:   Revision 1.141  2014/01/26 02:42:01  brouard
                    325:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    326: 
1.141     brouard   327:   Revision 1.140  2011/09/02 10:37:54  brouard
                    328:   Summary: times.h is ok with mingw32 now.
                    329: 
1.140     brouard   330:   Revision 1.139  2010/06/14 07:50:17  brouard
                    331:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    332:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    333: 
1.139     brouard   334:   Revision 1.138  2010/04/30 18:19:40  brouard
                    335:   *** empty log message ***
                    336: 
1.138     brouard   337:   Revision 1.137  2010/04/29 18:11:38  brouard
                    338:   (Module): Checking covariates for more complex models
                    339:   than V1+V2. A lot of change to be done. Unstable.
                    340: 
1.137     brouard   341:   Revision 1.136  2010/04/26 20:30:53  brouard
                    342:   (Module): merging some libgsl code. Fixing computation
                    343:   of likelione (using inter/intrapolation if mle = 0) in order to
                    344:   get same likelihood as if mle=1.
                    345:   Some cleaning of code and comments added.
                    346: 
1.136     brouard   347:   Revision 1.135  2009/10/29 15:33:14  brouard
                    348:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    349: 
1.135     brouard   350:   Revision 1.134  2009/10/29 13:18:53  brouard
                    351:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    352: 
1.134     brouard   353:   Revision 1.133  2009/07/06 10:21:25  brouard
                    354:   just nforces
                    355: 
1.133     brouard   356:   Revision 1.132  2009/07/06 08:22:05  brouard
                    357:   Many tings
                    358: 
1.132     brouard   359:   Revision 1.131  2009/06/20 16:22:47  brouard
                    360:   Some dimensions resccaled
                    361: 
1.131     brouard   362:   Revision 1.130  2009/05/26 06:44:34  brouard
                    363:   (Module): Max Covariate is now set to 20 instead of 8. A
                    364:   lot of cleaning with variables initialized to 0. Trying to make
                    365:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    366: 
1.130     brouard   367:   Revision 1.129  2007/08/31 13:49:27  lievre
                    368:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    369: 
1.129     lievre    370:   Revision 1.128  2006/06/30 13:02:05  brouard
                    371:   (Module): Clarifications on computing e.j
                    372: 
1.128     brouard   373:   Revision 1.127  2006/04/28 18:11:50  brouard
                    374:   (Module): Yes the sum of survivors was wrong since
                    375:   imach-114 because nhstepm was no more computed in the age
                    376:   loop. Now we define nhstepma in the age loop.
                    377:   (Module): In order to speed up (in case of numerous covariates) we
                    378:   compute health expectancies (without variances) in a first step
                    379:   and then all the health expectancies with variances or standard
                    380:   deviation (needs data from the Hessian matrices) which slows the
                    381:   computation.
                    382:   In the future we should be able to stop the program is only health
                    383:   expectancies and graph are needed without standard deviations.
                    384: 
1.127     brouard   385:   Revision 1.126  2006/04/28 17:23:28  brouard
                    386:   (Module): Yes the sum of survivors was wrong since
                    387:   imach-114 because nhstepm was no more computed in the age
                    388:   loop. Now we define nhstepma in the age loop.
                    389:   Version 0.98h
                    390: 
1.126     brouard   391:   Revision 1.125  2006/04/04 15:20:31  lievre
                    392:   Errors in calculation of health expectancies. Age was not initialized.
                    393:   Forecasting file added.
                    394: 
                    395:   Revision 1.124  2006/03/22 17:13:53  lievre
                    396:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    397:   The log-likelihood is printed in the log file
                    398: 
                    399:   Revision 1.123  2006/03/20 10:52:43  brouard
                    400:   * imach.c (Module): <title> changed, corresponds to .htm file
                    401:   name. <head> headers where missing.
                    402: 
                    403:   * imach.c (Module): Weights can have a decimal point as for
                    404:   English (a comma might work with a correct LC_NUMERIC environment,
                    405:   otherwise the weight is truncated).
                    406:   Modification of warning when the covariates values are not 0 or
                    407:   1.
                    408:   Version 0.98g
                    409: 
                    410:   Revision 1.122  2006/03/20 09:45:41  brouard
                    411:   (Module): Weights can have a decimal point as for
                    412:   English (a comma might work with a correct LC_NUMERIC environment,
                    413:   otherwise the weight is truncated).
                    414:   Modification of warning when the covariates values are not 0 or
                    415:   1.
                    416:   Version 0.98g
                    417: 
                    418:   Revision 1.121  2006/03/16 17:45:01  lievre
                    419:   * imach.c (Module): Comments concerning covariates added
                    420: 
                    421:   * imach.c (Module): refinements in the computation of lli if
                    422:   status=-2 in order to have more reliable computation if stepm is
                    423:   not 1 month. Version 0.98f
                    424: 
                    425:   Revision 1.120  2006/03/16 15:10:38  lievre
                    426:   (Module): refinements in the computation of lli if
                    427:   status=-2 in order to have more reliable computation if stepm is
                    428:   not 1 month. Version 0.98f
                    429: 
                    430:   Revision 1.119  2006/03/15 17:42:26  brouard
                    431:   (Module): Bug if status = -2, the loglikelihood was
                    432:   computed as likelihood omitting the logarithm. Version O.98e
                    433: 
                    434:   Revision 1.118  2006/03/14 18:20:07  brouard
                    435:   (Module): varevsij Comments added explaining the second
                    436:   table of variances if popbased=1 .
                    437:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    438:   (Module): Function pstamp added
                    439:   (Module): Version 0.98d
                    440: 
                    441:   Revision 1.117  2006/03/14 17:16:22  brouard
                    442:   (Module): varevsij Comments added explaining the second
                    443:   table of variances if popbased=1 .
                    444:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    445:   (Module): Function pstamp added
                    446:   (Module): Version 0.98d
                    447: 
                    448:   Revision 1.116  2006/03/06 10:29:27  brouard
                    449:   (Module): Variance-covariance wrong links and
                    450:   varian-covariance of ej. is needed (Saito).
                    451: 
                    452:   Revision 1.115  2006/02/27 12:17:45  brouard
                    453:   (Module): One freematrix added in mlikeli! 0.98c
                    454: 
                    455:   Revision 1.114  2006/02/26 12:57:58  brouard
                    456:   (Module): Some improvements in processing parameter
                    457:   filename with strsep.
                    458: 
                    459:   Revision 1.113  2006/02/24 14:20:24  brouard
                    460:   (Module): Memory leaks checks with valgrind and:
                    461:   datafile was not closed, some imatrix were not freed and on matrix
                    462:   allocation too.
                    463: 
                    464:   Revision 1.112  2006/01/30 09:55:26  brouard
                    465:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    466: 
                    467:   Revision 1.111  2006/01/25 20:38:18  brouard
                    468:   (Module): Lots of cleaning and bugs added (Gompertz)
                    469:   (Module): Comments can be added in data file. Missing date values
                    470:   can be a simple dot '.'.
                    471: 
                    472:   Revision 1.110  2006/01/25 00:51:50  brouard
                    473:   (Module): Lots of cleaning and bugs added (Gompertz)
                    474: 
                    475:   Revision 1.109  2006/01/24 19:37:15  brouard
                    476:   (Module): Comments (lines starting with a #) are allowed in data.
                    477: 
                    478:   Revision 1.108  2006/01/19 18:05:42  lievre
                    479:   Gnuplot problem appeared...
                    480:   To be fixed
                    481: 
                    482:   Revision 1.107  2006/01/19 16:20:37  brouard
                    483:   Test existence of gnuplot in imach path
                    484: 
                    485:   Revision 1.106  2006/01/19 13:24:36  brouard
                    486:   Some cleaning and links added in html output
                    487: 
                    488:   Revision 1.105  2006/01/05 20:23:19  lievre
                    489:   *** empty log message ***
                    490: 
                    491:   Revision 1.104  2005/09/30 16:11:43  lievre
                    492:   (Module): sump fixed, loop imx fixed, and simplifications.
                    493:   (Module): If the status is missing at the last wave but we know
                    494:   that the person is alive, then we can code his/her status as -2
                    495:   (instead of missing=-1 in earlier versions) and his/her
                    496:   contributions to the likelihood is 1 - Prob of dying from last
                    497:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    498:   the healthy state at last known wave). Version is 0.98
                    499: 
                    500:   Revision 1.103  2005/09/30 15:54:49  lievre
                    501:   (Module): sump fixed, loop imx fixed, and simplifications.
                    502: 
                    503:   Revision 1.102  2004/09/15 17:31:30  brouard
                    504:   Add the possibility to read data file including tab characters.
                    505: 
                    506:   Revision 1.101  2004/09/15 10:38:38  brouard
                    507:   Fix on curr_time
                    508: 
                    509:   Revision 1.100  2004/07/12 18:29:06  brouard
                    510:   Add version for Mac OS X. Just define UNIX in Makefile
                    511: 
                    512:   Revision 1.99  2004/06/05 08:57:40  brouard
                    513:   *** empty log message ***
                    514: 
                    515:   Revision 1.98  2004/05/16 15:05:56  brouard
                    516:   New version 0.97 . First attempt to estimate force of mortality
                    517:   directly from the data i.e. without the need of knowing the health
                    518:   state at each age, but using a Gompertz model: log u =a + b*age .
                    519:   This is the basic analysis of mortality and should be done before any
                    520:   other analysis, in order to test if the mortality estimated from the
                    521:   cross-longitudinal survey is different from the mortality estimated
                    522:   from other sources like vital statistic data.
                    523: 
                    524:   The same imach parameter file can be used but the option for mle should be -3.
                    525: 
1.133     brouard   526:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   527:   former routines in order to include the new code within the former code.
                    528: 
                    529:   The output is very simple: only an estimate of the intercept and of
                    530:   the slope with 95% confident intervals.
                    531: 
                    532:   Current limitations:
                    533:   A) Even if you enter covariates, i.e. with the
                    534:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    535:   B) There is no computation of Life Expectancy nor Life Table.
                    536: 
                    537:   Revision 1.97  2004/02/20 13:25:42  lievre
                    538:   Version 0.96d. Population forecasting command line is (temporarily)
                    539:   suppressed.
                    540: 
                    541:   Revision 1.96  2003/07/15 15:38:55  brouard
                    542:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    543:   rewritten within the same printf. Workaround: many printfs.
                    544: 
                    545:   Revision 1.95  2003/07/08 07:54:34  brouard
                    546:   * imach.c (Repository):
                    547:   (Repository): Using imachwizard code to output a more meaningful covariance
                    548:   matrix (cov(a12,c31) instead of numbers.
                    549: 
                    550:   Revision 1.94  2003/06/27 13:00:02  brouard
                    551:   Just cleaning
                    552: 
                    553:   Revision 1.93  2003/06/25 16:33:55  brouard
                    554:   (Module): On windows (cygwin) function asctime_r doesn't
                    555:   exist so I changed back to asctime which exists.
                    556:   (Module): Version 0.96b
                    557: 
                    558:   Revision 1.92  2003/06/25 16:30:45  brouard
                    559:   (Module): On windows (cygwin) function asctime_r doesn't
                    560:   exist so I changed back to asctime which exists.
                    561: 
                    562:   Revision 1.91  2003/06/25 15:30:29  brouard
                    563:   * imach.c (Repository): Duplicated warning errors corrected.
                    564:   (Repository): Elapsed time after each iteration is now output. It
                    565:   helps to forecast when convergence will be reached. Elapsed time
                    566:   is stamped in powell.  We created a new html file for the graphs
                    567:   concerning matrix of covariance. It has extension -cov.htm.
                    568: 
                    569:   Revision 1.90  2003/06/24 12:34:15  brouard
                    570:   (Module): Some bugs corrected for windows. Also, when
                    571:   mle=-1 a template is output in file "or"mypar.txt with the design
                    572:   of the covariance matrix to be input.
                    573: 
                    574:   Revision 1.89  2003/06/24 12:30:52  brouard
                    575:   (Module): Some bugs corrected for windows. Also, when
                    576:   mle=-1 a template is output in file "or"mypar.txt with the design
                    577:   of the covariance matrix to be input.
                    578: 
                    579:   Revision 1.88  2003/06/23 17:54:56  brouard
                    580:   * 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.
                    581: 
                    582:   Revision 1.87  2003/06/18 12:26:01  brouard
                    583:   Version 0.96
                    584: 
                    585:   Revision 1.86  2003/06/17 20:04:08  brouard
                    586:   (Module): Change position of html and gnuplot routines and added
                    587:   routine fileappend.
                    588: 
                    589:   Revision 1.85  2003/06/17 13:12:43  brouard
                    590:   * imach.c (Repository): Check when date of death was earlier that
                    591:   current date of interview. It may happen when the death was just
                    592:   prior to the death. In this case, dh was negative and likelihood
                    593:   was wrong (infinity). We still send an "Error" but patch by
                    594:   assuming that the date of death was just one stepm after the
                    595:   interview.
                    596:   (Repository): Because some people have very long ID (first column)
                    597:   we changed int to long in num[] and we added a new lvector for
                    598:   memory allocation. But we also truncated to 8 characters (left
                    599:   truncation)
                    600:   (Repository): No more line truncation errors.
                    601: 
                    602:   Revision 1.84  2003/06/13 21:44:43  brouard
                    603:   * imach.c (Repository): Replace "freqsummary" at a correct
                    604:   place. It differs from routine "prevalence" which may be called
                    605:   many times. Probs is memory consuming and must be used with
                    606:   parcimony.
                    607:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    608: 
                    609:   Revision 1.83  2003/06/10 13:39:11  lievre
                    610:   *** empty log message ***
                    611: 
                    612:   Revision 1.82  2003/06/05 15:57:20  brouard
                    613:   Add log in  imach.c and  fullversion number is now printed.
                    614: 
                    615: */
                    616: /*
                    617:    Interpolated Markov Chain
                    618: 
                    619:   Short summary of the programme:
                    620:   
                    621:   This program computes Healthy Life Expectancies from
                    622:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    623:   first survey ("cross") where individuals from different ages are
                    624:   interviewed on their health status or degree of disability (in the
                    625:   case of a health survey which is our main interest) -2- at least a
                    626:   second wave of interviews ("longitudinal") which measure each change
                    627:   (if any) in individual health status.  Health expectancies are
                    628:   computed from the time spent in each health state according to a
                    629:   model. More health states you consider, more time is necessary to reach the
                    630:   Maximum Likelihood of the parameters involved in the model.  The
                    631:   simplest model is the multinomial logistic model where pij is the
                    632:   probability to be observed in state j at the second wave
                    633:   conditional to be observed in state i at the first wave. Therefore
                    634:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    635:   'age' is age and 'sex' is a covariate. If you want to have a more
                    636:   complex model than "constant and age", you should modify the program
                    637:   where the markup *Covariates have to be included here again* invites
                    638:   you to do it.  More covariates you add, slower the
                    639:   convergence.
                    640: 
                    641:   The advantage of this computer programme, compared to a simple
                    642:   multinomial logistic model, is clear when the delay between waves is not
                    643:   identical for each individual. Also, if a individual missed an
                    644:   intermediate interview, the information is lost, but taken into
                    645:   account using an interpolation or extrapolation.  
                    646: 
                    647:   hPijx is the probability to be observed in state i at age x+h
                    648:   conditional to the observed state i at age x. The delay 'h' can be
                    649:   split into an exact number (nh*stepm) of unobserved intermediate
                    650:   states. This elementary transition (by month, quarter,
                    651:   semester or year) is modelled as a multinomial logistic.  The hPx
                    652:   matrix is simply the matrix product of nh*stepm elementary matrices
                    653:   and the contribution of each individual to the likelihood is simply
                    654:   hPijx.
                    655: 
                    656:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   657:   of the life expectancies. It also computes the period (stable) prevalence.
                    658: 
                    659: Back prevalence and projections:
                    660:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj)
                    661:     Computes the back prevalence limit  for any combination    of covariate values k
                    662:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
                    663:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    664:  - hBijx Back Probability to be in state i at age x-h being in j at x
                    665:    Computes for any combination of covariates k and any age between bage and fage 
                    666:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    667:                        oldm=oldms;savm=savms;
                    668:         - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
                    669:      Computes the transition matrix starting at age 'age' over
                    670:      'nhstepm*hstepm*stepm' months (i.e. until
                    671:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                    672:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
                    673:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
                    674:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    675: 
1.133     brouard   676:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    677:            Institut national d'études démographiques, Paris.
1.126     brouard   678:   This software have been partly granted by Euro-REVES, a concerted action
                    679:   from the European Union.
                    680:   It is copyrighted identically to a GNU software product, ie programme and
                    681:   software can be distributed freely for non commercial use. Latest version
                    682:   can be accessed at http://euroreves.ined.fr/imach .
                    683: 
                    684:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    685:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    686:   
                    687:   **********************************************************************/
                    688: /*
                    689:   main
                    690:   read parameterfile
                    691:   read datafile
                    692:   concatwav
                    693:   freqsummary
                    694:   if (mle >= 1)
                    695:     mlikeli
                    696:   print results files
                    697:   if mle==1 
                    698:      computes hessian
                    699:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    700:       begin-prev-date,...
                    701:   open gnuplot file
                    702:   open html file
1.145     brouard   703:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    704:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    705:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    706:     freexexit2 possible for memory heap.
                    707: 
                    708:   h Pij x                         | pij_nom  ficrestpij
                    709:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    710:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    711:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    712: 
                    713:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    714:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    715:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    716:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    717:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    718: 
1.126     brouard   719:   forecasting if prevfcast==1 prevforecast call prevalence()
                    720:   health expectancies
                    721:   Variance-covariance of DFLE
                    722:   prevalence()
                    723:    movingaverage()
                    724:   varevsij() 
                    725:   if popbased==1 varevsij(,popbased)
                    726:   total life expectancies
                    727:   Variance of period (stable) prevalence
                    728:  end
                    729: */
                    730: 
1.187     brouard   731: /* #define DEBUG */
                    732: /* #define DEBUGBRENT */
1.203     brouard   733: /* #define DEBUGLINMIN */
                    734: /* #define DEBUGHESS */
                    735: #define DEBUGHESSIJ
                    736: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   737: #define POWELL /* Instead of NLOPT */
1.192     brouard   738: #define POWELLF1F3 /* Skip test */
1.186     brouard   739: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    740: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   741: 
                    742: #include <math.h>
                    743: #include <stdio.h>
                    744: #include <stdlib.h>
                    745: #include <string.h>
1.159     brouard   746: 
                    747: #ifdef _WIN32
                    748: #include <io.h>
1.172     brouard   749: #include <windows.h>
                    750: #include <tchar.h>
1.159     brouard   751: #else
1.126     brouard   752: #include <unistd.h>
1.159     brouard   753: #endif
1.126     brouard   754: 
                    755: #include <limits.h>
                    756: #include <sys/types.h>
1.171     brouard   757: 
                    758: #if defined(__GNUC__)
                    759: #include <sys/utsname.h> /* Doesn't work on Windows */
                    760: #endif
                    761: 
1.126     brouard   762: #include <sys/stat.h>
                    763: #include <errno.h>
1.159     brouard   764: /* extern int errno; */
1.126     brouard   765: 
1.157     brouard   766: /* #ifdef LINUX */
                    767: /* #include <time.h> */
                    768: /* #include "timeval.h" */
                    769: /* #else */
                    770: /* #include <sys/time.h> */
                    771: /* #endif */
                    772: 
1.126     brouard   773: #include <time.h>
                    774: 
1.136     brouard   775: #ifdef GSL
                    776: #include <gsl/gsl_errno.h>
                    777: #include <gsl/gsl_multimin.h>
                    778: #endif
                    779: 
1.167     brouard   780: 
1.162     brouard   781: #ifdef NLOPT
                    782: #include <nlopt.h>
                    783: typedef struct {
                    784:   double (* function)(double [] );
                    785: } myfunc_data ;
                    786: #endif
                    787: 
1.126     brouard   788: /* #include <libintl.h> */
                    789: /* #define _(String) gettext (String) */
                    790: 
1.141     brouard   791: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   792: 
                    793: #define GNUPLOTPROGRAM "gnuplot"
                    794: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    795: #define FILENAMELENGTH 132
                    796: 
                    797: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    798: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    799: 
1.144     brouard   800: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    801: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   802: 
                    803: #define NINTERVMAX 8
1.144     brouard   804: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    805: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    806: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   807: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   808: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    809: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   810: #define MAXN 20000
1.144     brouard   811: #define YEARM 12. /**< Number of months per year */
1.218     brouard   812: /* #define AGESUP 130 */
                    813: #define AGESUP 150
                    814: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   815: #define AGEBASE 40
1.194     brouard   816: #define AGEOVERFLOW 1.e20
1.164     brouard   817: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   818: #ifdef _WIN32
                    819: #define DIRSEPARATOR '\\'
                    820: #define CHARSEPARATOR "\\"
                    821: #define ODIRSEPARATOR '/'
                    822: #else
1.126     brouard   823: #define DIRSEPARATOR '/'
                    824: #define CHARSEPARATOR "/"
                    825: #define ODIRSEPARATOR '\\'
                    826: #endif
                    827: 
1.219   ! brouard   828: /* $Id: imach.c,v 1.218 2016/02/12 11:29:23 brouard Exp $ */
1.126     brouard   829: /* $State: Exp $ */
1.196     brouard   830: #include "version.h"
                    831: char version[]=__IMACH_VERSION__;
1.204     brouard   832: 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.219   ! brouard   833: char fullversion[]="$Revision: 1.218 $ $Date: 2016/02/12 11:29:23 $"; 
1.126     brouard   834: char strstart[80];
                    835: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   836: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   837: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   838: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    839: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    840: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    841: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    842: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    843: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    844: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    845: int cptcov=0; /* Working variable */
1.218     brouard   846: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   847: int npar=NPARMAX;
                    848: int nlstate=2; /* Number of live states */
                    849: int ndeath=1; /* Number of dead states */
1.130     brouard   850: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   851: int popbased=0;
                    852: 
                    853: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   854: int maxwav=0; /* Maxim number of waves */
                    855: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    856: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    857: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   858:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   859: int mle=1, weightopt=0;
1.126     brouard   860: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    861: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    862: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    863:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   864: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   865: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   866: double **matprod2(); /* test */
1.126     brouard   867: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    868: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   869: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    870: 
1.136     brouard   871: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   872: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   873: FILE *ficlog, *ficrespow;
1.130     brouard   874: int globpr=0; /* Global variable for printing or not */
1.126     brouard   875: double fretone; /* Only one call to likelihood */
1.130     brouard   876: long ipmx=0; /* Number of contributions */
1.126     brouard   877: double sw; /* Sum of weights */
                    878: char filerespow[FILENAMELENGTH];
                    879: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    880: FILE *ficresilk;
                    881: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    882: FILE *ficresprobmorprev;
                    883: FILE *fichtm, *fichtmcov; /* Html File */
                    884: FILE *ficreseij;
                    885: char filerese[FILENAMELENGTH];
                    886: FILE *ficresstdeij;
                    887: char fileresstde[FILENAMELENGTH];
                    888: FILE *ficrescveij;
                    889: char filerescve[FILENAMELENGTH];
                    890: FILE  *ficresvij;
                    891: char fileresv[FILENAMELENGTH];
                    892: FILE  *ficresvpl;
                    893: char fileresvpl[FILENAMELENGTH];
                    894: char title[MAXLINE];
1.217     brouard   895: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   896: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    897: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    898: char command[FILENAMELENGTH];
                    899: int  outcmd=0;
                    900: 
1.217     brouard   901: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   902: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   903: char filelog[FILENAMELENGTH]; /* Log file */
                    904: char filerest[FILENAMELENGTH];
                    905: char fileregp[FILENAMELENGTH];
                    906: char popfile[FILENAMELENGTH];
                    907: 
                    908: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    909: 
1.157     brouard   910: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    911: /* struct timezone tzp; */
                    912: /* extern int gettimeofday(); */
                    913: struct tm tml, *gmtime(), *localtime();
                    914: 
                    915: extern time_t time();
                    916: 
                    917: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    918: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    919: struct tm tm;
                    920: 
1.126     brouard   921: char strcurr[80], strfor[80];
                    922: 
                    923: char *endptr;
                    924: long lval;
                    925: double dval;
                    926: 
                    927: #define NR_END 1
                    928: #define FREE_ARG char*
                    929: #define FTOL 1.0e-10
                    930: 
                    931: #define NRANSI 
                    932: #define ITMAX 200 
                    933: 
                    934: #define TOL 2.0e-4 
                    935: 
                    936: #define CGOLD 0.3819660 
                    937: #define ZEPS 1.0e-10 
                    938: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    939: 
                    940: #define GOLD 1.618034 
                    941: #define GLIMIT 100.0 
                    942: #define TINY 1.0e-20 
                    943: 
                    944: static double maxarg1,maxarg2;
                    945: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    946: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    947:   
                    948: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    949: #define rint(a) floor(a+0.5)
1.166     brouard   950: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   951: #define mytinydouble 1.0e-16
1.166     brouard   952: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    953: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    954: /* static double dsqrarg; */
                    955: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   956: static double sqrarg;
                    957: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    958: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    959: int agegomp= AGEGOMP;
                    960: 
                    961: int imx; 
                    962: int stepm=1;
                    963: /* Stepm, step in month: minimum step interpolation*/
                    964: 
                    965: int estepm;
                    966: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    967: 
                    968: int m,nb;
                    969: long *num;
1.197     brouard   970: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   971: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    972:                   covariate for which somebody answered excluding 
                    973:                   undefined. Usually 2: 0 and 1. */
                    974: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    975:                             covariate for which somebody answered including 
                    976:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   977: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard   978: double **pmmij, ***probs; /* Global pointer */
1.219   ! brouard   979: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard   980: double *ageexmed,*agecens;
                    981: double dateintmean=0;
                    982: 
                    983: double *weight;
                    984: int **s; /* Status */
1.141     brouard   985: double *agedc;
1.145     brouard   986: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   987:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   988:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   989: double  idx; 
                    990: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   991: int *Tage;
1.145     brouard   992: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   993: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   994: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   995: double *lsurv, *lpop, *tpop;
                    996: 
1.143     brouard   997: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    998: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   999: 
                   1000: /**************** split *************************/
                   1001: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1002: {
                   1003:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1004:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1005:   */ 
                   1006:   char *ss;                            /* pointer */
1.186     brouard  1007:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1008: 
                   1009:   l1 = strlen(path );                  /* length of path */
                   1010:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1011:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1012:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1013:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1014:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1015:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1016:     /* get current working directory */
                   1017:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1018: #ifdef WIN32
                   1019:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1020: #else
                   1021:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1022: #endif
1.126     brouard  1023:       return( GLOCK_ERROR_GETCWD );
                   1024:     }
                   1025:     /* got dirc from getcwd*/
                   1026:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1027:   } else {                             /* strip directory from path */
1.126     brouard  1028:     ss++;                              /* after this, the filename */
                   1029:     l2 = strlen( ss );                 /* length of filename */
                   1030:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1031:     strcpy( name, ss );                /* save file name */
                   1032:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1033:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1034:     printf(" DIRC2 = %s \n",dirc);
                   1035:   }
                   1036:   /* We add a separator at the end of dirc if not exists */
                   1037:   l1 = strlen( dirc );                 /* length of directory */
                   1038:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1039:     dirc[l1] =  DIRSEPARATOR;
                   1040:     dirc[l1+1] = 0; 
                   1041:     printf(" DIRC3 = %s \n",dirc);
                   1042:   }
                   1043:   ss = strrchr( name, '.' );           /* find last / */
                   1044:   if (ss >0){
                   1045:     ss++;
                   1046:     strcpy(ext,ss);                    /* save extension */
                   1047:     l1= strlen( name);
                   1048:     l2= strlen(ss)+1;
                   1049:     strncpy( finame, name, l1-l2);
                   1050:     finame[l1-l2]= 0;
                   1051:   }
                   1052: 
                   1053:   return( 0 );                         /* we're done */
                   1054: }
                   1055: 
                   1056: 
                   1057: /******************************************/
                   1058: 
                   1059: void replace_back_to_slash(char *s, char*t)
                   1060: {
                   1061:   int i;
                   1062:   int lg=0;
                   1063:   i=0;
                   1064:   lg=strlen(t);
                   1065:   for(i=0; i<= lg; i++) {
                   1066:     (s[i] = t[i]);
                   1067:     if (t[i]== '\\') s[i]='/';
                   1068:   }
                   1069: }
                   1070: 
1.132     brouard  1071: char *trimbb(char *out, char *in)
1.137     brouard  1072: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1073:   char *s;
                   1074:   s=out;
                   1075:   while (*in != '\0'){
1.137     brouard  1076:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1077:       in++;
                   1078:     }
                   1079:     *out++ = *in++;
                   1080:   }
                   1081:   *out='\0';
                   1082:   return s;
                   1083: }
                   1084: 
1.187     brouard  1085: /* char *substrchaine(char *out, char *in, char *chain) */
                   1086: /* { */
                   1087: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1088: /*   char *s, *t; */
                   1089: /*   t=in;s=out; */
                   1090: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1091: /*     *out++ = *in++; */
                   1092: /*   } */
                   1093: 
                   1094: /*   /\* *in matches *chain *\/ */
                   1095: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1096: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1097: /*   } */
                   1098: /*   in--; chain--; */
                   1099: /*   while ( (*in != '\0')){ */
                   1100: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1101: /*     *out++ = *in++; */
                   1102: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1103: /*   } */
                   1104: /*   *out='\0'; */
                   1105: /*   out=s; */
                   1106: /*   return out; */
                   1107: /* } */
                   1108: char *substrchaine(char *out, char *in, char *chain)
                   1109: {
                   1110:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1111:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1112: 
                   1113:   char *strloc;
                   1114: 
                   1115:   strcpy (out, in); 
                   1116:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1117:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1118:   if(strloc != NULL){ 
                   1119:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1120:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1121:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1122:   }
                   1123:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1124:   return out;
                   1125: }
                   1126: 
                   1127: 
1.145     brouard  1128: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1129: {
1.187     brouard  1130:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1131:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1132:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1133:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1134:   */
1.160     brouard  1135:   char *s, *t;
1.145     brouard  1136:   t=in;s=in;
                   1137:   while ((*in != occ) && (*in != '\0')){
                   1138:     *alocc++ = *in++;
                   1139:   }
                   1140:   if( *in == occ){
                   1141:     *(alocc)='\0';
                   1142:     s=++in;
                   1143:   }
                   1144:  
                   1145:   if (s == t) {/* occ not found */
                   1146:     *(alocc-(in-s))='\0';
                   1147:     in=s;
                   1148:   }
                   1149:   while ( *in != '\0'){
                   1150:     *blocc++ = *in++;
                   1151:   }
                   1152: 
                   1153:   *blocc='\0';
                   1154:   return t;
                   1155: }
1.137     brouard  1156: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1157: {
1.187     brouard  1158:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1159:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1160:      gives blocc="abcdef2ghi" and alocc="j".
                   1161:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1162:   */
                   1163:   char *s, *t;
                   1164:   t=in;s=in;
                   1165:   while (*in != '\0'){
                   1166:     while( *in == occ){
                   1167:       *blocc++ = *in++;
                   1168:       s=in;
                   1169:     }
                   1170:     *blocc++ = *in++;
                   1171:   }
                   1172:   if (s == t) /* occ not found */
                   1173:     *(blocc-(in-s))='\0';
                   1174:   else
                   1175:     *(blocc-(in-s)-1)='\0';
                   1176:   in=s;
                   1177:   while ( *in != '\0'){
                   1178:     *alocc++ = *in++;
                   1179:   }
                   1180: 
                   1181:   *alocc='\0';
                   1182:   return s;
                   1183: }
                   1184: 
1.126     brouard  1185: int nbocc(char *s, char occ)
                   1186: {
                   1187:   int i,j=0;
                   1188:   int lg=20;
                   1189:   i=0;
                   1190:   lg=strlen(s);
                   1191:   for(i=0; i<= lg; i++) {
                   1192:   if  (s[i] == occ ) j++;
                   1193:   }
                   1194:   return j;
                   1195: }
                   1196: 
1.137     brouard  1197: /* void cutv(char *u,char *v, char*t, char occ) */
                   1198: /* { */
                   1199: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1200: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1201: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1202: /*   int i,lg,j,p=0; */
                   1203: /*   i=0; */
                   1204: /*   lg=strlen(t); */
                   1205: /*   for(j=0; j<=lg-1; j++) { */
                   1206: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1207: /*   } */
1.126     brouard  1208: 
1.137     brouard  1209: /*   for(j=0; j<p; j++) { */
                   1210: /*     (u[j] = t[j]); */
                   1211: /*   } */
                   1212: /*      u[p]='\0'; */
1.126     brouard  1213: 
1.137     brouard  1214: /*    for(j=0; j<= lg; j++) { */
                   1215: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1216: /*   } */
                   1217: /* } */
1.126     brouard  1218: 
1.160     brouard  1219: #ifdef _WIN32
                   1220: char * strsep(char **pp, const char *delim)
                   1221: {
                   1222:   char *p, *q;
                   1223:          
                   1224:   if ((p = *pp) == NULL)
                   1225:     return 0;
                   1226:   if ((q = strpbrk (p, delim)) != NULL)
                   1227:   {
                   1228:     *pp = q + 1;
                   1229:     *q = '\0';
                   1230:   }
                   1231:   else
                   1232:     *pp = 0;
                   1233:   return p;
                   1234: }
                   1235: #endif
                   1236: 
1.126     brouard  1237: /********************** nrerror ********************/
                   1238: 
                   1239: void nrerror(char error_text[])
                   1240: {
                   1241:   fprintf(stderr,"ERREUR ...\n");
                   1242:   fprintf(stderr,"%s\n",error_text);
                   1243:   exit(EXIT_FAILURE);
                   1244: }
                   1245: /*********************** vector *******************/
                   1246: double *vector(int nl, int nh)
                   1247: {
                   1248:   double *v;
                   1249:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1250:   if (!v) nrerror("allocation failure in vector");
                   1251:   return v-nl+NR_END;
                   1252: }
                   1253: 
                   1254: /************************ free vector ******************/
                   1255: void free_vector(double*v, int nl, int nh)
                   1256: {
                   1257:   free((FREE_ARG)(v+nl-NR_END));
                   1258: }
                   1259: 
                   1260: /************************ivector *******************************/
                   1261: int *ivector(long nl,long nh)
                   1262: {
                   1263:   int *v;
                   1264:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1265:   if (!v) nrerror("allocation failure in ivector");
                   1266:   return v-nl+NR_END;
                   1267: }
                   1268: 
                   1269: /******************free ivector **************************/
                   1270: void free_ivector(int *v, long nl, long nh)
                   1271: {
                   1272:   free((FREE_ARG)(v+nl-NR_END));
                   1273: }
                   1274: 
                   1275: /************************lvector *******************************/
                   1276: long *lvector(long nl,long nh)
                   1277: {
                   1278:   long *v;
                   1279:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1280:   if (!v) nrerror("allocation failure in ivector");
                   1281:   return v-nl+NR_END;
                   1282: }
                   1283: 
                   1284: /******************free lvector **************************/
                   1285: void free_lvector(long *v, long nl, long nh)
                   1286: {
                   1287:   free((FREE_ARG)(v+nl-NR_END));
                   1288: }
                   1289: 
                   1290: /******************* imatrix *******************************/
                   1291: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1292:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1293: { 
                   1294:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1295:   int **m; 
                   1296:   
                   1297:   /* allocate pointers to rows */ 
                   1298:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1299:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1300:   m += NR_END; 
                   1301:   m -= nrl; 
                   1302:   
                   1303:   
                   1304:   /* allocate rows and set pointers to them */ 
                   1305:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1306:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1307:   m[nrl] += NR_END; 
                   1308:   m[nrl] -= ncl; 
                   1309:   
                   1310:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1311:   
                   1312:   /* return pointer to array of pointers to rows */ 
                   1313:   return m; 
                   1314: } 
                   1315: 
                   1316: /****************** free_imatrix *************************/
                   1317: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1318:       int **m;
                   1319:       long nch,ncl,nrh,nrl; 
                   1320:      /* free an int matrix allocated by imatrix() */ 
                   1321: { 
                   1322:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1323:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1324: } 
                   1325: 
                   1326: /******************* matrix *******************************/
                   1327: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1328: {
                   1329:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1330:   double **m;
                   1331: 
                   1332:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1333:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1334:   m += NR_END;
                   1335:   m -= nrl;
                   1336: 
                   1337:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1338:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1339:   m[nrl] += NR_END;
                   1340:   m[nrl] -= ncl;
                   1341: 
                   1342:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1343:   return m;
1.145     brouard  1344:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1345: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1346: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1347:    */
                   1348: }
                   1349: 
                   1350: /*************************free matrix ************************/
                   1351: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1352: {
                   1353:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1354:   free((FREE_ARG)(m+nrl-NR_END));
                   1355: }
                   1356: 
                   1357: /******************* ma3x *******************************/
                   1358: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1359: {
                   1360:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1361:   double ***m;
                   1362: 
                   1363:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1364:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1365:   m += NR_END;
                   1366:   m -= nrl;
                   1367: 
                   1368:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1369:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1370:   m[nrl] += NR_END;
                   1371:   m[nrl] -= ncl;
                   1372: 
                   1373:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1374: 
                   1375:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1376:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1377:   m[nrl][ncl] += NR_END;
                   1378:   m[nrl][ncl] -= nll;
                   1379:   for (j=ncl+1; j<=nch; j++) 
                   1380:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1381:   
                   1382:   for (i=nrl+1; i<=nrh; i++) {
                   1383:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1384:     for (j=ncl+1; j<=nch; j++) 
                   1385:       m[i][j]=m[i][j-1]+nlay;
                   1386:   }
                   1387:   return m; 
                   1388:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1389:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1390:   */
                   1391: }
                   1392: 
                   1393: /*************************free ma3x ************************/
                   1394: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1395: {
                   1396:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1397:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1398:   free((FREE_ARG)(m+nrl-NR_END));
                   1399: }
                   1400: 
                   1401: /*************** function subdirf ***********/
                   1402: char *subdirf(char fileres[])
                   1403: {
                   1404:   /* Caution optionfilefiname is hidden */
                   1405:   strcpy(tmpout,optionfilefiname);
                   1406:   strcat(tmpout,"/"); /* Add to the right */
                   1407:   strcat(tmpout,fileres);
                   1408:   return tmpout;
                   1409: }
                   1410: 
                   1411: /*************** function subdirf2 ***********/
                   1412: char *subdirf2(char fileres[], char *preop)
                   1413: {
                   1414:   
                   1415:   /* Caution optionfilefiname is hidden */
                   1416:   strcpy(tmpout,optionfilefiname);
                   1417:   strcat(tmpout,"/");
                   1418:   strcat(tmpout,preop);
                   1419:   strcat(tmpout,fileres);
                   1420:   return tmpout;
                   1421: }
                   1422: 
                   1423: /*************** function subdirf3 ***********/
                   1424: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1425: {
                   1426:   
                   1427:   /* Caution optionfilefiname is hidden */
                   1428:   strcpy(tmpout,optionfilefiname);
                   1429:   strcat(tmpout,"/");
                   1430:   strcat(tmpout,preop);
                   1431:   strcat(tmpout,preop2);
                   1432:   strcat(tmpout,fileres);
                   1433:   return tmpout;
                   1434: }
1.213     brouard  1435:  
                   1436: /*************** function subdirfext ***********/
                   1437: char *subdirfext(char fileres[], char *preop, char *postop)
                   1438: {
                   1439:   
                   1440:   strcpy(tmpout,preop);
                   1441:   strcat(tmpout,fileres);
                   1442:   strcat(tmpout,postop);
                   1443:   return tmpout;
                   1444: }
1.126     brouard  1445: 
1.213     brouard  1446: /*************** function subdirfext3 ***********/
                   1447: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1448: {
                   1449:   
                   1450:   /* Caution optionfilefiname is hidden */
                   1451:   strcpy(tmpout,optionfilefiname);
                   1452:   strcat(tmpout,"/");
                   1453:   strcat(tmpout,preop);
                   1454:   strcat(tmpout,fileres);
                   1455:   strcat(tmpout,postop);
                   1456:   return tmpout;
                   1457: }
                   1458:  
1.162     brouard  1459: char *asc_diff_time(long time_sec, char ascdiff[])
                   1460: {
                   1461:   long sec_left, days, hours, minutes;
                   1462:   days = (time_sec) / (60*60*24);
                   1463:   sec_left = (time_sec) % (60*60*24);
                   1464:   hours = (sec_left) / (60*60) ;
                   1465:   sec_left = (sec_left) %(60*60);
                   1466:   minutes = (sec_left) /60;
                   1467:   sec_left = (sec_left) % (60);
                   1468:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1469:   return ascdiff;
                   1470: }
                   1471: 
1.126     brouard  1472: /***************** f1dim *************************/
                   1473: extern int ncom; 
                   1474: extern double *pcom,*xicom;
                   1475: extern double (*nrfunc)(double []); 
                   1476:  
                   1477: double f1dim(double x) 
                   1478: { 
                   1479:   int j; 
                   1480:   double f;
                   1481:   double *xt; 
                   1482:  
                   1483:   xt=vector(1,ncom); 
                   1484:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1485:   f=(*nrfunc)(xt); 
                   1486:   free_vector(xt,1,ncom); 
                   1487:   return f; 
                   1488: } 
                   1489: 
                   1490: /*****************brent *************************/
                   1491: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1492: {
                   1493:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1494:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1495:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1496:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1497:    * returned function value. 
                   1498:   */
1.126     brouard  1499:   int iter; 
                   1500:   double a,b,d,etemp;
1.159     brouard  1501:   double fu=0,fv,fw,fx;
1.164     brouard  1502:   double ftemp=0.;
1.126     brouard  1503:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1504:   double e=0.0; 
                   1505:  
                   1506:   a=(ax < cx ? ax : cx); 
                   1507:   b=(ax > cx ? ax : cx); 
                   1508:   x=w=v=bx; 
                   1509:   fw=fv=fx=(*f)(x); 
                   1510:   for (iter=1;iter<=ITMAX;iter++) { 
                   1511:     xm=0.5*(a+b); 
                   1512:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1513:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1514:     printf(".");fflush(stdout);
                   1515:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1516: #ifdef DEBUGBRENT
1.126     brouard  1517:     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);
                   1518:     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);
                   1519:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1520: #endif
                   1521:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1522:       *xmin=x; 
                   1523:       return fx; 
                   1524:     } 
                   1525:     ftemp=fu;
                   1526:     if (fabs(e) > tol1) { 
                   1527:       r=(x-w)*(fx-fv); 
                   1528:       q=(x-v)*(fx-fw); 
                   1529:       p=(x-v)*q-(x-w)*r; 
                   1530:       q=2.0*(q-r); 
                   1531:       if (q > 0.0) p = -p; 
                   1532:       q=fabs(q); 
                   1533:       etemp=e; 
                   1534:       e=d; 
                   1535:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1536:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1537:       else { 
                   1538:        d=p/q; 
                   1539:        u=x+d; 
                   1540:        if (u-a < tol2 || b-u < tol2) 
                   1541:          d=SIGN(tol1,xm-x); 
                   1542:       } 
                   1543:     } else { 
                   1544:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1545:     } 
                   1546:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1547:     fu=(*f)(u); 
                   1548:     if (fu <= fx) { 
                   1549:       if (u >= x) a=x; else b=x; 
                   1550:       SHFT(v,w,x,u) 
1.183     brouard  1551:       SHFT(fv,fw,fx,fu) 
                   1552:     } else { 
                   1553:       if (u < x) a=u; else b=u; 
                   1554:       if (fu <= fw || w == x) { 
                   1555:        v=w; 
                   1556:        w=u; 
                   1557:        fv=fw; 
                   1558:        fw=fu; 
                   1559:       } else if (fu <= fv || v == x || v == w) { 
                   1560:        v=u; 
                   1561:        fv=fu; 
                   1562:       } 
                   1563:     } 
1.126     brouard  1564:   } 
                   1565:   nrerror("Too many iterations in brent"); 
                   1566:   *xmin=x; 
                   1567:   return fx; 
                   1568: } 
                   1569: 
                   1570: /****************** mnbrak ***********************/
                   1571: 
                   1572: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1573:            double (*func)(double)) 
1.183     brouard  1574: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1575: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1576: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1577: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1578:    */
1.126     brouard  1579:   double ulim,u,r,q, dum;
                   1580:   double fu; 
1.187     brouard  1581: 
                   1582:   double scale=10.;
                   1583:   int iterscale=0;
                   1584: 
                   1585:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1586:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1587: 
                   1588: 
                   1589:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1590:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1591:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1592:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1593:   /* } */
                   1594: 
1.126     brouard  1595:   if (*fb > *fa) { 
                   1596:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1597:     SHFT(dum,*fb,*fa,dum) 
                   1598:   } 
1.126     brouard  1599:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1600:   *fc=(*func)(*cx); 
1.183     brouard  1601: #ifdef DEBUG
                   1602:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1603:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1604: #endif
                   1605:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1606:     r=(*bx-*ax)*(*fb-*fc); 
                   1607:     q=(*bx-*cx)*(*fb-*fa); 
                   1608:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1609:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1610:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1611:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1612:       fu=(*func)(u); 
1.163     brouard  1613: #ifdef DEBUG
                   1614:       /* f(x)=A(x-u)**2+f(u) */
                   1615:       double A, fparabu; 
                   1616:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1617:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1618:       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);
                   1619:       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  1620:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1621:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1622:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1623:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1624: #endif 
1.184     brouard  1625: #ifdef MNBRAKORIGINAL
1.183     brouard  1626: #else
1.191     brouard  1627: /*       if (fu > *fc) { */
                   1628: /* #ifdef DEBUG */
                   1629: /*       printf("mnbrak4  fu > fc \n"); */
                   1630: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1631: /* #endif */
                   1632: /*     /\* 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 *\\/  *\/ */
                   1633: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1634: /*     dum=u; /\* Shifting c and u *\/ */
                   1635: /*     u = *cx; */
                   1636: /*     *cx = dum; */
                   1637: /*     dum = fu; */
                   1638: /*     fu = *fc; */
                   1639: /*     *fc =dum; */
                   1640: /*       } else { /\* end *\/ */
                   1641: /* #ifdef DEBUG */
                   1642: /*       printf("mnbrak3  fu < fc \n"); */
                   1643: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1644: /* #endif */
                   1645: /*     dum=u; /\* Shifting c and u *\/ */
                   1646: /*     u = *cx; */
                   1647: /*     *cx = dum; */
                   1648: /*     dum = fu; */
                   1649: /*     fu = *fc; */
                   1650: /*     *fc =dum; */
                   1651: /*       } */
1.183     brouard  1652: #ifdef DEBUG
1.191     brouard  1653:       printf("mnbrak34  fu < or >= fc \n");
                   1654:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1655: #endif
1.191     brouard  1656:       dum=u; /* Shifting c and u */
                   1657:       u = *cx;
                   1658:       *cx = dum;
                   1659:       dum = fu;
                   1660:       fu = *fc;
                   1661:       *fc =dum;
1.183     brouard  1662: #endif
1.162     brouard  1663:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1664: #ifdef DEBUG
                   1665:       printf("mnbrak2  u after c but before ulim\n");
                   1666:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1667: #endif
1.126     brouard  1668:       fu=(*func)(u); 
                   1669:       if (fu < *fc) { 
1.183     brouard  1670: #ifdef DEBUG
                   1671:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1672:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1673: #endif
1.126     brouard  1674:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1675:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1676:       } 
1.162     brouard  1677:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1678: #ifdef DEBUG
                   1679:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1680:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1681: #endif
1.126     brouard  1682:       u=ulim; 
                   1683:       fu=(*func)(u); 
1.183     brouard  1684:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1685: #ifdef DEBUG
                   1686:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1687:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1688: #endif
1.126     brouard  1689:       u=(*cx)+GOLD*(*cx-*bx); 
                   1690:       fu=(*func)(u); 
1.183     brouard  1691:     } /* end tests */
1.126     brouard  1692:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1693:     SHFT(*fa,*fb,*fc,fu) 
                   1694: #ifdef DEBUG
                   1695:       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);
                   1696:       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);
                   1697: #endif
                   1698:   } /* 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  1699: } 
                   1700: 
                   1701: /*************** linmin ************************/
1.162     brouard  1702: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1703: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1704: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1705: the value of func at the returned location p . This is actually all accomplished by calling the
                   1706: routines mnbrak and brent .*/
1.126     brouard  1707: int ncom; 
                   1708: double *pcom,*xicom;
                   1709: double (*nrfunc)(double []); 
                   1710:  
                   1711: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1712: { 
                   1713:   double brent(double ax, double bx, double cx, 
                   1714:               double (*f)(double), double tol, double *xmin); 
                   1715:   double f1dim(double x); 
                   1716:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1717:              double *fc, double (*func)(double)); 
                   1718:   int j; 
                   1719:   double xx,xmin,bx,ax; 
                   1720:   double fx,fb,fa;
1.187     brouard  1721: 
1.203     brouard  1722: #ifdef LINMINORIGINAL
                   1723: #else
                   1724:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1725: #endif
                   1726:   
1.126     brouard  1727:   ncom=n; 
                   1728:   pcom=vector(1,n); 
                   1729:   xicom=vector(1,n); 
                   1730:   nrfunc=func; 
                   1731:   for (j=1;j<=n;j++) { 
                   1732:     pcom[j]=p[j]; 
1.202     brouard  1733:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1734:   } 
1.187     brouard  1735: 
1.203     brouard  1736: #ifdef LINMINORIGINAL
                   1737:   xx=1.;
                   1738: #else
                   1739:   axs=0.0;
                   1740:   xxs=1.;
                   1741:   do{
                   1742:     xx= xxs;
                   1743: #endif
1.187     brouard  1744:     ax=0.;
                   1745:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1746:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1747:     /* 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))   */
                   1748:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1749:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1750:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1751:     /* 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  1752: #ifdef LINMINORIGINAL
                   1753: #else
                   1754:     if (fx != fx){
                   1755:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1756:        printf("|");
                   1757:        fprintf(ficlog,"|");
                   1758: #ifdef DEBUGLINMIN
                   1759:        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);
                   1760: #endif
                   1761:     }
                   1762:   }while(fx != fx);
                   1763: #endif
                   1764:   
1.191     brouard  1765: #ifdef DEBUGLINMIN
                   1766:   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  1767:   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  1768: #endif
1.187     brouard  1769:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1770:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1771:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1772:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1773:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1774: #ifdef DEBUG
                   1775:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1776:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1777: #endif
1.191     brouard  1778: #ifdef DEBUGLINMIN
                   1779:   printf("linmin end ");
1.202     brouard  1780:   fprintf(ficlog,"linmin end ");
1.191     brouard  1781: #endif
1.126     brouard  1782:   for (j=1;j<=n;j++) { 
1.203     brouard  1783: #ifdef LINMINORIGINAL
                   1784:     xi[j] *= xmin; 
                   1785: #else
                   1786: #ifdef DEBUGLINMIN
                   1787:     if(xxs <1.0)
                   1788:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1789: #endif
                   1790:     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) */
                   1791: #ifdef DEBUGLINMIN
                   1792:     if(xxs <1.0)
                   1793:       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 );
                   1794: #endif
                   1795: #endif
1.187     brouard  1796:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1797:   } 
1.191     brouard  1798: #ifdef DEBUGLINMIN
1.203     brouard  1799:   printf("\n");
1.191     brouard  1800:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1801:   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  1802:   for (j=1;j<=n;j++) { 
1.202     brouard  1803:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1804:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1805:     if(j % ncovmodel == 0){
1.191     brouard  1806:       printf("\n");
1.202     brouard  1807:       fprintf(ficlog,"\n");
                   1808:     }
1.191     brouard  1809:   }
1.203     brouard  1810: #else
1.191     brouard  1811: #endif
1.126     brouard  1812:   free_vector(xicom,1,n); 
                   1813:   free_vector(pcom,1,n); 
                   1814: } 
                   1815: 
                   1816: 
                   1817: /*************** powell ************************/
1.162     brouard  1818: /*
                   1819: Minimization of a function func of n variables. Input consists of an initial starting point
                   1820: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1821: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1822: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1823: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1824: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1825:  */
1.126     brouard  1826: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1827:            double (*func)(double [])) 
                   1828: { 
                   1829:   void linmin(double p[], double xi[], int n, double *fret, 
                   1830:              double (*func)(double [])); 
                   1831:   int i,ibig,j; 
                   1832:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1833:   double directest;
1.126     brouard  1834:   double fp,fptt;
                   1835:   double *xits;
                   1836:   int niterf, itmp;
                   1837: 
                   1838:   pt=vector(1,n); 
                   1839:   ptt=vector(1,n); 
                   1840:   xit=vector(1,n); 
                   1841:   xits=vector(1,n); 
                   1842:   *fret=(*func)(p); 
                   1843:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1844:   rcurr_time = time(NULL);  
1.126     brouard  1845:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1846:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1847:     ibig=0; 
                   1848:     del=0.0; 
1.157     brouard  1849:     rlast_time=rcurr_time;
                   1850:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1851:     rcurr_time = time(NULL);  
                   1852:     curr_time = *localtime(&rcurr_time);
                   1853:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1854:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1855: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1856:     for (i=1;i<=n;i++) {
1.126     brouard  1857:       printf(" %d %.12f",i, p[i]);
                   1858:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1859:       fprintf(ficrespow," %.12lf", p[i]);
                   1860:     }
                   1861:     printf("\n");
                   1862:     fprintf(ficlog,"\n");
                   1863:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1864:     if(*iter <=3){
1.157     brouard  1865:       tml = *localtime(&rcurr_time);
                   1866:       strcpy(strcurr,asctime(&tml));
                   1867:       rforecast_time=rcurr_time; 
1.126     brouard  1868:       itmp = strlen(strcurr);
                   1869:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1870:        strcurr[itmp-1]='\0';
1.162     brouard  1871:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1872:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1873:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1874:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1875:        forecast_time = *localtime(&rforecast_time);
                   1876:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1877:        itmp = strlen(strfor);
                   1878:        if(strfor[itmp-1]=='\n')
                   1879:        strfor[itmp-1]='\0';
1.157     brouard  1880:        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);
                   1881:        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  1882:       }
                   1883:     }
1.187     brouard  1884:     for (i=1;i<=n;i++) { /* For each direction i */
                   1885:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1886:       fptt=(*fret); 
                   1887: #ifdef DEBUG
1.203     brouard  1888:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1889:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1890: #endif
1.203     brouard  1891:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1892:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1893:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1894:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1895:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1896:        /* because that direction will be replaced unless the gain del is small */
                   1897:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1898:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1899:        /* with the new direction. */
1.126     brouard  1900:        del=fabs(fptt-(*fret)); 
                   1901:        ibig=i; 
                   1902:       } 
                   1903: #ifdef DEBUG
                   1904:       printf("%d %.12e",i,(*fret));
                   1905:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1906:       for (j=1;j<=n;j++) {
                   1907:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1908:        printf(" x(%d)=%.12e",j,xit[j]);
                   1909:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1910:       }
                   1911:       for(j=1;j<=n;j++) {
1.162     brouard  1912:        printf(" p(%d)=%.12e",j,p[j]);
                   1913:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1914:       }
                   1915:       printf("\n");
                   1916:       fprintf(ficlog,"\n");
                   1917: #endif
1.187     brouard  1918:     } /* end loop on each direction i */
                   1919:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1920:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1921:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1922:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1923:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1924:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1925:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1926:       /* decreased of more than 3.84  */
                   1927:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1928:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1929:       /* By adding 10 parameters more the gain should be 18.31 */
                   1930: 
                   1931:       /* Starting the program with initial values given by a former maximization will simply change */
                   1932:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1933:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1934:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1935: #ifdef DEBUG
                   1936:       int k[2],l;
                   1937:       k[0]=1;
                   1938:       k[1]=-1;
                   1939:       printf("Max: %.12e",(*func)(p));
                   1940:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1941:       for (j=1;j<=n;j++) {
                   1942:        printf(" %.12e",p[j]);
                   1943:        fprintf(ficlog," %.12e",p[j]);
                   1944:       }
                   1945:       printf("\n");
                   1946:       fprintf(ficlog,"\n");
                   1947:       for(l=0;l<=1;l++) {
                   1948:        for (j=1;j<=n;j++) {
                   1949:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1950:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1951:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1952:        }
                   1953:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1954:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1955:       }
                   1956: #endif
                   1957: 
                   1958: 
                   1959:       free_vector(xit,1,n); 
                   1960:       free_vector(xits,1,n); 
                   1961:       free_vector(ptt,1,n); 
                   1962:       free_vector(pt,1,n); 
                   1963:       return; 
1.192     brouard  1964:     } /* enough precision */ 
1.126     brouard  1965:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1966:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1967:       ptt[j]=2.0*p[j]-pt[j]; 
                   1968:       xit[j]=p[j]-pt[j]; 
                   1969:       pt[j]=p[j]; 
                   1970:     } 
1.181     brouard  1971:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1972: #ifdef POWELLF1F3
                   1973: #else
1.161     brouard  1974:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1975: #endif
1.162     brouard  1976:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1977:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1978:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1979:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1980:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1981:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1982:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1983: #ifdef NRCORIGINAL
                   1984:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1985: #else
                   1986:       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  1987:       t= t- del*SQR(fp-fptt);
1.183     brouard  1988: #endif
1.202     brouard  1989:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1990: #ifdef DEBUG
1.181     brouard  1991:       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);
                   1992:       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  1993:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1994:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1995:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1996:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1997:       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);
                   1998:       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);
                   1999: #endif
1.183     brouard  2000: #ifdef POWELLORIGINAL
                   2001:       if (t < 0.0) { /* Then we use it for new direction */
                   2002: #else
1.182     brouard  2003:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  2004:        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  2005:         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  2006:         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  2007:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2008:       } 
1.181     brouard  2009:       if (directest < 0.0) { /* Then we use it for new direction */
                   2010: #endif
1.191     brouard  2011: #ifdef DEBUGLINMIN
                   2012:        printf("Before linmin in direction P%d-P0\n",n);
                   2013:        for (j=1;j<=n;j++) { 
1.202     brouard  2014:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2015:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2016:          if(j % ncovmodel == 0){
1.191     brouard  2017:            printf("\n");
1.202     brouard  2018:            fprintf(ficlog,"\n");
                   2019:          }
1.191     brouard  2020:        }
                   2021: #endif
1.187     brouard  2022:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  2023: #ifdef DEBUGLINMIN
                   2024:        for (j=1;j<=n;j++) { 
                   2025:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  2026:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2027:          if(j % ncovmodel == 0){
1.191     brouard  2028:            printf("\n");
1.202     brouard  2029:            fprintf(ficlog,"\n");
                   2030:          }
1.191     brouard  2031:        }
                   2032: #endif
1.126     brouard  2033:        for (j=1;j<=n;j++) { 
1.181     brouard  2034:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2035:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  2036:        }
1.181     brouard  2037:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2038:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  2039: 
1.126     brouard  2040: #ifdef DEBUG
1.164     brouard  2041:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2042:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2043:        for(j=1;j<=n;j++){
                   2044:          printf(" %.12e",xit[j]);
                   2045:          fprintf(ficlog," %.12e",xit[j]);
                   2046:        }
                   2047:        printf("\n");
                   2048:        fprintf(ficlog,"\n");
                   2049: #endif
1.192     brouard  2050:       } /* end of t or directest negative */
                   2051: #ifdef POWELLF1F3
                   2052: #else
1.162     brouard  2053:     } /* end if (fptt < fp)  */
1.192     brouard  2054: #endif
                   2055:   } /* loop iteration */ 
1.126     brouard  2056: } 
                   2057: 
                   2058: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2059: 
1.203     brouard  2060: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2061: {
1.218     brouard  2062:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
1.203     brouard  2063:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2064:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2065:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2066:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2067:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2068:   /* Initial matrix pimij */
                   2069:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2070:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2071:   /*  0,                   0                  , 1} */
                   2072:   /*
                   2073:    * and after some iteration: */
                   2074:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2075:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2076:   /*  0,                   0                  , 1} */
                   2077:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2078:   /* {0.51571254859325999, 0.4842874514067399, */
                   2079:   /*  0.51326036147820708, 0.48673963852179264} */
                   2080:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2081: 
1.126     brouard  2082:   int i, ii,j,k;
1.209     brouard  2083:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2084:   /* double **matprod2(); */ /* test */
1.218     brouard  2085:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2086:   double **newm;
1.209     brouard  2087:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2088:   int ncvloop=0;
1.169     brouard  2089:   
1.209     brouard  2090:   min=vector(1,nlstate);
                   2091:   max=vector(1,nlstate);
                   2092:   meandiff=vector(1,nlstate);
                   2093: 
1.218     brouard  2094:        /* Starting with matrix unity */
1.126     brouard  2095:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2096:     for (j=1;j<=nlstate+ndeath;j++){
                   2097:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2098:     }
1.169     brouard  2099:   
                   2100:   cov[1]=1.;
                   2101:   
                   2102:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2103:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2104:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2105:     ncvloop++;
1.126     brouard  2106:     newm=savm;
                   2107:     /* Covariates have to be included here again */
1.138     brouard  2108:     cov[2]=agefin;
1.187     brouard  2109:     if(nagesqr==1)
                   2110:       cov[3]= agefin*agefin;;
1.138     brouard  2111:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2112:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.218     brouard  2113:                        /* Here comes the value of the covariate 'ij' */
1.200     brouard  2114:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2115:       /* 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  2116:     }
1.186     brouard  2117:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2118:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2119:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2120:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2121:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2122:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2123:     
                   2124:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2125:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2126:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2127:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2128:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2129:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2130:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2131:     
1.126     brouard  2132:     savm=oldm;
                   2133:     oldm=newm;
1.209     brouard  2134: 
                   2135:     for(j=1; j<=nlstate; j++){
                   2136:       max[j]=0.;
                   2137:       min[j]=1.;
                   2138:     }
                   2139:     for(i=1;i<=nlstate;i++){
                   2140:       sumnew=0;
                   2141:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2142:       for(j=1; j<=nlstate; j++){ 
                   2143:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2144:        max[j]=FMAX(max[j],prlim[i][j]);
                   2145:        min[j]=FMIN(min[j],prlim[i][j]);
                   2146:       }
                   2147:     }
                   2148: 
1.126     brouard  2149:     maxmax=0.;
1.209     brouard  2150:     for(j=1; j<=nlstate; j++){
                   2151:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2152:       maxmax=FMAX(maxmax,meandiff[j]);
                   2153:       /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
1.169     brouard  2154:     } /* j loop */
1.203     brouard  2155:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2156:     /* 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  2157:     if(maxmax < ftolpl){
1.209     brouard  2158:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2159:       free_vector(min,1,nlstate);
                   2160:       free_vector(max,1,nlstate);
                   2161:       free_vector(meandiff,1,nlstate);
1.126     brouard  2162:       return prlim;
                   2163:     }
1.169     brouard  2164:   } /* age loop */
1.208     brouard  2165:     /* After some age loop it doesn't converge */
1.209     brouard  2166:   printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.208     brouard  2167: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
1.209     brouard  2168:   /* 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); */
                   2169:   free_vector(min,1,nlstate);
                   2170:   free_vector(max,1,nlstate);
                   2171:   free_vector(meandiff,1,nlstate);
1.208     brouard  2172:   
1.169     brouard  2173:   return prlim; /* should not reach here */
1.126     brouard  2174: }
                   2175: 
1.217     brouard  2176: 
                   2177:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2178: 
1.218     brouard  2179:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2180:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2181:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2182: {
1.218     brouard  2183:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2184:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2185:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2186:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2187:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2188:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2189:   /* Initial matrix pimij */
                   2190:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2191:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2192:   /*  0,                   0                  , 1} */
                   2193:   /*
                   2194:    * and after some iteration: */
                   2195:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2196:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2197:   /*  0,                   0                  , 1} */
                   2198:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2199:   /* {0.51571254859325999, 0.4842874514067399, */
                   2200:   /*  0.51326036147820708, 0.48673963852179264} */
                   2201:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2202: 
                   2203:   int i, ii,j,k;
                   2204:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2205:   /* double **matprod2(); */ /* test */
                   2206:   double **out, cov[NCOVMAX+1], **bmij();
                   2207:   double **newm;
1.218     brouard  2208:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2209:   double        **oldm, **savm;  /* for use */
                   2210: 
1.217     brouard  2211:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2212:   int ncvloop=0;
                   2213:   
                   2214:   min=vector(1,nlstate);
                   2215:   max=vector(1,nlstate);
                   2216:   meandiff=vector(1,nlstate);
                   2217: 
1.218     brouard  2218:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2219:        oldm=oldms; savm=savms;
                   2220: 
                   2221:        /* Starting with matrix unity */
                   2222:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2223:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2224:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2225:     }
                   2226:   
                   2227:   cov[1]=1.;
                   2228:   
                   2229:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2230:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2231:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2232:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2233:     ncvloop++;
1.218     brouard  2234:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2235:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2236:     /* Covariates have to be included here again */
                   2237:     cov[2]=agefin;
                   2238:     if(nagesqr==1)
                   2239:       cov[3]= agefin*agefin;;
                   2240:     for (k=1; k<=cptcovn;k++) {
                   2241:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2242:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2243:       /* 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])]); */
                   2244:     }
                   2245:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2246:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2247:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2248:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2249:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2250:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2251:     
                   2252:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2253:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2254:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2255:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2256:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2257:                /* ij should be linked to the correct index of cov */
                   2258:                /* age and covariate values ij are in 'cov', but we need to pass
                   2259:                 * ij for the observed prevalence at age and status and covariate
                   2260:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2261:                 */
                   2262:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2263:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2264:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.217     brouard  2265:     savm=oldm;
                   2266:     oldm=newm;
                   2267:     for(j=1; j<=nlstate; j++){
                   2268:       max[j]=0.;
                   2269:       min[j]=1.;
                   2270:     }
                   2271:     for(j=1; j<=nlstate; j++){ 
                   2272:       for(i=1;i<=nlstate;i++){
1.218     brouard  2273:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2274:                                bprlim[i][j]= newm[i][j];
                   2275:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2276:                                min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2277:       }
                   2278:     }
1.218     brouard  2279:                
1.217     brouard  2280:     maxmax=0.;
                   2281:     for(i=1; i<=nlstate; i++){
                   2282:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2283:       maxmax=FMAX(maxmax,meandiff[i]);
                   2284:       /* printf("Back age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, i, meandiff[i],(int)agefin, i, max[i], i, min[i],maxmax); */
                   2285:     } /* j loop */
                   2286:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2287:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2288:     if(maxmax < ftolpl){
                   2289:       printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);
                   2290:       free_vector(min,1,nlstate);
                   2291:       free_vector(max,1,nlstate);
                   2292:       free_vector(meandiff,1,nlstate);
                   2293:       return bprlim;
                   2294:     }
                   2295:   } /* age loop */
                   2296:     /* After some age loop it doesn't converge */
                   2297:   printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
                   2298: Oldest 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);
                   2299:   /* 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); */
                   2300:   free_vector(min,1,nlstate);
                   2301:   free_vector(max,1,nlstate);
                   2302:   free_vector(meandiff,1,nlstate);
                   2303:   
                   2304:   return bprlim; /* should not reach here */
                   2305: }
                   2306: 
1.126     brouard  2307: /*************** transition probabilities ***************/ 
                   2308: 
                   2309: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2310: {
1.138     brouard  2311:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2312:      computes the probability to be observed in state j being in state i by appying the
                   2313:      model to the ncovmodel covariates (including constant and age).
                   2314:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2315:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2316:      ncth covariate in the global vector x is given by the formula:
                   2317:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2318:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2319:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2320:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2321:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2322:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2323:   */
                   2324:   double s1, lnpijopii;
1.126     brouard  2325:   /*double t34;*/
1.164     brouard  2326:   int i,j, nc, ii, jj;
1.126     brouard  2327: 
1.218     brouard  2328:        for(i=1; i<= nlstate; i++){
                   2329:                for(j=1; j<i;j++){
                   2330:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2331:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2332:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2333:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2334:                        }
                   2335:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2336:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2337:                }
                   2338:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2339:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2340:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2341:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2342:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2343:                        }
                   2344:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2345:                }
                   2346:        }
                   2347:   
                   2348:        for(i=1; i<= nlstate; i++){
                   2349:                s1=0;
                   2350:                for(j=1; j<i; j++){
                   2351:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2352:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2353:                }
                   2354:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2355:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2356:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2357:                }
                   2358:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2359:                ps[i][i]=1./(s1+1.);
                   2360:                /* Computing other pijs */
                   2361:                for(j=1; j<i; j++)
                   2362:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2363:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2364:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2365:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2366:        } /* end i */
                   2367:   
                   2368:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2369:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2370:                        ps[ii][jj]=0;
                   2371:                        ps[ii][ii]=1;
                   2372:                }
                   2373:        }
                   2374:   
                   2375:   
                   2376:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2377:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2378:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2379:        /*   } */
                   2380:        /*   printf("\n "); */
                   2381:        /* } */
                   2382:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2383:        /*
                   2384:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2385:                goto end;*/
                   2386:        return ps;
1.126     brouard  2387: }
                   2388: 
1.218     brouard  2389: /*************** backward transition probabilities ***************/ 
                   2390: 
                   2391:  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2392: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2393:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2394: {
                   2395:        /* Computes the backward probability at age agefin and covariate ij
                   2396:         * and returns in **ps as well as **bmij.
                   2397:         */
                   2398:   int i, ii, j,k;
                   2399: 
                   2400:        double **out, **pmij();
                   2401:        double sumnew=0.;
                   2402:   double agefin;
                   2403: 
                   2404:        double **dnewm, **dsavm, **doldm;
                   2405:        double **bbmij;
                   2406: 
                   2407:   doldm=ddoldms; /* global pointers */
                   2408:        dnewm=ddnewms;
                   2409:        dsavm=ddsavms;
                   2410: 
                   2411:        agefin=cov[2];
                   2412:        /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2413:                 the observed prevalence (with this covariate ij) */
                   2414:        dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2415:        /* We do have the matrix Px in savm  and we need pij */
                   2416:        for (j=1;j<=nlstate+ndeath;j++){
                   2417:                sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2418:                for (ii=1;ii<=nlstate;ii++){
                   2419:                        sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2420:                } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2421:                for (ii=1;ii<=nlstate+ndeath;ii++){
                   2422:                        if(sumnew >= 1.e-10){
                   2423:                                /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2424:                                /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2425:                                /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2426:                                /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2427:                                /* }else */
                   2428:                                        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2429:                        }else{
                   2430:                                printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
                   2431:                        }
                   2432:                } /*End ii */
                   2433:        } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2434:                /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2435:        bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2436:        /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2437:        /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2438:        /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2439:        /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2440:        for (j=1;j<=nlstate+ndeath;j++){
                   2441:                for (ii=1;ii<=nlstate+ndeath;ii++){
                   2442:                        dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2443:                }
                   2444:        } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2445:        ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2446:        /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2447:        /* end bmij */
                   2448:        return ps; 
                   2449: }
1.217     brouard  2450: /*************** transition probabilities ***************/ 
                   2451: 
1.218     brouard  2452: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2453: {
                   2454:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2455:      computes the probability to be observed in state j being in state i by appying the
                   2456:      model to the ncovmodel covariates (including constant and age).
                   2457:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2458:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2459:      ncth covariate in the global vector x is given by the formula:
                   2460:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2461:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2462:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2463:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2464:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2465:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2466:   */
                   2467:   double s1, lnpijopii;
                   2468:   /*double t34;*/
                   2469:   int i,j, nc, ii, jj;
                   2470: 
1.218     brouard  2471:        for(i=1; i<= nlstate; i++){
                   2472:                for(j=1; j<i;j++){
                   2473:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2474:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2475:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2476:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2477:                        }
                   2478:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2479:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2480:                }
                   2481:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2482:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2483:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2484:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2485:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2486:                        }
                   2487:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2488:                }
                   2489:        }
                   2490:        
                   2491:        for(i=1; i<= nlstate; i++){
                   2492:                s1=0;
                   2493:                for(j=1; j<i; j++){
                   2494:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2495:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2496:                }
                   2497:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2498:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2499:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2500:                }
                   2501:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2502:                ps[i][i]=1./(s1+1.);
                   2503:                /* Computing other pijs */
                   2504:                for(j=1; j<i; j++)
                   2505:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2506:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2507:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2508:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2509:        } /* end i */
                   2510:        
                   2511:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2512:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2513:                        ps[ii][jj]=0;
                   2514:                        ps[ii][ii]=1;
                   2515:                }
                   2516:        }
                   2517:        /* Added for backcast */ /* Transposed matrix too */
                   2518:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2519:                s1=0.;
                   2520:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2521:                        s1+=ps[ii][jj];
                   2522:                }
                   2523:                for(ii=1; ii<= nlstate; ii++){
                   2524:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2525:                }
                   2526:        }
                   2527:        /* Transposition */
                   2528:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2529:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2530:                        s1=ps[ii][jj];
                   2531:                        ps[ii][jj]=ps[jj][ii];
                   2532:                        ps[jj][ii]=s1;
                   2533:                }
                   2534:        }
                   2535:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2536:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2537:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2538:        /*   } */
                   2539:        /*   printf("\n "); */
                   2540:        /* } */
                   2541:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2542:        /*
                   2543:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2544:                goto end;*/
                   2545:        return ps;
1.217     brouard  2546: }
                   2547: 
                   2548: 
1.126     brouard  2549: /**************** Product of 2 matrices ******************/
                   2550: 
1.145     brouard  2551: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2552: {
                   2553:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2554:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2555:   /* in, b, out are matrice of pointers which should have been initialized 
                   2556:      before: only the contents of out is modified. The function returns
                   2557:      a pointer to pointers identical to out */
1.145     brouard  2558:   int i, j, k;
1.126     brouard  2559:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2560:     for(k=ncolol; k<=ncoloh; k++){
                   2561:       out[i][k]=0.;
                   2562:       for(j=ncl; j<=nch; j++)
                   2563:        out[i][k] +=in[i][j]*b[j][k];
                   2564:     }
1.126     brouard  2565:   return out;
                   2566: }
                   2567: 
                   2568: 
                   2569: /************* Higher Matrix Product ***************/
                   2570: 
                   2571: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2572: {
1.218     brouard  2573:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2574:      'nhstepm*hstepm*stepm' months (i.e. until
                   2575:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2576:      nhstepm*hstepm matrices. 
                   2577:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2578:      (typically every 2 years instead of every month which is too big 
                   2579:      for the memory).
                   2580:      Model is determined by parameters x and covariates have to be 
                   2581:      included manually here. 
                   2582: 
                   2583:      */
                   2584: 
                   2585:   int i, j, d, h, k;
1.131     brouard  2586:   double **out, cov[NCOVMAX+1];
1.126     brouard  2587:   double **newm;
1.187     brouard  2588:   double agexact;
1.214     brouard  2589:   double agebegin, ageend;
1.126     brouard  2590: 
                   2591:   /* Hstepm could be zero and should return the unit matrix */
                   2592:   for (i=1;i<=nlstate+ndeath;i++)
                   2593:     for (j=1;j<=nlstate+ndeath;j++){
                   2594:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2595:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2596:     }
                   2597:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2598:   for(h=1; h <=nhstepm; h++){
                   2599:     for(d=1; d <=hstepm; d++){
                   2600:       newm=savm;
                   2601:       /* Covariates have to be included here again */
                   2602:       cov[1]=1.;
1.214     brouard  2603:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2604:       cov[2]=agexact;
                   2605:       if(nagesqr==1)
1.218     brouard  2606:                                cov[3]= agexact*agexact;
1.131     brouard  2607:       for (k=1; k<=cptcovn;k++) 
1.218     brouard  2608:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2609:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2610:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2611:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2612:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2613:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2614:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2615:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2616:                        /* 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  2617: 
                   2618: 
                   2619:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2620:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2621:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2622:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2623:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2624:       /* if((int)age == 70){ */
                   2625:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2626:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2627:       /*         printf("%d pmmij ",i); */
                   2628:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2629:       /*           printf("%f ",pmmij[i][j]); */
                   2630:       /*         } */
                   2631:       /*         printf(" oldm "); */
                   2632:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2633:       /*           printf("%f ",oldm[i][j]); */
                   2634:       /*         } */
                   2635:       /*         printf("\n"); */
                   2636:       /*       } */
                   2637:       /* } */
1.126     brouard  2638:       savm=oldm;
                   2639:       oldm=newm;
                   2640:     }
                   2641:     for(i=1; i<=nlstate+ndeath; i++)
                   2642:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2643:                                po[i][j][h]=newm[i][j];
                   2644:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2645:       }
1.128     brouard  2646:     /*printf("h=%d ",h);*/
1.126     brouard  2647:   } /* end h */
1.218     brouard  2648:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2649:   return po;
                   2650: }
                   2651: 
1.217     brouard  2652: /************* Higher Back Matrix Product ***************/
1.218     brouard  2653: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
                   2654:  double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2655: {
1.218     brouard  2656:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2657:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2658:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2659:      nhstepm*hstepm matrices.
                   2660:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2661:      (typically every 2 years instead of every month which is too big
1.217     brouard  2662:      for the memory).
1.218     brouard  2663:      Model is determined by parameters x and covariates have to be
                   2664:      included manually here.
1.217     brouard  2665: 
                   2666:      */
                   2667: 
                   2668:   int i, j, d, h, k;
                   2669:   double **out, cov[NCOVMAX+1];
                   2670:   double **newm;
                   2671:   double agexact;
                   2672:   double agebegin, ageend;
1.218     brouard  2673:        double **oldm, **savm;
1.217     brouard  2674: 
1.218     brouard  2675:        oldm=oldms;savm=savms;
1.217     brouard  2676:   /* Hstepm could be zero and should return the unit matrix */
                   2677:   for (i=1;i<=nlstate+ndeath;i++)
                   2678:     for (j=1;j<=nlstate+ndeath;j++){
                   2679:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2680:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2681:     }
                   2682:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2683:   for(h=1; h <=nhstepm; h++){
                   2684:     for(d=1; d <=hstepm; d++){
                   2685:       newm=savm;
                   2686:       /* Covariates have to be included here again */
                   2687:       cov[1]=1.;
                   2688:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2689:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2690:       cov[2]=agexact;
                   2691:       if(nagesqr==1)
1.218     brouard  2692:                                cov[3]= agexact*agexact;
                   2693:       for (k=1; k<=cptcovn;k++)
                   2694:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2695:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  2696:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2697:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2698:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2699:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  2700:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2701:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2702:                        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2703:                        
                   2704:                        
1.217     brouard  2705:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2706:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2707:       /* Careful transposed matrix */
                   2708:                        /* age is in cov[2] */
                   2709:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
                   2710:                        /*                                               1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
                   2711:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
                   2712:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  2713:       /* if((int)age == 70){ */
                   2714:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2715:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2716:       /*         printf("%d pmmij ",i); */
                   2717:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2718:       /*           printf("%f ",pmmij[i][j]); */
                   2719:       /*         } */
                   2720:       /*         printf(" oldm "); */
                   2721:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2722:       /*           printf("%f ",oldm[i][j]); */
                   2723:       /*         } */
                   2724:       /*         printf("\n"); */
                   2725:       /*       } */
                   2726:       /* } */
                   2727:       savm=oldm;
                   2728:       oldm=newm;
                   2729:     }
                   2730:     for(i=1; i<=nlstate+ndeath; i++)
                   2731:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2732:                                po[i][j][h]=newm[i][j];
                   2733:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  2734:       }
                   2735:     /*printf("h=%d ",h);*/
                   2736:   } /* end h */
1.218     brouard  2737:        /*     printf("\n H=%d \n",h); */
1.217     brouard  2738:   return po;
                   2739: }
                   2740: 
                   2741: 
1.162     brouard  2742: #ifdef NLOPT
                   2743:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2744:   double fret;
                   2745:   double *xt;
                   2746:   int j;
                   2747:   myfunc_data *d2 = (myfunc_data *) pd;
                   2748: /* xt = (p1-1); */
                   2749:   xt=vector(1,n); 
                   2750:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2751: 
                   2752:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2753:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2754:   printf("Function = %.12lf ",fret);
                   2755:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2756:   printf("\n");
                   2757:  free_vector(xt,1,n);
                   2758:   return fret;
                   2759: }
                   2760: #endif
1.126     brouard  2761: 
                   2762: /*************** log-likelihood *************/
                   2763: double func( double *x)
                   2764: {
                   2765:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2766:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2767:   double **out;
                   2768:   double sw; /* Sum of weights */
                   2769:   double lli; /* Individual log likelihood */
                   2770:   int s1, s2;
                   2771:   double bbh, survp;
                   2772:   long ipmx;
1.187     brouard  2773:   double agexact;
1.126     brouard  2774:   /*extern weight */
                   2775:   /* We are differentiating ll according to initial status */
                   2776:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2777:   /*for(i=1;i<imx;i++) 
                   2778:     printf(" %d\n",s[4][i]);
                   2779:   */
1.162     brouard  2780: 
                   2781:   ++countcallfunc;
                   2782: 
1.126     brouard  2783:   cov[1]=1.;
                   2784: 
                   2785:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2786: 
                   2787:   if(mle==1){
                   2788:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2789:       /* Computes the values of the ncovmodel covariates of the model
                   2790:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2791:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2792:         to be observed in j being in i according to the model.
                   2793:        */
1.145     brouard  2794:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2795:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2796:       }
1.137     brouard  2797:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2798:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2799:         has been calculated etc */
1.126     brouard  2800:       for(mi=1; mi<= wav[i]-1; mi++){
                   2801:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2802:          for (j=1;j<=nlstate+ndeath;j++){
                   2803:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2804:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2805:          }
                   2806:        for(d=0; d<dh[mi][i]; d++){
                   2807:          newm=savm;
1.187     brouard  2808:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2809:          cov[2]=agexact;
                   2810:          if(nagesqr==1)
                   2811:            cov[3]= agexact*agexact;
1.126     brouard  2812:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2813:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2814:          }
                   2815:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2816:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2817:          savm=oldm;
                   2818:          oldm=newm;
                   2819:        } /* end mult */
                   2820:       
                   2821:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2822:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2823:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2824:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2825:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2826:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2827:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2828:         * probability in order to take into account the bias as a fraction of the way
                   2829:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2830:         * -stepm/2 to stepm/2 .
                   2831:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2832:         * For stepm > 1 the results are less biased than in previous versions. 
                   2833:         */
                   2834:        s1=s[mw[mi][i]][i];
                   2835:        s2=s[mw[mi+1][i]][i];
                   2836:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2837:        /* bias bh is positive if real duration
                   2838:         * is higher than the multiple of stepm and negative otherwise.
                   2839:         */
                   2840:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2841:        if( s2 > nlstate){ 
                   2842:          /* i.e. if s2 is a death state and if the date of death is known 
                   2843:             then the contribution to the likelihood is the probability to 
                   2844:             die between last step unit time and current  step unit time, 
                   2845:             which is also equal to probability to die before dh 
                   2846:             minus probability to die before dh-stepm . 
                   2847:             In version up to 0.92 likelihood was computed
                   2848:        as if date of death was unknown. Death was treated as any other
                   2849:        health state: the date of the interview describes the actual state
                   2850:        and not the date of a change in health state. The former idea was
                   2851:        to consider that at each interview the state was recorded
                   2852:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2853:        introduced the exact date of death then we should have modified
                   2854:        the contribution of an exact death to the likelihood. This new
                   2855:        contribution is smaller and very dependent of the step unit
                   2856:        stepm. It is no more the probability to die between last interview
                   2857:        and month of death but the probability to survive from last
                   2858:        interview up to one month before death multiplied by the
                   2859:        probability to die within a month. Thanks to Chris
                   2860:        Jackson for correcting this bug.  Former versions increased
                   2861:        mortality artificially. The bad side is that we add another loop
                   2862:        which slows down the processing. The difference can be up to 10%
                   2863:        lower mortality.
                   2864:          */
1.183     brouard  2865:        /* If, at the beginning of the maximization mostly, the
                   2866:           cumulative probability or probability to be dead is
                   2867:           constant (ie = 1) over time d, the difference is equal to
                   2868:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2869:           s1 at precedent wave, to be dead a month before current
                   2870:           wave is equal to probability, being at state s1 at
                   2871:           precedent wave, to be dead at mont of the current
                   2872:           wave. Then the observed probability (that this person died)
                   2873:           is null according to current estimated parameter. In fact,
                   2874:           it should be very low but not zero otherwise the log go to
                   2875:           infinity.
                   2876:        */
                   2877: /* #ifdef INFINITYORIGINAL */
                   2878: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2879: /* #else */
                   2880: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2881: /*         lli=log(mytinydouble); */
                   2882: /*       else */
                   2883: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2884: /* #endif */
1.216     brouard  2885:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2886:          
                   2887:        } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2888:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2889:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2890:          /*survp += out[s1][j]; */
                   2891:          lli= log(survp);
                   2892:        }
                   2893:        else if  (s2==-4) { 
                   2894:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2895:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2896:          lli= log(survp); 
                   2897:        } 
                   2898:        else if  (s2==-5) { 
                   2899:          for (j=1,survp=0. ; j<=2; j++)  
                   2900:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2901:          lli= log(survp); 
                   2902:        } 
                   2903:        else{
                   2904:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2905:          /*  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 */
                   2906:        } 
                   2907:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2908:        /*if(lli ==000.0)*/
                   2909:        /*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); */
                   2910:        ipmx +=1;
                   2911:        sw += weight[i];
                   2912:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2913:        /* if (lli < log(mytinydouble)){ */
                   2914:        /*   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); */
                   2915:        /*   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]); */
                   2916:        /* } */
1.126     brouard  2917:       } /* end of wave */
                   2918:     } /* end of individual */
                   2919:   }  else if(mle==2){
                   2920:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2921:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2922:       for(mi=1; mi<= wav[i]-1; mi++){
                   2923:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2924:          for (j=1;j<=nlstate+ndeath;j++){
                   2925:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2926:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2927:          }
                   2928:        for(d=0; d<=dh[mi][i]; d++){
                   2929:          newm=savm;
1.187     brouard  2930:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2931:          cov[2]=agexact;
                   2932:          if(nagesqr==1)
                   2933:            cov[3]= agexact*agexact;
1.126     brouard  2934:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2935:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2936:          }
                   2937:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2938:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2939:          savm=oldm;
                   2940:          oldm=newm;
                   2941:        } /* end mult */
                   2942:       
                   2943:        s1=s[mw[mi][i]][i];
                   2944:        s2=s[mw[mi+1][i]][i];
                   2945:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2946:        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 */
                   2947:        ipmx +=1;
                   2948:        sw += weight[i];
                   2949:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2950:       } /* end of wave */
                   2951:     } /* end of individual */
                   2952:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2953:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2954:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2955:       for(mi=1; mi<= wav[i]-1; mi++){
                   2956:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2957:          for (j=1;j<=nlstate+ndeath;j++){
                   2958:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2959:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2960:          }
                   2961:        for(d=0; d<dh[mi][i]; d++){
                   2962:          newm=savm;
1.187     brouard  2963:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2964:          cov[2]=agexact;
                   2965:          if(nagesqr==1)
                   2966:            cov[3]= agexact*agexact;
1.126     brouard  2967:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2968:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2969:          }
                   2970:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2971:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2972:          savm=oldm;
                   2973:          oldm=newm;
                   2974:        } /* end mult */
                   2975:       
                   2976:        s1=s[mw[mi][i]][i];
                   2977:        s2=s[mw[mi+1][i]][i];
                   2978:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2979:        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 */
                   2980:        ipmx +=1;
                   2981:        sw += weight[i];
                   2982:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2983:       } /* end of wave */
                   2984:     } /* end of individual */
                   2985:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2986:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2987:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2988:       for(mi=1; mi<= wav[i]-1; mi++){
                   2989:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2990:          for (j=1;j<=nlstate+ndeath;j++){
                   2991:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2992:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2993:          }
                   2994:        for(d=0; d<dh[mi][i]; d++){
                   2995:          newm=savm;
1.187     brouard  2996:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2997:          cov[2]=agexact;
                   2998:          if(nagesqr==1)
                   2999:            cov[3]= agexact*agexact;
1.126     brouard  3000:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3001:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3002:          }
                   3003:        
                   3004:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3005:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3006:          savm=oldm;
                   3007:          oldm=newm;
                   3008:        } /* end mult */
                   3009:       
                   3010:        s1=s[mw[mi][i]][i];
                   3011:        s2=s[mw[mi+1][i]][i];
                   3012:        if( s2 > nlstate){ 
                   3013:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3014:        } else if  ( s2==-1 ) { /* alive */
                   3015:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3016:            survp += out[s1][j];
                   3017:          lli= log(survp);
1.126     brouard  3018:        }else{
                   3019:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3020:        }
                   3021:        ipmx +=1;
                   3022:        sw += weight[i];
                   3023:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3024: /*     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]); */
                   3025:       } /* end of wave */
                   3026:     } /* end of individual */
                   3027:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3028:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3029:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3030:       for(mi=1; mi<= wav[i]-1; mi++){
                   3031:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3032:          for (j=1;j<=nlstate+ndeath;j++){
                   3033:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3034:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3035:          }
                   3036:        for(d=0; d<dh[mi][i]; d++){
                   3037:          newm=savm;
1.187     brouard  3038:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3039:          cov[2]=agexact;
                   3040:          if(nagesqr==1)
                   3041:            cov[3]= agexact*agexact;
1.126     brouard  3042:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3043:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3044:          }
                   3045:        
                   3046:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3047:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3048:          savm=oldm;
                   3049:          oldm=newm;
                   3050:        } /* end mult */
                   3051:       
                   3052:        s1=s[mw[mi][i]][i];
                   3053:        s2=s[mw[mi+1][i]][i];
                   3054:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3055:        ipmx +=1;
                   3056:        sw += weight[i];
                   3057:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3058:        /*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]);*/
                   3059:       } /* end of wave */
                   3060:     } /* end of individual */
                   3061:   } /* End of if */
                   3062:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3063:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3064:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3065:   return -l;
                   3066: }
                   3067: 
                   3068: /*************** log-likelihood *************/
                   3069: double funcone( double *x)
                   3070: {
                   3071:   /* Same as likeli but slower because of a lot of printf and if */
                   3072:   int i, ii, j, k, mi, d, kk;
1.131     brouard  3073:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3074:   double **out;
                   3075:   double lli; /* Individual log likelihood */
                   3076:   double llt;
                   3077:   int s1, s2;
                   3078:   double bbh, survp;
1.187     brouard  3079:   double agexact;
1.214     brouard  3080:   double agebegin, ageend;
1.126     brouard  3081:   /*extern weight */
                   3082:   /* We are differentiating ll according to initial status */
                   3083:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3084:   /*for(i=1;i<imx;i++) 
                   3085:     printf(" %d\n",s[4][i]);
                   3086:   */
                   3087:   cov[1]=1.;
                   3088: 
                   3089:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   3090: 
                   3091:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3092:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3093:     for(mi=1; mi<= wav[i]-1; mi++){
                   3094:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   3095:        for (j=1;j<=nlstate+ndeath;j++){
                   3096:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3097:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3098:        }
1.214     brouard  3099:       
                   3100:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3101:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3102:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   3103:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3104:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  3105:        newm=savm;
1.187     brouard  3106:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3107:        cov[2]=agexact;
                   3108:        if(nagesqr==1)
                   3109:          cov[3]= agexact*agexact;
1.126     brouard  3110:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3111:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3112:        }
1.187     brouard  3113: 
1.145     brouard  3114:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  3115:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3116:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  3117:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3118:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  3119:        savm=oldm;
                   3120:        oldm=newm;
                   3121:       } /* end mult */
                   3122:       
                   3123:       s1=s[mw[mi][i]][i];
                   3124:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3125:       /* if(s2==-1){ */
                   3126:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3127:       /*       /\* exit(1); *\/ */
                   3128:       /* } */
1.126     brouard  3129:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3130:       /* bias is positive if real duration
                   3131:        * is higher than the multiple of stepm and negative otherwise.
                   3132:        */
                   3133:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   3134:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3135:       } else if  ( s2==-1 ) { /* alive */
1.126     brouard  3136:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3137:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3138:        lli= log(survp);
                   3139:       }else if (mle==1){
                   3140:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3141:       } else if(mle==2){
                   3142:        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 */
                   3143:       } else if(mle==3){  /* exponential inter-extrapolation */
                   3144:        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 */
                   3145:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   3146:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3147:       } else{  /* mle=0 back to 1 */
                   3148:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3149:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3150:       } /* End of if */
                   3151:       ipmx +=1;
                   3152:       sw += weight[i];
                   3153:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3154:       /*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  3155:       if(globpr){
1.214     brouard  3156:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  3157:  %11.6f %11.6f %11.6f ", \
1.214     brouard  3158:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  3159:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3160:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3161:          llt +=ll[k]*gipmx/gsw;
                   3162:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3163:        }
                   3164:        fprintf(ficresilk," %10.6f\n", -llt);
                   3165:       }
                   3166:     } /* end of wave */
                   3167:   } /* end of individual */
                   3168:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3169:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3170:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3171:   if(globpr==0){ /* First time we count the contributions and weights */
                   3172:     gipmx=ipmx;
                   3173:     gsw=sw;
                   3174:   }
                   3175:   return -l;
                   3176: }
                   3177: 
                   3178: 
                   3179: /*************** function likelione ***********/
                   3180: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3181: {
                   3182:   /* This routine should help understanding what is done with 
                   3183:      the selection of individuals/waves and
                   3184:      to check the exact contribution to the likelihood.
                   3185:      Plotting could be done.
                   3186:    */
                   3187:   int k;
                   3188: 
                   3189:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3190:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3191:     strcat(fileresilk,fileresu);
1.126     brouard  3192:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3193:       printf("Problem with resultfile: %s\n", fileresilk);
                   3194:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3195:     }
1.214     brouard  3196:     fprintf(ficresilk, "#individual(line's_record) count ageb ageend 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");
                   3197:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3198:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3199:     for(k=1; k<=nlstate; k++) 
                   3200:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3201:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3202:   }
                   3203: 
                   3204:   *fretone=(*funcone)(p);
                   3205:   if(*globpri !=0){
                   3206:     fclose(ficresilk);
1.205     brouard  3207:     if (mle ==0)
                   3208:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3209:     else if(mle >=1)
                   3210:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3211:     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  3212:     
1.208     brouard  3213:       
                   3214:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3215:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.208     brouard  3216: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3217:     }
1.207     brouard  3218:     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  3219: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3220:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3221: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3222:     fflush(fichtm);
1.205     brouard  3223:   }
1.126     brouard  3224:   return;
                   3225: }
                   3226: 
                   3227: 
                   3228: /*********** Maximum Likelihood Estimation ***************/
                   3229: 
                   3230: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3231: {
1.165     brouard  3232:   int i,j, iter=0;
1.126     brouard  3233:   double **xi;
                   3234:   double fret;
                   3235:   double fretone; /* Only one call to likelihood */
                   3236:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3237: 
                   3238: #ifdef NLOPT
                   3239:   int creturn;
                   3240:   nlopt_opt opt;
                   3241:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3242:   double *lb;
                   3243:   double minf; /* the minimum objective value, upon return */
                   3244:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3245:   myfunc_data dinst, *d = &dinst;
                   3246: #endif
                   3247: 
                   3248: 
1.126     brouard  3249:   xi=matrix(1,npar,1,npar);
                   3250:   for (i=1;i<=npar;i++)
                   3251:     for (j=1;j<=npar;j++)
                   3252:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3253:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3254:   strcpy(filerespow,"POW_"); 
1.126     brouard  3255:   strcat(filerespow,fileres);
                   3256:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3257:     printf("Problem with resultfile: %s\n", filerespow);
                   3258:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3259:   }
                   3260:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3261:   for (i=1;i<=nlstate;i++)
                   3262:     for(j=1;j<=nlstate+ndeath;j++)
                   3263:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3264:   fprintf(ficrespow,"\n");
1.162     brouard  3265: #ifdef POWELL
1.126     brouard  3266:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3267: #endif
1.126     brouard  3268: 
1.162     brouard  3269: #ifdef NLOPT
                   3270: #ifdef NEWUOA
                   3271:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3272: #else
                   3273:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3274: #endif
                   3275:   lb=vector(0,npar-1);
                   3276:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3277:   nlopt_set_lower_bounds(opt, lb);
                   3278:   nlopt_set_initial_step1(opt, 0.1);
                   3279:   
                   3280:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3281:   d->function = func;
                   3282:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3283:   nlopt_set_min_objective(opt, myfunc, d);
                   3284:   nlopt_set_xtol_rel(opt, ftol);
                   3285:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3286:     printf("nlopt failed! %d\n",creturn); 
                   3287:   }
                   3288:   else {
                   3289:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3290:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3291:     iter=1; /* not equal */
                   3292:   }
                   3293:   nlopt_destroy(opt);
                   3294: #endif
1.126     brouard  3295:   free_matrix(xi,1,npar,1,npar);
                   3296:   fclose(ficrespow);
1.203     brouard  3297:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3298:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3299:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3300: 
                   3301: }
                   3302: 
                   3303: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3304: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3305: {
                   3306:   double  **a,**y,*x,pd;
1.203     brouard  3307:   /* double **hess; */
1.164     brouard  3308:   int i, j;
1.126     brouard  3309:   int *indx;
                   3310: 
                   3311:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3312:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3313:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3314:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3315:   double gompertz(double p[]);
1.203     brouard  3316:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3317: 
                   3318:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3319:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3320:   for (i=1;i<=npar;i++){
1.203     brouard  3321:     printf("%d-",i);fflush(stdout);
                   3322:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3323:    
                   3324:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3325:     
                   3326:     /*  printf(" %f ",p[i]);
                   3327:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3328:   }
                   3329:   
                   3330:   for (i=1;i<=npar;i++) {
                   3331:     for (j=1;j<=npar;j++)  {
                   3332:       if (j>i) { 
1.203     brouard  3333:        printf(".%d-%d",i,j);fflush(stdout);
                   3334:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3335:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3336:        
                   3337:        hess[j][i]=hess[i][j];    
                   3338:        /*printf(" %lf ",hess[i][j]);*/
                   3339:       }
                   3340:     }
                   3341:   }
                   3342:   printf("\n");
                   3343:   fprintf(ficlog,"\n");
                   3344: 
                   3345:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3346:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3347:   
                   3348:   a=matrix(1,npar,1,npar);
                   3349:   y=matrix(1,npar,1,npar);
                   3350:   x=vector(1,npar);
                   3351:   indx=ivector(1,npar);
                   3352:   for (i=1;i<=npar;i++)
                   3353:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3354:   ludcmp(a,npar,indx,&pd);
                   3355: 
                   3356:   for (j=1;j<=npar;j++) {
                   3357:     for (i=1;i<=npar;i++) x[i]=0;
                   3358:     x[j]=1;
                   3359:     lubksb(a,npar,indx,x);
                   3360:     for (i=1;i<=npar;i++){ 
                   3361:       matcov[i][j]=x[i];
                   3362:     }
                   3363:   }
                   3364: 
                   3365:   printf("\n#Hessian matrix#\n");
                   3366:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3367:   for (i=1;i<=npar;i++) { 
                   3368:     for (j=1;j<=npar;j++) { 
1.203     brouard  3369:       printf("%.6e ",hess[i][j]);
                   3370:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3371:     }
                   3372:     printf("\n");
                   3373:     fprintf(ficlog,"\n");
                   3374:   }
                   3375: 
1.203     brouard  3376:   /* printf("\n#Covariance matrix#\n"); */
                   3377:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3378:   /* for (i=1;i<=npar;i++) {  */
                   3379:   /*   for (j=1;j<=npar;j++) {  */
                   3380:   /*     printf("%.6e ",matcov[i][j]); */
                   3381:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3382:   /*   } */
                   3383:   /*   printf("\n"); */
                   3384:   /*   fprintf(ficlog,"\n"); */
                   3385:   /* } */
                   3386: 
1.126     brouard  3387:   /* Recompute Inverse */
1.203     brouard  3388:   /* for (i=1;i<=npar;i++) */
                   3389:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3390:   /* ludcmp(a,npar,indx,&pd); */
                   3391: 
                   3392:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3393: 
                   3394:   /* for (j=1;j<=npar;j++) { */
                   3395:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3396:   /*   x[j]=1; */
                   3397:   /*   lubksb(a,npar,indx,x); */
                   3398:   /*   for (i=1;i<=npar;i++){  */
                   3399:   /*     y[i][j]=x[i]; */
                   3400:   /*     printf("%.3e ",y[i][j]); */
                   3401:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3402:   /*   } */
                   3403:   /*   printf("\n"); */
                   3404:   /*   fprintf(ficlog,"\n"); */
                   3405:   /* } */
                   3406: 
                   3407:   /* Verifying the inverse matrix */
                   3408: #ifdef DEBUGHESS
                   3409:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3410: 
1.203     brouard  3411:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3412:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3413: 
                   3414:   for (j=1;j<=npar;j++) {
                   3415:     for (i=1;i<=npar;i++){ 
1.203     brouard  3416:       printf("%.2f ",y[i][j]);
                   3417:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3418:     }
                   3419:     printf("\n");
                   3420:     fprintf(ficlog,"\n");
                   3421:   }
1.203     brouard  3422: #endif
1.126     brouard  3423: 
                   3424:   free_matrix(a,1,npar,1,npar);
                   3425:   free_matrix(y,1,npar,1,npar);
                   3426:   free_vector(x,1,npar);
                   3427:   free_ivector(indx,1,npar);
1.203     brouard  3428:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3429: 
                   3430: 
                   3431: }
                   3432: 
                   3433: /*************** hessian matrix ****************/
                   3434: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3435: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3436:   int i;
                   3437:   int l=1, lmax=20;
1.203     brouard  3438:   double k1,k2, res, fx;
1.132     brouard  3439:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3440:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3441:   int k=0,kmax=10;
                   3442:   double l1;
                   3443: 
                   3444:   fx=func(x);
                   3445:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3446:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3447:     l1=pow(10,l);
                   3448:     delts=delt;
                   3449:     for(k=1 ; k <kmax; k=k+1){
                   3450:       delt = delta*(l1*k);
                   3451:       p2[theta]=x[theta] +delt;
1.145     brouard  3452:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3453:       p2[theta]=x[theta]-delt;
                   3454:       k2=func(p2)-fx;
                   3455:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3456:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3457:       
1.203     brouard  3458: #ifdef DEBUGHESSII
1.126     brouard  3459:       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);
                   3460:       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);
                   3461: #endif
                   3462:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3463:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3464:        k=kmax;
                   3465:       }
                   3466:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3467:        k=kmax; l=lmax*10;
1.126     brouard  3468:       }
                   3469:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3470:        delts=delt;
                   3471:       }
1.203     brouard  3472:     } /* End loop k */
1.126     brouard  3473:   }
                   3474:   delti[theta]=delts;
                   3475:   return res; 
                   3476:   
                   3477: }
                   3478: 
1.203     brouard  3479: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3480: {
                   3481:   int i;
1.164     brouard  3482:   int l=1, lmax=20;
1.126     brouard  3483:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3484:   double p2[MAXPARM+1];
1.203     brouard  3485:   int k, kmax=1;
                   3486:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3487: 
                   3488:   int firstime=0;
1.203     brouard  3489:   
1.126     brouard  3490:   fx=func(x);
1.203     brouard  3491:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3492:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3493:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3494:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3495:     k1=func(p2)-fx;
                   3496:   
1.203     brouard  3497:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3498:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3499:     k2=func(p2)-fx;
                   3500:   
1.203     brouard  3501:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3502:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3503:     k3=func(p2)-fx;
                   3504:   
1.203     brouard  3505:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3506:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3507:     k4=func(p2)-fx;
1.203     brouard  3508:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3509:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3510:       firstime=1;
1.203     brouard  3511:       kmax=kmax+10;
1.208     brouard  3512:     }
                   3513:     if(kmax >=10 || firstime ==1){
1.218     brouard  3514:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3515:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  3516:       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);
                   3517:       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);
                   3518:     }
                   3519: #ifdef DEBUGHESSIJ
                   3520:     v1=hess[thetai][thetai];
                   3521:     v2=hess[thetaj][thetaj];
                   3522:     cv12=res;
                   3523:     /* Computing eigen value of Hessian matrix */
                   3524:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3525:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3526:     if ((lc2 <0) || (lc1 <0) ){
                   3527:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3528:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3529:       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);
                   3530:       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);
                   3531:     }
1.126     brouard  3532: #endif
                   3533:   }
                   3534:   return res;
                   3535: }
                   3536: 
1.203     brouard  3537:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3538: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3539: /* { */
                   3540: /*   int i; */
                   3541: /*   int l=1, lmax=20; */
                   3542: /*   double k1,k2,k3,k4,res,fx; */
                   3543: /*   double p2[MAXPARM+1]; */
                   3544: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3545: /*   int k=0,kmax=10; */
                   3546: /*   double l1; */
                   3547:   
                   3548: /*   fx=func(x); */
                   3549: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3550: /*     l1=pow(10,l); */
                   3551: /*     delts=delt; */
                   3552: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3553: /*       delt = delti*(l1*k); */
                   3554: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3555: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3556: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3557: /*       k1=func(p2)-fx; */
                   3558:       
                   3559: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3560: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3561: /*       k2=func(p2)-fx; */
                   3562:       
                   3563: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3564: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3565: /*       k3=func(p2)-fx; */
                   3566:       
                   3567: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3568: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3569: /*       k4=func(p2)-fx; */
                   3570: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3571: /* #ifdef DEBUGHESSIJ */
                   3572: /*       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); */
                   3573: /*       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); */
                   3574: /* #endif */
                   3575: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3576: /*     k=kmax; */
                   3577: /*       } */
                   3578: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3579: /*     k=kmax; l=lmax*10; */
                   3580: /*       } */
                   3581: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3582: /*     delts=delt; */
                   3583: /*       } */
                   3584: /*     } /\* End loop k *\/ */
                   3585: /*   } */
                   3586: /*   delti[theta]=delts; */
                   3587: /*   return res;  */
                   3588: /* } */
                   3589: 
                   3590: 
1.126     brouard  3591: /************** Inverse of matrix **************/
                   3592: void ludcmp(double **a, int n, int *indx, double *d) 
                   3593: { 
                   3594:   int i,imax,j,k; 
                   3595:   double big,dum,sum,temp; 
                   3596:   double *vv; 
                   3597:  
                   3598:   vv=vector(1,n); 
                   3599:   *d=1.0; 
                   3600:   for (i=1;i<=n;i++) { 
                   3601:     big=0.0; 
                   3602:     for (j=1;j<=n;j++) 
                   3603:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3604:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3605:     vv[i]=1.0/big; 
                   3606:   } 
                   3607:   for (j=1;j<=n;j++) { 
                   3608:     for (i=1;i<j;i++) { 
                   3609:       sum=a[i][j]; 
                   3610:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3611:       a[i][j]=sum; 
                   3612:     } 
                   3613:     big=0.0; 
                   3614:     for (i=j;i<=n;i++) { 
                   3615:       sum=a[i][j]; 
                   3616:       for (k=1;k<j;k++) 
                   3617:        sum -= a[i][k]*a[k][j]; 
                   3618:       a[i][j]=sum; 
                   3619:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3620:        big=dum; 
                   3621:        imax=i; 
                   3622:       } 
                   3623:     } 
                   3624:     if (j != imax) { 
                   3625:       for (k=1;k<=n;k++) { 
                   3626:        dum=a[imax][k]; 
                   3627:        a[imax][k]=a[j][k]; 
                   3628:        a[j][k]=dum; 
                   3629:       } 
                   3630:       *d = -(*d); 
                   3631:       vv[imax]=vv[j]; 
                   3632:     } 
                   3633:     indx[j]=imax; 
                   3634:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3635:     if (j != n) { 
                   3636:       dum=1.0/(a[j][j]); 
                   3637:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3638:     } 
                   3639:   } 
                   3640:   free_vector(vv,1,n);  /* Doesn't work */
                   3641: ;
                   3642: } 
                   3643: 
                   3644: void lubksb(double **a, int n, int *indx, double b[]) 
                   3645: { 
                   3646:   int i,ii=0,ip,j; 
                   3647:   double sum; 
                   3648:  
                   3649:   for (i=1;i<=n;i++) { 
                   3650:     ip=indx[i]; 
                   3651:     sum=b[ip]; 
                   3652:     b[ip]=b[i]; 
                   3653:     if (ii) 
                   3654:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3655:     else if (sum) ii=i; 
                   3656:     b[i]=sum; 
                   3657:   } 
                   3658:   for (i=n;i>=1;i--) { 
                   3659:     sum=b[i]; 
                   3660:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3661:     b[i]=sum/a[i][i]; 
                   3662:   } 
                   3663: } 
                   3664: 
                   3665: void pstamp(FILE *fichier)
                   3666: {
1.196     brouard  3667:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3668: }
                   3669: 
                   3670: /************ Frequencies ********************/
1.214     brouard  3671: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3672:                  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
                   3673:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.126     brouard  3674: {  /* Some frequencies */
                   3675:   
1.164     brouard  3676:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3677:   int mi; /* Effective wave */
1.126     brouard  3678:   int first;
                   3679:   double ***freq; /* Frequencies */
                   3680:   double *pp, **prop;
                   3681:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
1.214     brouard  3682:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3683:   double agebegin, ageend;
                   3684:     
1.126     brouard  3685:   pp=vector(1,nlstate);
1.218     brouard  3686:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   3687:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
1.201     brouard  3688:   strcpy(fileresp,"P_");
                   3689:   strcat(fileresp,fileresu);
1.213     brouard  3690:   /*strcat(fileresphtm,fileresu);*/
1.126     brouard  3691:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3692:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3693:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3694:     exit(0);
                   3695:   }
1.214     brouard  3696: 
1.213     brouard  3697:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3698:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3699:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3700:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3701:     fflush(ficlog);
                   3702:     exit(70); 
                   3703:   }
1.214     brouard  3704:   else{
                   3705:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3706: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3707: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3708:          fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3709:   }
                   3710:     fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
                   3711:     
                   3712:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3713:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3714:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3715:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3716:     fflush(ficlog);
                   3717:     exit(70); 
                   3718:   }
                   3719:   else{
                   3720:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3721: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3722: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3723:          fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3724:   }
                   3725:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
                   3726: 
1.218     brouard  3727:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
1.126     brouard  3728:   j1=0;
                   3729:   
                   3730:   j=cptcoveff;
                   3731:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3732: 
                   3733:   first=1;
                   3734: 
1.214     brouard  3735:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
1.126     brouard  3736:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3737:        scanf("%d", i);*/
                   3738:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3739:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3740:          for(m=iagemin; m <= iagemax+3; m++)
                   3741:            freq[i][jk][m]=0;
1.143     brouard  3742:       
                   3743:       for (i=1; i<=nlstate; i++)  
                   3744:        for(m=iagemin; m <= iagemax+3; m++)
                   3745:          prop[i][m]=0;
1.126     brouard  3746:       
                   3747:       dateintsum=0;
                   3748:       k2cpt=0;
1.214     brouard  3749:       for (i=1; i<=imx; i++) { /* For each individual i */
1.126     brouard  3750:        bool=1;
1.210     brouard  3751:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3752:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3753:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3754:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3755:               bool=0;
1.198     brouard  3756:               /* 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", 
                   3757:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3758:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3759:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3760:             } 
1.210     brouard  3761:        } /* cptcovn > 0 */
1.214     brouard  3762: 
1.126     brouard  3763:        if (bool==1){
1.214     brouard  3764:          /* for(m=firstpass; m<=lastpass; m++){ */
                   3765:          for(mi=1; mi<wav[i];mi++){
                   3766:            m=mw[mi][i];
                   3767:            /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
                   3768:               and mw[mi+1][i]. dh depends on stepm. */
                   3769:            agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3770:            ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
                   3771:            if(m >=firstpass && m <=lastpass){
                   3772:              k2=anint[m][i]+(mint[m][i]/12.);
                   3773:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3774:              if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3775:              if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3776:              if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
                   3777:                prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
1.126     brouard  3778:              if (m<lastpass) {
1.214     brouard  3779:                /* if(s[m][i]==4 && s[m+1][i]==4) */
                   3780:                /*   printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
                   3781:                if(s[m][i]==-1)
                   3782:                  printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
                   3783:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
                   3784:                /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
                   3785:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
1.126     brouard  3786:              }
1.214     brouard  3787:            }  
                   3788:            if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
                   3789:              dateintsum=dateintsum+k2;
                   3790:              k2cpt++;
                   3791:              /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3792:            }
                   3793:            /*}*/
1.210     brouard  3794:          } /* end m */
                   3795:        } /* end bool */
                   3796:       } /* end i = 1 to imx */
1.126     brouard  3797:        
                   3798:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3799:       pstamp(ficresp);
                   3800:       if  (cptcovn>0) {
                   3801:        fprintf(ficresp, "\n#********** Variable "); 
1.214     brouard  3802:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3803:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.213     brouard  3804:        for (z1=1; z1<=cptcoveff; z1++){
                   3805:          fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3806:          fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3807:          fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.213     brouard  3808:        }
                   3809:          fprintf(ficresp, "**********\n#");
1.214     brouard  3810:        fprintf(ficresphtm, "**********</h3>\n");
                   3811:        fprintf(ficresphtmfr, "**********</h3>\n");
1.143     brouard  3812:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3813:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3814:        fprintf(ficlog, "**********\n");
1.126     brouard  3815:       }
1.214     brouard  3816:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.213     brouard  3817:       for(i=1; i<=nlstate;i++) {
1.126     brouard  3818:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
1.213     brouard  3819:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3820:       }
1.126     brouard  3821:       fprintf(ficresp, "\n");
1.213     brouard  3822:       fprintf(ficresphtm, "\n");
1.126     brouard  3823:       
1.214     brouard  3824:       /* Header of frequency table by age */
                   3825:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3826:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   3827:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3828:        for(m=-1; m <=nlstate+ndeath; m++){
                   3829:          if(jk!=0 && m!=0)
                   3830:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3831:        }
                   3832:       }
                   3833:       fprintf(ficresphtmfr, "\n");
                   3834:       
                   3835:       /* For each age */
1.126     brouard  3836:       for(i=iagemin; i <= iagemax+3; i++){
1.213     brouard  3837:        fprintf(ficresphtm,"<tr>");
1.214     brouard  3838:        if(i==iagemax+1){
                   3839:          fprintf(ficlog,"1");
                   3840:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3841:        }else if(i==iagemax+2){
                   3842:          fprintf(ficlog,"0");
                   3843:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3844:        }else if(i==iagemax+3){
1.126     brouard  3845:          fprintf(ficlog,"Total");
1.214     brouard  3846:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.126     brouard  3847:        }else{
                   3848:          if(first==1){
                   3849:            first=0;
                   3850:            printf("See log file for details...\n");
                   3851:          }
1.214     brouard  3852:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
1.126     brouard  3853:          fprintf(ficlog,"Age %d", i);
                   3854:        }
                   3855:        for(jk=1; jk <=nlstate ; jk++){
                   3856:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3857:            pp[jk] += freq[jk][m][i]; 
                   3858:        }
                   3859:        for(jk=1; jk <=nlstate ; jk++){
                   3860:          for(m=-1, pos=0; m <=0 ; m++)
                   3861:            pos += freq[jk][m][i];
                   3862:          if(pp[jk]>=1.e-10){
                   3863:            if(first==1){
1.132     brouard  3864:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3865:            }
                   3866:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3867:          }else{
                   3868:            if(first==1)
                   3869:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3870:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3871:          }
                   3872:        }
                   3873: 
                   3874:        for(jk=1; jk <=nlstate ; jk++){
                   3875:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3876:            pp[jk] += freq[jk][m][i];
                   3877:        }       
                   3878:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3879:          pos += pp[jk];
                   3880:          posprop += prop[jk][i];
                   3881:        }
                   3882:        for(jk=1; jk <=nlstate ; jk++){
                   3883:          if(pos>=1.e-5){
                   3884:            if(first==1)
                   3885:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3886:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3887:          }else{
                   3888:            if(first==1)
                   3889:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3890:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3891:          }
                   3892:          if( i <= iagemax){
                   3893:            if(pos>=1.e-5){
                   3894:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.213     brouard  3895:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.126     brouard  3896:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3897:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3898:            }
1.213     brouard  3899:            else{
1.126     brouard  3900:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
1.213     brouard  3901:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
                   3902:            }
1.126     brouard  3903:          }
                   3904:        }
                   3905:        
1.214     brouard  3906:        for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3907:          for(m=-1; m <=nlstate+ndeath; m++){
                   3908:            if(freq[jk][m][i] !=0 ) { /* minimizing output */
                   3909:              if(first==1){
                   3910:                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3911:              }
1.126     brouard  3912:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3913:            }
1.214     brouard  3914:            if(jk!=0 && m!=0)
                   3915:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
                   3916:          }
                   3917:        }
                   3918:        fprintf(ficresphtmfr,"</tr>\n ");
1.213     brouard  3919:        if(i <= iagemax){
1.126     brouard  3920:          fprintf(ficresp,"\n");
1.213     brouard  3921:          fprintf(ficresphtm,"</tr>\n");
                   3922:        }
1.126     brouard  3923:        if(first==1)
                   3924:          printf("Others in log...\n");
                   3925:        fprintf(ficlog,"\n");
1.210     brouard  3926:       } /* end loop i */
1.213     brouard  3927:       fprintf(ficresphtm,"</table>\n");
1.214     brouard  3928:       fprintf(ficresphtmfr,"</table>\n");
1.145     brouard  3929:       /*}*/
1.210     brouard  3930:   } /* end j1 */
1.126     brouard  3931:   dateintmean=dateintsum/k2cpt; 
                   3932:  
                   3933:   fclose(ficresp);
1.213     brouard  3934:   fclose(ficresphtm);
1.214     brouard  3935:   fclose(ficresphtmfr);
1.218     brouard  3936:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
1.126     brouard  3937:   free_vector(pp,1,nlstate);
1.218     brouard  3938:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
1.126     brouard  3939:   /* End of Freq */
                   3940: }
                   3941: 
                   3942: /************ Prevalence ********************/
                   3943: 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)
                   3944: {  
                   3945:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3946:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3947:      We still use firstpass and lastpass as another selection.
                   3948:   */
                   3949:  
1.164     brouard  3950:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3951:   int mi; /* Effective wave */
                   3952:   int iage;
                   3953:   double agebegin, ageend;
1.164     brouard  3954: 
                   3955:   double **prop;
                   3956:   double posprop; 
1.126     brouard  3957:   double  y2; /* in fractional years */
                   3958:   int iagemin, iagemax;
1.145     brouard  3959:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3960: 
                   3961:   iagemin= (int) agemin;
                   3962:   iagemax= (int) agemax;
                   3963:   /*pp=vector(1,nlstate);*/
1.218     brouard  3964:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
1.126     brouard  3965:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3966:   j1=0;
                   3967:   
1.145     brouard  3968:   /*j=cptcoveff;*/
1.126     brouard  3969:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3970:   
1.145     brouard  3971:   first=1;
1.219   ! brouard  3972:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
1.214     brouard  3973:     for (i=1; i<=nlstate; i++)  
1.218     brouard  3974:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   3975:                                prop[i][iage]=0.0;
1.214     brouard  3976:     
                   3977:     for (i=1; i<=imx; i++) { /* Each individual */
                   3978:       bool=1;
                   3979:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.219   ! brouard  3980:                                for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
1.218     brouard  3981:                                        if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   3982:                                                bool=0;
1.214     brouard  3983:       } 
1.219   ! brouard  3984:       if (bool==1) { /* For this combination of covariates values, this individual fits */
1.218     brouard  3985:                                /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   3986:                                for(mi=1; mi<wav[i];mi++){
                   3987:                                        m=mw[mi][i];
                   3988:                                        agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3989:                                        /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   3990:                                        if(m >=firstpass && m <=lastpass){
                   3991:                                                y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3992:                                                if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3993:                                                        if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3994:                                                        if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3995:                                                        if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   3996:                                                                printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
                   3997:                                                                exit(1);
                   3998:                                                        }
                   3999:                                                        if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4000:                                                                /*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]]);*/
                   4001:                                                                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4002:                                                                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4003:                                                        } /* end valid statuses */ 
                   4004:                                                } /* end selection of dates */
                   4005:                                        } /* end selection of waves */
                   4006:                                } /* end effective waves */
1.214     brouard  4007:       } /* end bool */
                   4008:     }
                   4009:     for(i=iagemin; i <= iagemax+3; i++){  
                   4010:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
1.218     brouard  4011:                                posprop += prop[jk][i]; 
1.214     brouard  4012:       } 
                   4013:       
                   4014:       for(jk=1; jk <=nlstate ; jk++){      
1.218     brouard  4015:                                if( i <=  iagemax){ 
                   4016:                                        if(posprop>=1.e-5){ 
                   4017:                                                probs[i][jk][j1]= prop[jk][i]/posprop;
                   4018:                                        } else{
                   4019:                                                if(first==1){
                   4020:                                                        first=0;
                   4021:                                                        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]);
                   4022:                                                }
                   4023:                                        }
                   4024:                                } 
1.214     brouard  4025:       }/* end jk */ 
                   4026:     }/* end i */ 
1.145     brouard  4027:     /*} *//* end i1 */
                   4028:   } /* end j1 */
1.126     brouard  4029:   
                   4030:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4031:   /*free_vector(pp,1,nlstate);*/
1.218     brouard  4032:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
1.126     brouard  4033: }  /* End of prevalence */
                   4034: 
                   4035: /************* Waves Concatenation ***************/
                   4036: 
                   4037: 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)
                   4038: {
                   4039:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4040:      Death is a valid wave (if date is known).
                   4041:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4042:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4043:      and mw[mi+1][i]. dh depends on stepm.
                   4044:      */
                   4045: 
                   4046:   int i, mi, m;
                   4047:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4048:      double sum=0., jmean=0.;*/
1.218     brouard  4049:   int first, firstwo, firsthree, firstfour;
1.126     brouard  4050:   int j, k=0,jk, ju, jl;
                   4051:   double sum=0.;
                   4052:   first=0;
1.214     brouard  4053:   firstwo=0;
1.217     brouard  4054:   firsthree=0;
1.218     brouard  4055:   firstfour=0;
1.164     brouard  4056:   jmin=100000;
1.126     brouard  4057:   jmax=-1;
                   4058:   jmean=0.;
1.214     brouard  4059:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  4060:     mi=0;
                   4061:     m=firstpass;
1.214     brouard  4062:     while(s[m][i] <= nlstate){  /* a live state */
1.216     brouard  4063:       if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
1.126     brouard  4064:        mw[++mi][i]=m;
1.216     brouard  4065:       }
                   4066:       if(m >=lastpass){
                   4067:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
1.217     brouard  4068:          if(firsthree == 0){
                   4069:            printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
                   4070:            firsthree=1;
                   4071:          }
1.218     brouard  4072:          fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
1.216     brouard  4073:          mw[++mi][i]=m;
                   4074:        }
                   4075:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4076:          nbwarn++;
                   4077:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4078:            printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4079:            fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4080:          }
                   4081:          break;
                   4082:        }
1.126     brouard  4083:        break;
1.216     brouard  4084:       }
1.126     brouard  4085:       else
                   4086:        m++;
                   4087:     }/* end while */
1.216     brouard  4088:     
                   4089:     /* After last pass */
1.214     brouard  4090:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  4091:       mi++;    /* Death is another wave */
                   4092:       /* if(mi==0)  never been interviewed correctly before death */
                   4093:         /* Only death is a correct wave */
                   4094:       mw[mi][i]=m;
1.216     brouard  4095:     }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
                   4096:       /* m++; */
                   4097:       /* mi++; */
                   4098:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4099:       /* mw[mi][i]=m; */
                   4100:       nberr++;
1.218     brouard  4101:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
                   4102:        if(firstwo==0){
                   4103:          printf("Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4104:          firstwo=1;
                   4105:        }
                   4106:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4107:       }else{ /* end date of interview is known */
                   4108:        /* death is known but not confirmed by death status at any wave */
                   4109:        if(firstfour==0){
                   4110:          printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4111:          firstfour=1;
                   4112:        }
                   4113:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.214     brouard  4114:       }
1.126     brouard  4115:     }
                   4116:     wav[i]=mi;
                   4117:     if(mi==0){
                   4118:       nbwarn++;
                   4119:       if(first==0){
                   4120:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4121:        first=1;
                   4122:       }
                   4123:       if(first==1){
                   4124:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   4125:       }
                   4126:     } /* end mi==0 */
                   4127:   } /* End individuals */
1.214     brouard  4128:   /* wav and mw are no more changed */
1.126     brouard  4129: 
1.214     brouard  4130:   
1.126     brouard  4131:   for(i=1; i<=imx; i++){
                   4132:     for(mi=1; mi<wav[i];mi++){
                   4133:       if (stepm <=0)
                   4134:        dh[mi][i]=1;
                   4135:       else{
                   4136:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4137:          if (agedc[i] < 2*AGESUP) {
                   4138:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4139:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4140:            else if(j<0){
                   4141:              nberr++;
                   4142:              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]);
                   4143:              j=1; /* Temporary Dangerous patch */
                   4144:              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);
                   4145:              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]);
                   4146:              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);
                   4147:            }
                   4148:            k=k+1;
                   4149:            if (j >= jmax){
                   4150:              jmax=j;
                   4151:              ijmax=i;
                   4152:            }
                   4153:            if (j <= jmin){
                   4154:              jmin=j;
                   4155:              ijmin=i;
                   4156:            }
                   4157:            sum=sum+j;
                   4158:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4159:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4160:          }
                   4161:        }
                   4162:        else{
                   4163:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   4164: /*       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]); */
                   4165: 
                   4166:          k=k+1;
                   4167:          if (j >= jmax) {
                   4168:            jmax=j;
                   4169:            ijmax=i;
                   4170:          }
                   4171:          else if (j <= jmin){
                   4172:            jmin=j;
                   4173:            ijmin=i;
                   4174:          }
                   4175:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4176:          /*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]);*/
                   4177:          if(j<0){
                   4178:            nberr++;
                   4179:            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]);
                   4180:            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]);
                   4181:          }
                   4182:          sum=sum+j;
                   4183:        }
                   4184:        jk= j/stepm;
                   4185:        jl= j -jk*stepm;
                   4186:        ju= j -(jk+1)*stepm;
                   4187:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4188:          if(jl==0){
                   4189:            dh[mi][i]=jk;
                   4190:            bh[mi][i]=0;
                   4191:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  4192:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  4193:            dh[mi][i]=jk+1;
                   4194:            bh[mi][i]=ju;
                   4195:          }
                   4196:        }else{
                   4197:          if(jl <= -ju){
                   4198:            dh[mi][i]=jk;
                   4199:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4200:                                 * is higher than the multiple of stepm and negative otherwise.
                   4201:                                 */
                   4202:          }
                   4203:          else{
                   4204:            dh[mi][i]=jk+1;
                   4205:            bh[mi][i]=ju;
                   4206:          }
                   4207:          if(dh[mi][i]==0){
                   4208:            dh[mi][i]=1; /* At least one step */
                   4209:            bh[mi][i]=ju; /* At least one step */
                   4210:            /*  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);*/
                   4211:          }
                   4212:        } /* end if mle */
                   4213:       }
                   4214:     } /* end wave */
                   4215:   }
                   4216:   jmean=sum/k;
                   4217:   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  4218:   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  4219:  }
                   4220: 
                   4221: /*********** Tricode ****************************/
1.145     brouard  4222: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4223: {
1.144     brouard  4224:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4225:   /*     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  4226:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  4227:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  4228:    * nbcode[Tvar[j]][1]= 
1.144     brouard  4229:   */
1.130     brouard  4230: 
1.145     brouard  4231:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4232:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4233:   int cptcode=0; /* Modality max of covariates j */
                   4234:   int modmincovj=0; /* Modality min of covariates j */
                   4235: 
                   4236: 
1.126     brouard  4237:   cptcoveff=0; 
                   4238:  
1.144     brouard  4239:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4240: 
1.145     brouard  4241:   /* Loop on covariates without age and products */
1.186     brouard  4242:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  4243:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  4244:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.219   ! brouard  4245:                                                                                                                                modality of this covariate Vj*/ 
1.145     brouard  4246:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
1.219   ! brouard  4247:                                                                                                                                                * If product of Vn*Vm, still boolean *:
        !          4248:                                                                                                                                                * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
        !          4249:                                                                                                                                                * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
1.145     brouard  4250:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  4251:                                      modality of the nth covariate of individual i. */
1.145     brouard  4252:       if (ij > modmaxcovj)
                   4253:         modmaxcovj=ij; 
                   4254:       else if (ij < modmincovj) 
1.219   ! brouard  4255:                                modmincovj=ij; 
1.145     brouard  4256:       if ((ij < -1) && (ij > NCOVMAX)){
1.219   ! brouard  4257:                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
        !          4258:                                exit(1);
1.145     brouard  4259:       }else
1.136     brouard  4260:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  4261:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  4262:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  4263:       /* getting the maximum value of the modality of the covariate
                   4264:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4265:         female is 1, then modmaxcovj=1.*/
1.192     brouard  4266:     } /* end for loop on individuals i */
1.145     brouard  4267:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  4268:     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  4269:     cptcode=modmaxcovj;
1.137     brouard  4270:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  4271:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  4272:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4273:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4274:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4275:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
1.219   ! brouard  4276:                                if( k != -1){
        !          4277:                                        ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
        !          4278:                                                                                                                 covariate for which somebody answered excluding 
        !          4279:                                                                                                                 undefined. Usually 2: 0 and 1. */
        !          4280:                                }
        !          4281:                                ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
        !          4282:                                                                                                                                covariate for which somebody answered including 
        !          4283:                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  4284:       }
                   4285:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
1.219   ! brouard  4286:                                 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  4287:     } /* Ndum[-1] number of undefined modalities */
1.219   ! brouard  4288:                
1.136     brouard  4289:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  4290:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4291:        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  4292:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  4293:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4294:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4295:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  4296:        nbcode[Tvar[j]][ij]=k;
                   4297:        nbcode[Tvar[j]][1]=0;
                   4298:        nbcode[Tvar[j]][2]=1;
                   4299:        nbcode[Tvar[j]][3]=2;
1.197     brouard  4300:        To be continued (not working yet).
1.145     brouard  4301:     */
1.197     brouard  4302:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4303:     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*/
                   4304:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.219   ! brouard  4305:                                break;
        !          4306:                        }
1.192     brouard  4307:        ij++;
1.197     brouard  4308:        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  4309:        cptcode = ij; /* New max modality for covar j */
                   4310:     } /* end of loop on modality i=-1 to 1 or more */
                   4311:       
                   4312:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4313:     /*         /\*recode from 0 *\/ */
                   4314:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4315:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4316:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4317:     /*         } */
                   4318:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4319:     /*         if (ij > ncodemax[j]) { */
                   4320:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4321:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4322:     /*           break; */
                   4323:     /*         } */
                   4324:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4325:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4326:   
1.219   ! brouard  4327:        for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  4328:   
1.187     brouard  4329:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.219   ! brouard  4330:                /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
        !          4331:                ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
        !          4332:                Ndum[ij]++; /* Might be supersed V1 + V1*age */
        !          4333:        } 
        !          4334:        
        !          4335:        ij=0;
        !          4336:        for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
        !          4337:                /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
        !          4338:                if((Ndum[i]!=0) && (i<=ncovcol)){
        !          4339:                        ij++;
        !          4340:                        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
        !          4341:                        Tvaraff[ij]=i; /*For printing (unclear) */
        !          4342:                }else{
        !          4343:                        /* Tvaraff[ij]=0; */
        !          4344:                }
        !          4345:        }
        !          4346:        /* ij--; */
        !          4347:        cptcoveff=ij; /*Number of total covariates*/
        !          4348:        
1.126     brouard  4349: }
                   4350: 
1.145     brouard  4351: 
1.126     brouard  4352: /*********** Health Expectancies ****************/
                   4353: 
1.127     brouard  4354: 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  4355: 
                   4356: {
                   4357:   /* Health expectancies, no variances */
1.164     brouard  4358:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4359:   int nhstepma, nstepma; /* Decreasing with age */
                   4360:   double age, agelim, hf;
                   4361:   double ***p3mat;
                   4362:   double eip;
                   4363: 
                   4364:   pstamp(ficreseij);
                   4365:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4366:   fprintf(ficreseij,"# Age");
                   4367:   for(i=1; i<=nlstate;i++){
                   4368:     for(j=1; j<=nlstate;j++){
                   4369:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4370:     }
                   4371:     fprintf(ficreseij," e%1d. ",i);
                   4372:   }
                   4373:   fprintf(ficreseij,"\n");
                   4374: 
                   4375:   
                   4376:   if(estepm < stepm){
                   4377:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4378:   }
                   4379:   else  hstepm=estepm;   
                   4380:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4381:    * This is mainly to measure the difference between two models: for example
                   4382:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4383:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4384:    * progression in between and thus overestimating or underestimating according
                   4385:    * to the curvature of the survival function. If, for the same date, we 
                   4386:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4387:    * to compare the new estimate of Life expectancy with the same linear 
                   4388:    * hypothesis. A more precise result, taking into account a more precise
                   4389:    * curvature will be obtained if estepm is as small as stepm. */
                   4390: 
                   4391:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4392:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4393:      nhstepm is the number of hstepm from age to agelim 
                   4394:      nstepm is the number of stepm from age to agelin. 
                   4395:      Look at hpijx to understand the reason of that which relies in memory size
                   4396:      and note for a fixed period like estepm months */
                   4397:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4398:      survival function given by stepm (the optimization length). Unfortunately it
                   4399:      means that if the survival funtion is printed only each two years of age and if
                   4400:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4401:      results. So we changed our mind and took the option of the best precision.
                   4402:   */
                   4403:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4404: 
                   4405:   agelim=AGESUP;
                   4406:   /* If stepm=6 months */
                   4407:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4408:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4409:     
                   4410: /* nhstepm age range expressed in number of stepm */
                   4411:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4412:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4413:   /* if (stepm >= YEARM) hstepm=1;*/
                   4414:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4415:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4416: 
                   4417:   for (age=bage; age<=fage; age ++){ 
                   4418:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4419:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4420:     /* if (stepm >= YEARM) hstepm=1;*/
                   4421:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4422: 
                   4423:     /* If stepm=6 months */
                   4424:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4425:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4426:     
                   4427:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4428:     
                   4429:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4430:     
                   4431:     printf("%d|",(int)age);fflush(stdout);
                   4432:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4433:     
                   4434:     /* Computing expectancies */
                   4435:     for(i=1; i<=nlstate;i++)
                   4436:       for(j=1; j<=nlstate;j++)
                   4437:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4438:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4439:          
                   4440:          /* 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]);*/
                   4441: 
                   4442:        }
                   4443: 
                   4444:     fprintf(ficreseij,"%3.0f",age );
                   4445:     for(i=1; i<=nlstate;i++){
                   4446:       eip=0;
                   4447:       for(j=1; j<=nlstate;j++){
                   4448:        eip +=eij[i][j][(int)age];
                   4449:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4450:       }
                   4451:       fprintf(ficreseij,"%9.4f", eip );
                   4452:     }
                   4453:     fprintf(ficreseij,"\n");
                   4454:     
                   4455:   }
                   4456:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4457:   printf("\n");
                   4458:   fprintf(ficlog,"\n");
                   4459:   
                   4460: }
                   4461: 
1.127     brouard  4462: 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  4463: 
                   4464: {
                   4465:   /* Covariances of health expectancies eij and of total life expectancies according
                   4466:    to initial status i, ei. .
                   4467:   */
                   4468:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4469:   int nhstepma, nstepma; /* Decreasing with age */
                   4470:   double age, agelim, hf;
                   4471:   double ***p3matp, ***p3matm, ***varhe;
                   4472:   double **dnewm,**doldm;
                   4473:   double *xp, *xm;
                   4474:   double **gp, **gm;
                   4475:   double ***gradg, ***trgradg;
                   4476:   int theta;
                   4477: 
                   4478:   double eip, vip;
                   4479: 
                   4480:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4481:   xp=vector(1,npar);
                   4482:   xm=vector(1,npar);
                   4483:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4484:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4485:   
                   4486:   pstamp(ficresstdeij);
                   4487:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4488:   fprintf(ficresstdeij,"# Age");
                   4489:   for(i=1; i<=nlstate;i++){
                   4490:     for(j=1; j<=nlstate;j++)
                   4491:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4492:     fprintf(ficresstdeij," e%1d. ",i);
                   4493:   }
                   4494:   fprintf(ficresstdeij,"\n");
                   4495: 
                   4496:   pstamp(ficrescveij);
                   4497:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4498:   fprintf(ficrescveij,"# Age");
                   4499:   for(i=1; i<=nlstate;i++)
                   4500:     for(j=1; j<=nlstate;j++){
                   4501:       cptj= (j-1)*nlstate+i;
                   4502:       for(i2=1; i2<=nlstate;i2++)
                   4503:        for(j2=1; j2<=nlstate;j2++){
                   4504:          cptj2= (j2-1)*nlstate+i2;
                   4505:          if(cptj2 <= cptj)
                   4506:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4507:        }
                   4508:     }
                   4509:   fprintf(ficrescveij,"\n");
                   4510:   
                   4511:   if(estepm < stepm){
                   4512:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4513:   }
                   4514:   else  hstepm=estepm;   
                   4515:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4516:    * This is mainly to measure the difference between two models: for example
                   4517:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4518:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4519:    * progression in between and thus overestimating or underestimating according
                   4520:    * to the curvature of the survival function. If, for the same date, we 
                   4521:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4522:    * to compare the new estimate of Life expectancy with the same linear 
                   4523:    * hypothesis. A more precise result, taking into account a more precise
                   4524:    * curvature will be obtained if estepm is as small as stepm. */
                   4525: 
                   4526:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4527:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4528:      nhstepm is the number of hstepm from age to agelim 
                   4529:      nstepm is the number of stepm from age to agelin. 
                   4530:      Look at hpijx to understand the reason of that which relies in memory size
                   4531:      and note for a fixed period like estepm months */
                   4532:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4533:      survival function given by stepm (the optimization length). Unfortunately it
                   4534:      means that if the survival funtion is printed only each two years of age and if
                   4535:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4536:      results. So we changed our mind and took the option of the best precision.
                   4537:   */
                   4538:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4539: 
                   4540:   /* If stepm=6 months */
                   4541:   /* nhstepm age range expressed in number of stepm */
                   4542:   agelim=AGESUP;
                   4543:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4544:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4545:   /* if (stepm >= YEARM) hstepm=1;*/
                   4546:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4547:   
                   4548:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4549:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4550:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4551:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4552:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4553:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4554: 
                   4555:   for (age=bage; age<=fage; age ++){ 
                   4556:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4557:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4558:     /* if (stepm >= YEARM) hstepm=1;*/
                   4559:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  4560:                
1.126     brouard  4561:     /* If stepm=6 months */
                   4562:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4563:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4564:     
                   4565:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  4566:                
1.126     brouard  4567:     /* Computing  Variances of health expectancies */
                   4568:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4569:        decrease memory allocation */
                   4570:     for(theta=1; theta <=npar; theta++){
                   4571:       for(i=1; i<=npar; i++){ 
1.218     brouard  4572:                                xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4573:                                xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  4574:       }
                   4575:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4576:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
1.218     brouard  4577:                        
1.126     brouard  4578:       for(j=1; j<= nlstate; j++){
1.218     brouard  4579:                                for(i=1; i<=nlstate; i++){
                   4580:                                        for(h=0; h<=nhstepm-1; h++){
                   4581:                                                gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4582:                                                gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4583:                                        }
                   4584:                                }
1.126     brouard  4585:       }
1.218     brouard  4586:                        
1.126     brouard  4587:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.218     brouard  4588:                                for(h=0; h<=nhstepm-1; h++){
                   4589:                                        gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4590:                                }
1.126     brouard  4591:     }/* End theta */
                   4592:     
                   4593:     
                   4594:     for(h=0; h<=nhstepm-1; h++)
                   4595:       for(j=1; j<=nlstate*nlstate;j++)
1.218     brouard  4596:                                for(theta=1; theta <=npar; theta++)
                   4597:                                        trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  4598:     
1.218     brouard  4599:                
                   4600:                for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  4601:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.218     brouard  4602:                                varhe[ij][ji][(int)age] =0.;
                   4603:                
                   4604:                printf("%d|",(int)age);fflush(stdout);
                   4605:                fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4606:                for(h=0;h<=nhstepm-1;h++){
1.126     brouard  4607:       for(k=0;k<=nhstepm-1;k++){
1.218     brouard  4608:                                matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4609:                                matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4610:                                for(ij=1;ij<=nlstate*nlstate;ij++)
                   4611:                                        for(ji=1;ji<=nlstate*nlstate;ji++)
                   4612:                                                varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  4613:       }
                   4614:     }
1.218     brouard  4615:                
1.126     brouard  4616:     /* Computing expectancies */
                   4617:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4618:     for(i=1; i<=nlstate;i++)
                   4619:       for(j=1; j<=nlstate;j++)
1.218     brouard  4620:                                for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4621:                                        eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4622:                                        
                   4623:                                        /* 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]);*/
                   4624:                                        
                   4625:                                }
                   4626:                
1.126     brouard  4627:     fprintf(ficresstdeij,"%3.0f",age );
                   4628:     for(i=1; i<=nlstate;i++){
                   4629:       eip=0.;
                   4630:       vip=0.;
                   4631:       for(j=1; j<=nlstate;j++){
1.218     brouard  4632:                                eip += eij[i][j][(int)age];
                   4633:                                for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4634:                                        vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4635:                                fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
1.126     brouard  4636:       }
                   4637:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4638:     }
                   4639:     fprintf(ficresstdeij,"\n");
1.218     brouard  4640:                
1.126     brouard  4641:     fprintf(ficrescveij,"%3.0f",age );
                   4642:     for(i=1; i<=nlstate;i++)
                   4643:       for(j=1; j<=nlstate;j++){
1.218     brouard  4644:                                cptj= (j-1)*nlstate+i;
                   4645:                                for(i2=1; i2<=nlstate;i2++)
                   4646:                                        for(j2=1; j2<=nlstate;j2++){
                   4647:                                                cptj2= (j2-1)*nlstate+i2;
                   4648:                                                if(cptj2 <= cptj)
                   4649:                                                        fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4650:                                        }
1.126     brouard  4651:       }
                   4652:     fprintf(ficrescveij,"\n");
1.218     brouard  4653:                
1.126     brouard  4654:   }
                   4655:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4656:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4657:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4658:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4659:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4660:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4661:   printf("\n");
                   4662:   fprintf(ficlog,"\n");
1.218     brouard  4663:        
1.126     brouard  4664:   free_vector(xm,1,npar);
                   4665:   free_vector(xp,1,npar);
                   4666:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4667:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4668:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4669: }
1.218     brouard  4670:  
1.126     brouard  4671: /************ Variance ******************/
1.209     brouard  4672:  void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.218     brouard  4673:  {
                   4674:    /* Variance of health expectancies */
                   4675:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4676:    /* double **newm;*/
                   4677:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4678:   
                   4679:    /* int movingaverage(); */
                   4680:    double **dnewm,**doldm;
                   4681:    double **dnewmp,**doldmp;
                   4682:    int i, j, nhstepm, hstepm, h, nstepm ;
                   4683:    int k;
                   4684:    double *xp;
                   4685:    double **gp, **gm;  /* for var eij */
                   4686:    double ***gradg, ***trgradg; /*for var eij */
                   4687:    double **gradgp, **trgradgp; /* for var p point j */
                   4688:    double *gpp, *gmp; /* for var p point j */
                   4689:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4690:    double ***p3mat;
                   4691:    double age,agelim, hf;
                   4692:    /* double ***mobaverage; */
                   4693:    int theta;
                   4694:    char digit[4];
                   4695:    char digitp[25];
                   4696: 
                   4697:    char fileresprobmorprev[FILENAMELENGTH];
                   4698: 
                   4699:    if(popbased==1){
                   4700:      if(mobilav!=0)
                   4701:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4702:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   4703:    }
                   4704:    else 
                   4705:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  4706: 
1.218     brouard  4707:    /* if (mobilav!=0) { */
                   4708:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4709:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   4710:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   4711:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   4712:    /*   } */
                   4713:    /* } */
                   4714: 
                   4715:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   4716:    sprintf(digit,"%-d",ij);
                   4717:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4718:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4719:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   4720:    strcat(fileresprobmorprev,fileresu);
                   4721:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4722:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4723:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4724:    }
                   4725:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4726:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4727:    pstamp(ficresprobmorprev);
                   4728:    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);
                   4729:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4730:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4731:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   4732:      for(i=1; i<=nlstate;i++)
                   4733:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4734:    }  
                   4735:    fprintf(ficresprobmorprev,"\n");
                   4736:   
                   4737:    fprintf(ficgp,"\n# Routine varevsij");
                   4738:    fprintf(ficgp,"\nunset title \n");
                   4739:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   4740:    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");
                   4741:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4742:    /*   } */
                   4743:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4744:    pstamp(ficresvij);
                   4745:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4746:    if(popbased==1)
                   4747:      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);
                   4748:    else
                   4749:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4750:    fprintf(ficresvij,"# Age");
                   4751:    for(i=1; i<=nlstate;i++)
                   4752:      for(j=1; j<=nlstate;j++)
                   4753:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4754:    fprintf(ficresvij,"\n");
                   4755: 
                   4756:    xp=vector(1,npar);
                   4757:    dnewm=matrix(1,nlstate,1,npar);
                   4758:    doldm=matrix(1,nlstate,1,nlstate);
                   4759:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4760:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4761: 
                   4762:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4763:    gpp=vector(nlstate+1,nlstate+ndeath);
                   4764:    gmp=vector(nlstate+1,nlstate+ndeath);
                   4765:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  4766:   
1.218     brouard  4767:    if(estepm < stepm){
                   4768:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   4769:    }
                   4770:    else  hstepm=estepm;   
                   4771:    /* For example we decided to compute the life expectancy with the smallest unit */
                   4772:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4773:       nhstepm is the number of hstepm from age to agelim 
                   4774:       nstepm is the number of stepm from age to agelim. 
                   4775:       Look at function hpijx to understand why because of memory size limitations, 
                   4776:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   4777:       survival function given by stepm (the optimization length). Unfortunately it
                   4778:       means that if the survival funtion is printed every two years of age and if
                   4779:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4780:       results. So we changed our mind and took the option of the best precision.
                   4781:    */
                   4782:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4783:    agelim = AGESUP;
                   4784:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4785:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4786:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4787:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4788:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4789:      gp=matrix(0,nhstepm,1,nlstate);
                   4790:      gm=matrix(0,nhstepm,1,nlstate);
                   4791:                
                   4792:                
                   4793:      for(theta=1; theta <=npar; theta++){
                   4794:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4795:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4796:        }
                   4797:                        
                   4798:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4799:                        
                   4800:        if (popbased==1) {
                   4801:         if(mobilav ==0){
                   4802:           for(i=1; i<=nlstate;i++)
                   4803:             prlim[i][i]=probs[(int)age][i][ij];
                   4804:         }else{ /* mobilav */ 
                   4805:           for(i=1; i<=nlstate;i++)
                   4806:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4807:         }
                   4808:        }
                   4809:                        
                   4810:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   4811:        for(j=1; j<= nlstate; j++){
                   4812:         for(h=0; h<=nhstepm; h++){
                   4813:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4814:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4815:         }
                   4816:        }
                   4817:        /* Next for computing probability of death (h=1 means
                   4818:          computed over hstepm matrices product = hstepm*stepm months) 
                   4819:          as a weighted average of prlim.
                   4820:        */
                   4821:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4822:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4823:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4824:        }    
                   4825:        /* end probability of death */
                   4826:                        
                   4827:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4828:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4829:                        
                   4830:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   4831:                        
                   4832:        if (popbased==1) {
                   4833:         if(mobilav ==0){
                   4834:           for(i=1; i<=nlstate;i++)
                   4835:             prlim[i][i]=probs[(int)age][i][ij];
                   4836:         }else{ /* mobilav */ 
                   4837:           for(i=1; i<=nlstate;i++)
                   4838:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4839:         }
                   4840:        }
                   4841:                        
                   4842:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4843:                        
                   4844:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   4845:         for(h=0; h<=nhstepm; h++){
                   4846:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4847:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4848:         }
                   4849:        }
                   4850:        /* This for computing probability of death (h=1 means
                   4851:          computed over hstepm matrices product = hstepm*stepm months) 
                   4852:          as a weighted average of prlim.
                   4853:        */
                   4854:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4855:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4856:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4857:        }    
                   4858:        /* end probability of death */
                   4859:                        
                   4860:        for(j=1; j<= nlstate; j++) /* vareij */
                   4861:         for(h=0; h<=nhstepm; h++){
                   4862:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4863:         }
                   4864:                        
                   4865:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4866:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4867:        }
                   4868:                        
                   4869:      } /* End theta */
                   4870:                
                   4871:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4872:                
                   4873:      for(h=0; h<=nhstepm; h++) /* veij */
                   4874:        for(j=1; j<=nlstate;j++)
                   4875:         for(theta=1; theta <=npar; theta++)
                   4876:           trgradg[h][j][theta]=gradg[h][theta][j];
                   4877:                
                   4878:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4879:        for(theta=1; theta <=npar; theta++)
                   4880:         trgradgp[j][theta]=gradgp[theta][j];
                   4881:                
                   4882:                
                   4883:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4884:      for(i=1;i<=nlstate;i++)
                   4885:        for(j=1;j<=nlstate;j++)
                   4886:         vareij[i][j][(int)age] =0.;
                   4887:                
                   4888:      for(h=0;h<=nhstepm;h++){
                   4889:        for(k=0;k<=nhstepm;k++){
                   4890:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4891:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4892:         for(i=1;i<=nlstate;i++)
                   4893:           for(j=1;j<=nlstate;j++)
                   4894:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4895:        }
                   4896:      }
                   4897:                
                   4898:      /* pptj */
                   4899:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4900:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4901:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4902:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4903:         varppt[j][i]=doldmp[j][i];
                   4904:      /* end ppptj */
                   4905:      /*  x centered again */
                   4906:                
                   4907:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4908:                
                   4909:      if (popbased==1) {
                   4910:        if(mobilav ==0){
                   4911:         for(i=1; i<=nlstate;i++)
                   4912:           prlim[i][i]=probs[(int)age][i][ij];
                   4913:        }else{ /* mobilav */ 
                   4914:         for(i=1; i<=nlstate;i++)
                   4915:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   4916:        }
                   4917:      }
                   4918:                
                   4919:      /* This for computing probability of death (h=1 means
                   4920:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4921:        as a weighted average of prlim.
                   4922:      */
                   4923:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4924:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4925:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4926:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4927:      }    
                   4928:      /* end probability of death */
                   4929:                
                   4930:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4931:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4932:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4933:        for(i=1; i<=nlstate;i++){
                   4934:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4935:        }
                   4936:      } 
                   4937:      fprintf(ficresprobmorprev,"\n");
                   4938:                
                   4939:      fprintf(ficresvij,"%.0f ",age );
                   4940:      for(i=1; i<=nlstate;i++)
                   4941:        for(j=1; j<=nlstate;j++){
                   4942:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4943:        }
                   4944:      fprintf(ficresvij,"\n");
                   4945:      free_matrix(gp,0,nhstepm,1,nlstate);
                   4946:      free_matrix(gm,0,nhstepm,1,nlstate);
                   4947:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4948:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4949:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4950:    } /* End age */
                   4951:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4952:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4953:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4954:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4955:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4956:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   4957:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   4958:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   4959:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   4960:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4961:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4962:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4963:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   4964:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   4965:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   4966:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   4967:    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);
                   4968:    /*  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  4969:     */
1.218     brouard  4970:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   4971:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4972: 
1.218     brouard  4973:    free_vector(xp,1,npar);
                   4974:    free_matrix(doldm,1,nlstate,1,nlstate);
                   4975:    free_matrix(dnewm,1,nlstate,1,npar);
                   4976:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4977:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4978:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4979:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4980:    fclose(ficresprobmorprev);
                   4981:    fflush(ficgp);
                   4982:    fflush(fichtm); 
                   4983:  }  /* end varevsij */
1.126     brouard  4984: 
                   4985: /************ Variance of prevlim ******************/
1.209     brouard  4986:  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, char strstart[])
1.126     brouard  4987: {
1.205     brouard  4988:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4989:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4990: 
1.126     brouard  4991:   double **dnewm,**doldm;
                   4992:   int i, j, nhstepm, hstepm;
                   4993:   double *xp;
                   4994:   double *gp, *gm;
                   4995:   double **gradg, **trgradg;
1.208     brouard  4996:   double **mgm, **mgp;
1.126     brouard  4997:   double age,agelim;
                   4998:   int theta;
                   4999:   
                   5000:   pstamp(ficresvpl);
                   5001:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5002:   fprintf(ficresvpl,"# Age");
                   5003:   for(i=1; i<=nlstate;i++)
                   5004:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5005:   fprintf(ficresvpl,"\n");
                   5006: 
                   5007:   xp=vector(1,npar);
                   5008:   dnewm=matrix(1,nlstate,1,npar);
                   5009:   doldm=matrix(1,nlstate,1,nlstate);
                   5010:   
                   5011:   hstepm=1*YEARM; /* Every year of age */
                   5012:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5013:   agelim = AGESUP;
                   5014:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5015:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5016:     if (stepm >= YEARM) hstepm=1;
                   5017:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5018:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5019:     mgp=matrix(1,npar,1,nlstate);
                   5020:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5021:     gp=vector(1,nlstate);
                   5022:     gm=vector(1,nlstate);
                   5023: 
                   5024:     for(theta=1; theta <=npar; theta++){
                   5025:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5026:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5027:       }
1.209     brouard  5028:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5029:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5030:       else
                   5031:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5032:       for(i=1;i<=nlstate;i++){
1.126     brouard  5033:        gp[i] = prlim[i][i];
1.208     brouard  5034:        mgp[theta][i] = prlim[i][i];
                   5035:       }
1.126     brouard  5036:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5037:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5038:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5039:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5040:       else
                   5041:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5042:       for(i=1;i<=nlstate;i++){
1.126     brouard  5043:        gm[i] = prlim[i][i];
1.208     brouard  5044:        mgm[theta][i] = prlim[i][i];
                   5045:       }
1.126     brouard  5046:       for(i=1;i<=nlstate;i++)
                   5047:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5048:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5049:     } /* End theta */
                   5050: 
                   5051:     trgradg =matrix(1,nlstate,1,npar);
                   5052: 
                   5053:     for(j=1; j<=nlstate;j++)
                   5054:       for(theta=1; theta <=npar; theta++)
                   5055:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5056:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5057:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5058:     /*   for(j=1; j<=nlstate;j++){ */
                   5059:     /*         printf(" %d ",j); */
                   5060:     /*         for(theta=1; theta <=npar; theta++) */
                   5061:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5062:     /*         printf("\n "); */
                   5063:     /*   } */
                   5064:     /* } */
                   5065:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5066:     /*   printf("\n gradg %d ",(int)age); */
                   5067:     /*   for(j=1; j<=nlstate;j++){ */
                   5068:     /*         printf("%d ",j); */
                   5069:     /*         for(theta=1; theta <=npar; theta++) */
                   5070:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5071:     /*         printf("\n "); */
                   5072:     /*   } */
                   5073:     /* } */
1.126     brouard  5074: 
                   5075:     for(i=1;i<=nlstate;i++)
                   5076:       varpl[i][(int)age] =0.;
1.209     brouard  5077:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5078:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5079:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5080:     }else{
1.126     brouard  5081:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5082:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5083:     }
1.126     brouard  5084:     for(i=1;i<=nlstate;i++)
                   5085:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5086: 
                   5087:     fprintf(ficresvpl,"%.0f ",age );
                   5088:     for(i=1; i<=nlstate;i++)
                   5089:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5090:     fprintf(ficresvpl,"\n");
                   5091:     free_vector(gp,1,nlstate);
                   5092:     free_vector(gm,1,nlstate);
1.208     brouard  5093:     free_matrix(mgm,1,npar,1,nlstate);
                   5094:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5095:     free_matrix(gradg,1,npar,1,nlstate);
                   5096:     free_matrix(trgradg,1,nlstate,1,npar);
                   5097:   } /* End age */
                   5098: 
                   5099:   free_vector(xp,1,npar);
                   5100:   free_matrix(doldm,1,nlstate,1,npar);
                   5101:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5102: 
                   5103: }
                   5104: 
                   5105: /************ Variance of one-step probabilities  ******************/
                   5106: 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[])
                   5107: {
1.164     brouard  5108:   int i, j=0,  k1, l1, tj;
1.126     brouard  5109:   int k2, l2, j1,  z1;
1.164     brouard  5110:   int k=0, l;
1.145     brouard  5111:   int first=1, first1, first2;
1.126     brouard  5112:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5113:   double **dnewm,**doldm;
                   5114:   double *xp;
                   5115:   double *gp, *gm;
                   5116:   double **gradg, **trgradg;
                   5117:   double **mu;
1.164     brouard  5118:   double age, cov[NCOVMAX+1];
1.126     brouard  5119:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5120:   int theta;
                   5121:   char fileresprob[FILENAMELENGTH];
                   5122:   char fileresprobcov[FILENAMELENGTH];
                   5123:   char fileresprobcor[FILENAMELENGTH];
                   5124:   double ***varpij;
                   5125: 
1.201     brouard  5126:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  5127:   strcat(fileresprob,fileres);
                   5128:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5129:     printf("Problem with resultfile: %s\n", fileresprob);
                   5130:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5131:   }
1.201     brouard  5132:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  5133:   strcat(fileresprobcov,fileresu);
1.126     brouard  5134:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5135:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   5136:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5137:   }
1.201     brouard  5138:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  5139:   strcat(fileresprobcor,fileresu);
1.126     brouard  5140:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5141:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   5142:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5143:   }
                   5144:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5145:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5146:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5147:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5148:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5149:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5150:   pstamp(ficresprob);
                   5151:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5152:   fprintf(ficresprob,"# Age");
                   5153:   pstamp(ficresprobcov);
                   5154:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5155:   fprintf(ficresprobcov,"# Age");
                   5156:   pstamp(ficresprobcor);
                   5157:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5158:   fprintf(ficresprobcor,"# Age");
                   5159: 
                   5160: 
                   5161:   for(i=1; i<=nlstate;i++)
                   5162:     for(j=1; j<=(nlstate+ndeath);j++){
                   5163:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5164:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5165:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5166:     }  
                   5167:  /* fprintf(ficresprob,"\n");
                   5168:   fprintf(ficresprobcov,"\n");
                   5169:   fprintf(ficresprobcor,"\n");
                   5170:  */
1.131     brouard  5171:   xp=vector(1,npar);
1.126     brouard  5172:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5173:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5174:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5175:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5176:   first=1;
                   5177:   fprintf(ficgp,"\n# Routine varprob");
                   5178:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5179:   fprintf(fichtm,"\n");
                   5180: 
1.200     brouard  5181:   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  5182:   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);
                   5183:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5184: and drawn. It helps understanding how is the covariance between two incidences.\
                   5185:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   5186:   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. \
                   5187: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5188: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5189: standard deviations wide on each axis. <br>\
                   5190:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5191:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5192: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5193: 
                   5194:   cov[1]=1;
1.145     brouard  5195:   /* tj=cptcoveff; */
                   5196:   tj = (int) pow(2,cptcoveff);
1.126     brouard  5197:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5198:   j1=0;
1.145     brouard  5199:   for(j1=1; j1<=tj;j1++){
                   5200:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   5201:     /*j1++;*/
1.126     brouard  5202:       if  (cptcovn>0) {
                   5203:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  5204:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5205:        fprintf(ficresprob, "**********\n#\n");
                   5206:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  5207:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5208:        fprintf(ficresprobcov, "**********\n#\n");
                   5209:        
                   5210:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  5211:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5212:        fprintf(ficgp, "**********\n#\n");
                   5213:        
                   5214:        
                   5215:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  5216:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5217:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5218:        
                   5219:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  5220:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5221:        fprintf(ficresprobcor, "**********\n#");    
                   5222:       }
                   5223:       
1.145     brouard  5224:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5225:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5226:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5227:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  5228:       for (age=bage; age<=fage; age ++){ 
                   5229:        cov[2]=age;
1.187     brouard  5230:        if(nagesqr==1)
                   5231:          cov[3]= age*age;
1.126     brouard  5232:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  5233:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5234:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  5235:                                                         * 1  1 1 1 1
                   5236:                                                         * 2  2 1 1 1
                   5237:                                                         * 3  1 2 1 1
                   5238:                                                         */
                   5239:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  5240:        }
1.186     brouard  5241:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  5242:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  5243:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  5244:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  5245:        
                   5246:     
                   5247:        for(theta=1; theta <=npar; theta++){
                   5248:          for(i=1; i<=npar; i++)
                   5249:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   5250:          
                   5251:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5252:          
                   5253:          k=0;
                   5254:          for(i=1; i<= (nlstate); i++){
                   5255:            for(j=1; j<=(nlstate+ndeath);j++){
                   5256:              k=k+1;
                   5257:              gp[k]=pmmij[i][j];
                   5258:            }
                   5259:          }
                   5260:          
                   5261:          for(i=1; i<=npar; i++)
                   5262:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   5263:     
                   5264:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5265:          k=0;
                   5266:          for(i=1; i<=(nlstate); i++){
                   5267:            for(j=1; j<=(nlstate+ndeath);j++){
                   5268:              k=k+1;
                   5269:              gm[k]=pmmij[i][j];
                   5270:            }
                   5271:          }
                   5272:      
                   5273:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5274:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5275:        }
                   5276: 
                   5277:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5278:          for(theta=1; theta <=npar; theta++)
                   5279:            trgradg[j][theta]=gradg[theta][j];
                   5280:        
                   5281:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5282:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   5283: 
                   5284:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   5285:        
                   5286:        k=0;
                   5287:        for(i=1; i<=(nlstate); i++){
                   5288:          for(j=1; j<=(nlstate+ndeath);j++){
                   5289:            k=k+1;
                   5290:            mu[k][(int) age]=pmmij[i][j];
                   5291:          }
                   5292:        }
                   5293:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5294:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5295:            varpij[i][j][(int)age] = doldm[i][j];
                   5296: 
                   5297:        /*printf("\n%d ",(int)age);
                   5298:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5299:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5300:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5301:          }*/
                   5302: 
                   5303:        fprintf(ficresprob,"\n%d ",(int)age);
                   5304:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5305:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   5306: 
                   5307:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5308:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5309:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5310:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5311:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5312:        }
                   5313:        i=0;
                   5314:        for (k=1; k<=(nlstate);k++){
                   5315:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  5316:            i++;
1.126     brouard  5317:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5318:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5319:            for (j=1; j<=i;j++){
1.145     brouard  5320:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  5321:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5322:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5323:            }
                   5324:          }
                   5325:        }/* end of loop for state */
                   5326:       } /* end of loop for age */
1.145     brouard  5327:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5328:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5329:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5330:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5331:       
1.126     brouard  5332:       /* Confidence intervalle of pij  */
                   5333:       /*
1.131     brouard  5334:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  5335:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5336:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5337:        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);
                   5338:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5339:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5340:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5341:       */
                   5342: 
                   5343:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  5344:       first1=1;first2=2;
1.126     brouard  5345:       for (k2=1; k2<=(nlstate);k2++){
                   5346:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5347:          if(l2==k2) continue;
                   5348:          j=(k2-1)*(nlstate+ndeath)+l2;
                   5349:          for (k1=1; k1<=(nlstate);k1++){
                   5350:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5351:              if(l1==k1) continue;
                   5352:              i=(k1-1)*(nlstate+ndeath)+l1;
                   5353:              if(i<=j) continue;
                   5354:              for (age=bage; age<=fage; age ++){ 
                   5355:                if ((int)age %5==0){
                   5356:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5357:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5358:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5359:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   5360:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   5361:                  c12=cv12/sqrt(v1*v2);
                   5362:                  /* Computing eigen value of matrix of covariance */
                   5363:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5364:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  5365:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  5366:                    if(first2==1){
                   5367:                      first1=0;
                   5368:                    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);
                   5369:                    }
                   5370:                    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);
                   5371:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5372:                    /* lc2=fabs(lc2); */
1.135     brouard  5373:                  }
                   5374: 
1.126     brouard  5375:                  /* Eigen vectors */
                   5376:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5377:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   5378:                  v21=(lc1-v1)/cv12*v11;
                   5379:                  v12=-v21;
                   5380:                  v22=v11;
                   5381:                  tnalp=v21/v11;
                   5382:                  if(first1==1){
                   5383:                    first1=0;
                   5384:                    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);
                   5385:                  }
                   5386:                  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);
                   5387:                  /*printf(fignu*/
                   5388:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5389:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5390:                  if(first==1){
                   5391:                    first=0;
1.200     brouard  5392:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  5393:                    fprintf(ficgp,"\nset parametric;unset label");
                   5394:                    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  5395:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  5396:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  5397:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   5398: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   5399:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   5400:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5401:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  5402:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  5403:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  5404:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5405:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5406:                    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",\
                   5407:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   5408:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5409:                  }else{
                   5410:                    first=0;
                   5411:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5412:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5413:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5414:                    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",\
                   5415:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   5416:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5417:                  }/* if first */
                   5418:                } /* age mod 5 */
                   5419:              } /* end loop age */
1.201     brouard  5420:              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  5421:              first=1;
                   5422:            } /*l12 */
                   5423:          } /* k12 */
                   5424:        } /*l1 */
                   5425:       }/* k1 */
1.169     brouard  5426:       /* } */ /* loop covariates */
1.126     brouard  5427:   }
                   5428:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5429:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5430:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5431:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5432:   free_vector(xp,1,npar);
                   5433:   fclose(ficresprob);
                   5434:   fclose(ficresprobcov);
                   5435:   fclose(ficresprobcor);
                   5436:   fflush(ficgp);
                   5437:   fflush(fichtmcov);
                   5438: }
                   5439: 
                   5440: 
                   5441: /******************* Printing html file ***********/
1.201     brouard  5442: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5443:                  int lastpass, int stepm, int weightopt, char model[],\
                   5444:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5445:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5446:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5447:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5448:   int jj1, k1, i1, cpt;
                   5449: 
                   5450:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5451:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5452: </ul>");
1.214     brouard  5453:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5454:    fprintf(fichtm,"<li>- Observed frequency between two states (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file)<br/>\n",
                   5455:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5456:    fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
1.213     brouard  5457:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5458:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5459:    fprintf(fichtm,"\
                   5460:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5461:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5462:    fprintf(fichtm,"\
1.217     brouard  5463:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5464:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5465:    fprintf(fichtm,"\
1.126     brouard  5466:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5467:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5468:    fprintf(fichtm,"\
1.217     brouard  5469:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5470:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5471:    fprintf(fichtm,"\
1.211     brouard  5472:  - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
1.126     brouard  5473:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5474:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5475:    if(prevfcast==1){
                   5476:      fprintf(fichtm,"\
                   5477:  - Prevalence projections by age and states:                           \
1.201     brouard  5478:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5479:    }
1.126     brouard  5480: 
                   5481: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   5482: 
1.145     brouard  5483:  m=pow(2,cptcoveff);
1.126     brouard  5484:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5485: 
                   5486:  jj1=0;
                   5487:  for(k1=1; k1<=m;k1++){
1.192     brouard  5488:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5489:      jj1++;
                   5490:      if (cptcovn > 0) {
                   5491:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  5492:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  5493:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5494:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  5495:        }
1.126     brouard  5496:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5497:      }
1.201     brouard  5498:      /* aij, bij */
1.211     brouard  5499:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
                   5500: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  5501:      /* Pij */
1.211     brouard  5502:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  5503: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  5504:      /* Quasi-incidences */
1.211     brouard  5505:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.201     brouard  5506:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211     brouard  5507:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5508: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
1.201     brouard  5509: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   5510:      /* Survival functions (period) in state j */
                   5511:      for(cpt=1; cpt<=nlstate;cpt++){
                   5512:        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> \
                   5513: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   5514:      }
                   5515:      /* State specific survival functions (period) */
                   5516:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  5517:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  5518:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   5519:  <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);
                   5520:      }
                   5521:      /* Period (stable) prevalence in each health state */
                   5522:      for(cpt=1; cpt<=nlstate;cpt++){
1.217     brouard  5523:        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> \
1.201     brouard  5524: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   5525:      }
1.217     brouard  5526:     if(backcast==1){
                   5527:      /* Period (stable) back prevalence in each health state */
                   5528:      for(cpt=1; cpt<=nlstate;cpt++){
                   5529:        fprintf(fichtm,"<br>\n- Convergence to period (stable) back 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> \
                   5530: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
                   5531:      }
                   5532:     }
1.211     brouard  5533:     if(prevfcast==1){
                   5534:       /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5535:       for(cpt=1; cpt<=nlstate;cpt++){
1.214     brouard  5536:        fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
1.213     brouard  5537: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
1.211     brouard  5538:       }
                   5539:     }
                   5540: 
1.126     brouard  5541:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  5542:        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  5543: <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  5544:      }
1.192     brouard  5545:    /* } /\* end i1 *\/ */
1.126     brouard  5546:  }/* End k1 */
                   5547:  fprintf(fichtm,"</ul>");
                   5548: 
                   5549:  fprintf(fichtm,"\
                   5550: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5551:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5552:  - 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  5553: But because parameters are usually highly correlated (a higher incidence of disability \
                   5554: and a higher incidence of recovery can give very close observed transition) it might \
                   5555: be very useful to look not only at linear confidence intervals estimated from the \
                   5556: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5557: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5558: covariance matrix of the one-step probabilities. \
                   5559: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5560: 
1.193     brouard  5561:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5562:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  5563:  fprintf(fichtm,"\
                   5564:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5565:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5566: 
                   5567:  fprintf(fichtm,"\
                   5568:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5569:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  5570:  fprintf(fichtm,"\
                   5571:  - 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): \
                   5572:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5573:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  5574:  fprintf(fichtm,"\
                   5575:  - (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): \
                   5576:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5577:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  5578:  fprintf(fichtm,"\
1.128     brouard  5579:  - 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  5580:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  5581:  fprintf(fichtm,"\
1.128     brouard  5582:  - 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  5583:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  5584:  fprintf(fichtm,"\
                   5585:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  5586:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5587: 
                   5588: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5589: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5590: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5591: /*     <br>",fileres,fileres,fileres,fileres); */
                   5592: /*  else  */
                   5593: /*    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); */
                   5594:  fflush(fichtm);
                   5595:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5596: 
1.145     brouard  5597:  m=pow(2,cptcoveff);
1.126     brouard  5598:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5599: 
                   5600:  jj1=0;
                   5601:  for(k1=1; k1<=m;k1++){
1.192     brouard  5602:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5603:      jj1++;
                   5604:      if (cptcovn > 0) {
                   5605:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5606:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  5607:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5608:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5609:      }
                   5610:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  5611:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   5612: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  5613: <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  5614:      }
                   5615:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5616: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5617: true period expectancies (those weighted with period prevalences are also\
                   5618:  drawn in addition to the population based expectancies computed using\
1.218     brouard  5619:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  5620: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  5621:    /* } /\* end i1 *\/ */
1.126     brouard  5622:  }/* End k1 */
                   5623:  fprintf(fichtm,"</ul>");
                   5624:  fflush(fichtm);
                   5625: }
                   5626: 
                   5627: /******************* Gnuplot file **************/
1.218     brouard  5628:  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  5629: 
                   5630:   char dirfileres[132],optfileres[132];
1.164     brouard  5631:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5632:   int lv=0, vlv=0, kl=0;
1.130     brouard  5633:   int ng=0;
1.201     brouard  5634:   int vpopbased;
1.219   ! brouard  5635:        int ioffset; /* variable offset for columns */
        !          5636: 
1.126     brouard  5637: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5638: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5639: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5640: /*   } */
                   5641: 
                   5642:   /*#ifdef windows */
                   5643:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5644:     /*#endif */
                   5645:   m=pow(2,cptcoveff);
                   5646: 
1.202     brouard  5647:   /* Contribution to likelihood */
                   5648:   /* Plot the probability implied in the likelihood */
                   5649:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5650:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5651:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5652:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5653: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5654:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5655: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5656:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5657:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5658:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
1.204     brouard  5659:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5660:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
1.204     brouard  5661:     for (i=1; i<= nlstate ; i ++) {
                   5662:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5663:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214     brouard  5664:       fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
1.204     brouard  5665:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.219   ! brouard  5666:                                fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
1.204     brouard  5667:       }
                   5668:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5669:     }
                   5670:     /* 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 */             
                   5671:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5672:     /* 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  5673:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5674:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5675: 
1.126     brouard  5676:   strcpy(dirfileres,optionfilefiname);
                   5677:   strcpy(optfileres,"vpl");
                   5678:  /* 1eme*/
1.211     brouard  5679:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
                   5680:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
                   5681:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5682:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
1.219   ! brouard  5683:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          5684:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
        !          5685:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5686:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5687:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5688:                                vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
        !          5689:                        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
        !          5690:                                fprintf(ficgp," V%d=%d ",k,vlv);
1.211     brouard  5691:       }
                   5692:       fprintf(ficgp,"\n#\n");
                   5693: 
1.219   ! brouard  5694:                        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
        !          5695:                        fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
        !          5696:                        fprintf(ficgp,"set xlabel \"Age\" \n\
        !          5697: set ylabel \"Probability\" \n  \
        !          5698: set ter svg size 640, 480\n    \
1.201     brouard  5699: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.219   ! brouard  5700:                        
        !          5701:                        for (i=1; i<= nlstate ; i ++) {
        !          5702:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          5703:                                else        fprintf(ficgp," %%*lf (%%*lf)");
        !          5704:                        }
        !          5705:                        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);
        !          5706:                        for (i=1; i<= nlstate ; i ++) {
        !          5707:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          5708:                                else fprintf(ficgp," %%*lf (%%*lf)");
        !          5709:                        } 
        !          5710:                        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); 
        !          5711:                        for (i=1; i<= nlstate ; i ++) {
        !          5712:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          5713:                                else fprintf(ficgp," %%*lf (%%*lf)");
        !          5714:                        }  
        !          5715:                        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));
        !          5716:                        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
        !          5717:                                /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
        !          5718:                                fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
        !          5719:                                kl=0;
        !          5720:                                for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
        !          5721:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
        !          5722:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5723:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5724:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5725:                                        vlv= nbcode[Tvaraff[k]][lv];
        !          5726:                                        kl++;
        !          5727:                                        /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
        !          5728:                                        /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
        !          5729:                                        /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
        !          5730:                                        /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
        !          5731:                                        if(k==cptcoveff){
        !          5732:                                                        fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, k,kl+1+1,nbcode[Tvaraff[k]][lv], \
        !          5733:                                                                                4+(cpt-1),  cpt );
        !          5734:                                        }else{
        !          5735:                                                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, k,kl+1+1,nbcode[Tvaraff[k]][lv]);
        !          5736:                                                kl++;
        !          5737:                                        }
        !          5738:                                } /* end covariate */
        !          5739:                        }
        !          5740:                        fprintf(ficgp,"\nset out \n");
1.201     brouard  5741:     } /* k1 */
                   5742:   } /* cpt */
1.126     brouard  5743:   /*2 eme*/
                   5744:   for (k1=1; k1<= m ; k1 ++) { 
1.211     brouard  5745:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5746:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.219   ! brouard  5747:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5748:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5749:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5750:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5751:                                vlv= nbcode[Tvaraff[k]][lv];
        !          5752:                                fprintf(ficgp," V%d=%d ",k,vlv);
1.211     brouard  5753:       }
                   5754:       fprintf(ficgp,"\n#\n");
1.219   ! brouard  5755:                        
        !          5756:                        fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
        !          5757:                        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
        !          5758:                                if(vpopbased==0)
        !          5759:                                        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
        !          5760:                                else
        !          5761:                                        fprintf(ficgp,"\nreplot ");
        !          5762:                                for (i=1; i<= nlstate+1 ; i ++) {
        !          5763:                                        k=2*i;
        !          5764:                                        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);
        !          5765:                                        for (j=1; j<= nlstate+1 ; j ++) {
        !          5766:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          5767:                                                else fprintf(ficgp," %%*lf (%%*lf)");
        !          5768:                                        }   
        !          5769:                                        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
        !          5770:                                        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
        !          5771:                                        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);
        !          5772:                                        for (j=1; j<= nlstate+1 ; j ++) {
        !          5773:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          5774:                                                else fprintf(ficgp," %%*lf (%%*lf)");
        !          5775:                                        }   
        !          5776:                                        fprintf(ficgp,"\" t\"\" w l lt 0,");
        !          5777:                                        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);
        !          5778:                                        for (j=1; j<= nlstate+1 ; j ++) {
        !          5779:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          5780:                                                else fprintf(ficgp," %%*lf (%%*lf)");
        !          5781:                                        }   
        !          5782:                                        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
        !          5783:                                        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
        !          5784:                                } /* state */
        !          5785:                        } /* vpopbased */
        !          5786:                        fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.201     brouard  5787:   } /* k1 */
1.219   ! brouard  5788:        
        !          5789:        
1.126     brouard  5790:   /*3eme*/
                   5791:   for (k1=1; k1<= m ; k1 ++) { 
                   5792:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5793:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5794:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.219   ! brouard  5795:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5796:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5797:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5798:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5799:                                vlv= nbcode[Tvaraff[k]][lv];
        !          5800:                                fprintf(ficgp," V%d=%d ",k,vlv);
1.211     brouard  5801:       }
                   5802:       fprintf(ficgp,"\n#\n");
1.219   ! brouard  5803:                        
1.126     brouard  5804:       /*       k=2+nlstate*(2*cpt-2); */
                   5805:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5806:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5807:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5808: 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  5809:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.219   ! brouard  5810:                                for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          5811:                                fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
        !          5812:                                fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
        !          5813:                                for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          5814:                                fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
        !          5815:                                
1.126     brouard  5816:       */
                   5817:       for (i=1; i< nlstate ; i ++) {
1.219   ! brouard  5818:                                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);
        !          5819:                                /*      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);*/
        !          5820:                                
1.126     brouard  5821:       } 
1.201     brouard  5822:       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  5823:     }
                   5824:   }
                   5825:   
1.201     brouard  5826:   /* Survival functions (period) from state i in state j by initial state i */
                   5827:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5828:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5829:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5830:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5831:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5832:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5833:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5834:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.219   ! brouard  5835:        vlv= nbcode[Tvaraff[k]][lv];
1.211     brouard  5836:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5837:       }
                   5838:       fprintf(ficgp,"\n#\n");
                   5839: 
1.201     brouard  5840:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5841:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5842: set ter svg size 640, 480\n\
                   5843: unset log y\n\
                   5844: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5845:       k=3;
1.201     brouard  5846:       for (i=1; i<= nlstate ; i ++){
1.217     brouard  5847:        if(i==1){
1.201     brouard  5848:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.217     brouard  5849:        }else{
1.201     brouard  5850:          fprintf(ficgp,", '' ");
1.217     brouard  5851:        }
1.201     brouard  5852:        l=(nlstate+ndeath)*(i-1)+1;
                   5853:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5854:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5855:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5856:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5857:       } /* nlstate */
                   5858:       fprintf(ficgp,"\nset out\n");
                   5859:     } /* end cpt state*/ 
                   5860:   } /* end covariate */  
                   5861: 
                   5862:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5863:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5864:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5865:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
1.211     brouard  5866:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5867:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5868:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5869:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5870:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.219   ! brouard  5871:        vlv= nbcode[Tvaraff[k]][lv];
1.211     brouard  5872:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5873:       }
                   5874:       fprintf(ficgp,"\n#\n");
                   5875: 
1.201     brouard  5876:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5877:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5878: set ter svg size 640, 480\n\
                   5879: unset log y\n\
                   5880: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5881:       k=3;
1.201     brouard  5882:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5883:        if(j==1)
                   5884:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5885:        else
                   5886:          fprintf(ficgp,", '' ");
                   5887:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5888:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5889:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5890:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5891:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5892:       } /* nlstate */
                   5893:       fprintf(ficgp,", '' ");
                   5894:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5895:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5896:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5897:        if(j < nlstate)
                   5898:          fprintf(ficgp,"$%d +",k+l);
                   5899:        else
                   5900:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5901:       }
                   5902:       fprintf(ficgp,"\nset out\n");
                   5903:     } /* end cpt state*/ 
                   5904:   } /* end covariate */  
                   5905: 
1.202     brouard  5906:   /* CV preval stable (period) for each covariate */
1.211     brouard  5907:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  5908:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5909:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   5910:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5911:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5912:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5913:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5914:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.219   ! brouard  5915:        vlv= nbcode[Tvaraff[k]][lv];
1.211     brouard  5916:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5917:       }
                   5918:       fprintf(ficgp,"\n#\n");
                   5919: 
1.201     brouard  5920:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5921:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5922: set ter svg size 640, 480\n\
1.126     brouard  5923: unset log y\n\
1.153     brouard  5924: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5925:       k=3; /* Offset */
1.153     brouard  5926:       for (i=1; i<= nlstate ; i ++){
                   5927:        if(i==1)
1.201     brouard  5928:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5929:        else
                   5930:          fprintf(ficgp,", '' ");
1.154     brouard  5931:        l=(nlstate+ndeath)*(i-1)+1;
                   5932:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5933:        for (j=2; j<= nlstate ; j ++)
                   5934:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5935:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5936:       } /* nlstate */
1.201     brouard  5937:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5938:     } /* end cpt state*/ 
                   5939:   } /* end covariate */  
1.218     brouard  5940:   if(backcast == 1){
1.217     brouard  5941:     /* CV back preval stable (period) for each covariate */
1.218     brouard  5942:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   5943:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5944:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   5945:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5946:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5947:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5948:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5949:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.219   ! brouard  5950:          vlv= nbcode[Tvaraff[k]][lv];
1.218     brouard  5951:          fprintf(ficgp," V%d=%d ",k,vlv);
                   5952:        }
                   5953:        fprintf(ficgp,"\n#\n");
                   5954:        
                   5955:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   5956:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   5957: set ter svg size 640, 480\n                                            \
                   5958: unset log y\n                                                          \
                   5959: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5960:        k=3; /* Offset */
                   5961:        for (i=1; i<= nlstate ; i ++){
                   5962:          if(i==1)
                   5963:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   5964:          else
                   5965:            fprintf(ficgp,", '' ");
                   5966:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   5967:          l=(nlstate+ndeath)*(cpt-1)+1;
                   5968:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   5969:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   5970:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   5971:          /* for (j=2; j<= nlstate ; j ++) */
                   5972:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   5973:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   5974:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   5975:        } /* nlstate */
                   5976:        fprintf(ficgp,"\nset out\n");
                   5977:       } /* end cpt state*/ 
                   5978:     } /* end covariate */  
                   5979:   } /* End if backcast */
                   5980:   
                   5981:   if(prevfcast==1){
                   5982:     /* Projection from cross-sectional to stable (period) for each covariate */
                   5983:     
                   5984:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  5985:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.219   ! brouard  5986:                                fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
        !          5987:                                for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
        !          5988:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
        !          5989:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5990:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5991:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5992:                                        vlv= nbcode[Tvaraff[k]][lv];
        !          5993:                                        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5994:                                }
        !          5995:                                fprintf(ficgp,"\n#\n");
        !          5996:                                
        !          5997:                                fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
        !          5998:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
        !          5999:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
        !          6000: set ter svg size 640, 480\n    \
        !          6001: unset log y\n  \
        !          6002: plot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          6003:                                for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
        !          6004:                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          6005:                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
        !          6006:                                        /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          6007:                                        /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
        !          6008:                                        if(i==1){
        !          6009:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
        !          6010:                                        }else{
        !          6011:                                                fprintf(ficgp,",\\\n '' ");
        !          6012:                                        }
        !          6013:                                        if(cptcoveff ==0){ /* No covariate */
        !          6014:                                                ioffset=2; /* Age is in 2 */
        !          6015:                                                /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
        !          6016:                                                /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
        !          6017:                                                /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
        !          6018:                                                /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
        !          6019:                                                fprintf(ficgp," u %d:(", ioffset); 
        !          6020:                                                if(i==nlstate+1)
        !          6021:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                    \
        !          6022:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
        !          6023:                                                else
        !          6024:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                    \
        !          6025:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
        !          6026:                                        }else{ /* more than 2 covariates */
        !          6027:                                                if(cptcoveff ==1){
        !          6028:                                                        ioffset=4; /* Age is in 4 */
        !          6029:                                                }else{
        !          6030:                                                        ioffset=6; /* Age is in 6 */
        !          6031:                                                /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          6032:                                                /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
        !          6033:                                                }   
        !          6034:                                                fprintf(ficgp," u %d:((",ioffset); 
        !          6035:                                                kl=0;
        !          6036:                                                for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
        !          6037:                                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
        !          6038:                                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          6039:                                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          6040:                                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          6041:                                                        vlv= nbcode[Tvaraff[k]][lv];
        !          6042:                                                        kl++;
        !          6043:                                                        /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
        !          6044:                                                        /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
        !          6045:                                                        /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
        !          6046:                                                        /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
        !          6047:                                                        if(k==cptcoveff){
        !          6048:                                                                if(i==nlstate+1){
        !          6049:                                                                        if(cptcoveff ==1){
        !          6050:                                                                        fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
        !          6051:                                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
        !          6052:                                                                        }else{
        !          6053:                                                                        fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
        !          6054:                                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
        !          6055:                                                                        }
        !          6056:                                                                }else{
        !          6057:                                                                        if(cptcoveff ==1){
        !          6058:                                                                                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
        !          6059:                                                                                                                ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
        !          6060:                                                                        }else{
        !          6061:                                                                                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
        !          6062:                                                                                                                ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
        !          6063:                                                                        }
        !          6064:                                                                }
        !          6065:                                                        }else{ /* k < cptcoveff */
        !          6066:                                                                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[k]][lv]);
        !          6067:                                                                kl++;
        !          6068:                                                        }
        !          6069:                                                } /* end covariate */
        !          6070:                                        } /* end if covariate */
        !          6071:                                } /* nlstate */
        !          6072:                                fprintf(ficgp,"\nset out\n");
        !          6073:                        } /* end cpt state*/
        !          6074:                } /* end covariate */
        !          6075:        } /* End if prevfcast */
        !          6076:        
1.211     brouard  6077:        
1.219   ! brouard  6078:        /* proba elementaires */
        !          6079:        fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6080:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6081:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6082:     for(k=1; k <=(nlstate+ndeath); k++){
                   6083:       if (k != i) {
1.187     brouard  6084:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  6085:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  6086:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  6087:          jk++; 
                   6088:        }
1.187     brouard  6089:        fprintf(ficgp,"\n");
1.126     brouard  6090:       }
                   6091:     }
                   6092:    }
1.187     brouard  6093:   fprintf(ficgp,"##############\n#\n");
                   6094: 
1.145     brouard  6095:   /*goto avoid;*/
1.200     brouard  6096:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6097:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6098:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6099:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6100:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6101:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6102:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6103:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6104:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6105:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6106:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6107:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6108:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6109:   fprintf(ficgp,"#\n");
1.201     brouard  6110:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  6111:      fprintf(ficgp,"# ng=%d\n",ng);
                   6112:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  6113:      for(jk=1; jk <=m; jk++) {
1.187     brouard  6114:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  6115:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6116:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6117:        if (ng==1){
                   6118:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6119:         fprintf(ficgp,"\nunset log y");
                   6120:        }else if (ng==2){
                   6121:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6122:         fprintf(ficgp,"\nset log y");
                   6123:        }else if (ng==3){
1.126     brouard  6124:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  6125:         fprintf(ficgp,"\nset log y");
                   6126:        }else
                   6127:         fprintf(ficgp,"\nunset title ");
                   6128:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  6129:        i=1;
                   6130:        for(k2=1; k2<=nlstate; k2++) {
                   6131:         k3=i;
                   6132:         for(k=1; k<=(nlstate+ndeath); k++) {
                   6133:           if (k != k2){
1.201     brouard  6134:             switch( ng) {
                   6135:             case 1:
1.187     brouard  6136:               if(nagesqr==0)
1.201     brouard  6137:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  6138:               else /* nagesqr =1 */
1.201     brouard  6139:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6140:               break;
                   6141:             case 2: /* ng=2 */
1.187     brouard  6142:               if(nagesqr==0)
                   6143:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6144:               else /* nagesqr =1 */
1.201     brouard  6145:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6146:               break;
                   6147:             case 3:
                   6148:               if(nagesqr==0)
                   6149:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6150:               else /* nagesqr =1 */
                   6151:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6152:               break;
                   6153:             }
1.141     brouard  6154:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  6155:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  6156:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6157:               if(ij <=cptcovage) { /* Bug valgrind */
                   6158:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  6159:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6160:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  6161:                   ij++;
                   6162:                 }
1.186     brouard  6163:               }
                   6164:               else
1.198     brouard  6165:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6166:             }
1.217     brouard  6167:           }else{
                   6168:             i=i-ncovmodel;
                   6169:             if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6170:               fprintf(ficgp," (1.");
                   6171:           }
                   6172:           
                   6173:           if(ng != 1){
                   6174:             fprintf(ficgp,")/(1");
1.126     brouard  6175:             
1.217     brouard  6176:             for(k1=1; k1 <=nlstate; k1++){ 
                   6177:               if(nagesqr==0)
                   6178:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6179:               else /* nagesqr =1 */
                   6180:                 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);
                   6181:               
                   6182:               ij=1;
                   6183:               for(j=3; j <=ncovmodel-nagesqr; j++){
                   6184:                 if(ij <=cptcovage) { /* Bug valgrind */
                   6185:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6186:                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6187:                     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6188:                     ij++;
1.197     brouard  6189:                   }
1.186     brouard  6190:                 }
1.217     brouard  6191:                 else
                   6192:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6193:               }
                   6194:               fprintf(ficgp,")");
1.217     brouard  6195:             }
                   6196:             fprintf(ficgp,")");
                   6197:             if(ng ==2)
                   6198:               fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6199:             else /* ng= 3 */
                   6200:               fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6201:           }else{ /* end ng <> 1 */
                   6202:             if( k !=k2) /* logit p11 is hard to draw */
1.201     brouard  6203:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  6204:           }
1.217     brouard  6205:           if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6206:             fprintf(ficgp,",");
                   6207:           if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6208:             fprintf(ficgp,",");
                   6209:           i=i+ncovmodel;
1.126     brouard  6210:         } /* end k */
                   6211:        } /* end k2 */
1.201     brouard  6212:        fprintf(ficgp,"\n set out\n");
1.126     brouard  6213:      } /* end jk */
                   6214:    } /* end ng */
1.164     brouard  6215:  /* avoid: */
1.126     brouard  6216:    fflush(ficgp); 
                   6217: }  /* end gnuplot */
                   6218: 
                   6219: 
                   6220: /*************** Moving average **************/
1.219   ! brouard  6221: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.218     brouard  6222: int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
                   6223:    
1.126     brouard  6224:   int i, cpt, cptcod;
                   6225:   int modcovmax =1;
                   6226:   int mobilavrange, mob;
1.219   ! brouard  6227:   int iage=0;
        !          6228: 
        !          6229:   double sum=0.;
1.126     brouard  6230:   double age;
1.218     brouard  6231:   double *sumnewp, *sumnewm;
                   6232:   double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6233:   
1.219   ! brouard  6234:   
        !          6235:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
        !          6236:                           a covariate has 2 modalities, should be equal to ncovcombmax  */
        !          6237: 
1.218     brouard  6238:   sumnewp = vector(1,modcovmax);
                   6239:   sumnewm = vector(1,modcovmax);
                   6240:   agemingood = vector(1,modcovmax);    
                   6241:   agemaxgood = vector(1,modcovmax);
1.219   ! brouard  6242: 
        !          6243:   for (cptcod=1;cptcod<=modcovmax;cptcod++){
        !          6244:                sumnewm[cptcod]=0.;
        !          6245:                sumnewp[cptcod]=0.;
        !          6246:                agemingood[cptcod]=0;
        !          6247:                agemaxgood[cptcod]=0;
        !          6248:        }
1.126     brouard  6249:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
1.218     brouard  6250:   
1.126     brouard  6251:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6252:     if(mobilav==1) mobilavrange=5; /* default */
                   6253:     else mobilavrange=mobilav;
                   6254:     for (age=bage; age<=fage; age++)
                   6255:       for (i=1; i<=nlstate;i++)
1.219   ! brouard  6256:                                for (cptcod=1;cptcod<=modcovmax;cptcod++)
        !          6257:                                        mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
1.126     brouard  6258:     /* We keep the original values on the extreme ages bage, fage and for 
                   6259:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6260:        we use a 5 terms etc. until the borders are no more concerned. 
                   6261:     */ 
                   6262:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6263:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.219   ! brouard  6264:                                for (i=1; i<=nlstate;i++){
        !          6265:                                        for (cptcod=1;cptcod<=modcovmax;cptcod++){
        !          6266:                                                mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
        !          6267:                                                for (cpt=1;cpt<=(mob-1)/2;cpt++){
        !          6268:                                                        mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
        !          6269:                                                        mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
        !          6270:                                                }
        !          6271:                                                mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
        !          6272:                                        }
        !          6273:                                }
1.126     brouard  6274:       }/* end age */
                   6275:     }/* end mob */
1.218     brouard  6276:   }else
                   6277:     return -1;
                   6278:   for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   6279:     /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
1.219   ! brouard  6280:     agemingood[cptcod]=fage-(mob-1)/2;
1.218     brouard  6281:     for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6282:       sumnewm[cptcod]=0.;
                   6283:       for (i=1; i<=nlstate;i++){
                   6284:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6285:       }
                   6286:       if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.219   ! brouard  6287:                                agemingood[cptcod]=age;
1.218     brouard  6288:       }else{ /* bad */
1.219   ! brouard  6289:                                for (i=1; i<=nlstate;i++){
        !          6290:                                        mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
        !          6291:                                } /* i */
1.218     brouard  6292:       } /* end bad */
                   6293:     }/* age */
1.219   ! brouard  6294:     sum=0.;
        !          6295:     for (i=1; i<=nlstate;i++){
        !          6296:       sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
1.218     brouard  6297:     }
1.219   ! brouard  6298:     if(fabs(sum - 1.) > 1.e-3) { /* bad */
        !          6299:       printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
        !          6300:       /* for (i=1; i<=nlstate;i++){ */
        !          6301:       /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
        !          6302:       /* } /\* i *\/ */
        !          6303:     } /* end bad */
        !          6304:     /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
        !          6305:                /* From youngest, finding the oldest wrong */
        !          6306:                agemaxgood[cptcod]=bage+(mob-1)/2;
        !          6307:                for (age=bage+(mob-1)/2; age<=fage; age++){
        !          6308:                        sumnewm[cptcod]=0.;
        !          6309:                        for (i=1; i<=nlstate;i++){
        !          6310:                                sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
        !          6311:                        }
        !          6312:                        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
        !          6313:                                agemaxgood[cptcod]=age;
        !          6314:                        }else{ /* bad */
        !          6315:                                for (i=1; i<=nlstate;i++){
        !          6316:                                        mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
        !          6317:                                } /* i */
        !          6318:                        } /* end bad */
        !          6319:                }/* age */
        !          6320:                sum=0.;
        !          6321:                for (i=1; i<=nlstate;i++){
        !          6322:                        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
        !          6323:                }
        !          6324:                if(fabs(sum - 1.) > 1.e-3) { /* bad */
        !          6325:                        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
        !          6326:                        /* for (i=1; i<=nlstate;i++){ */
        !          6327:                        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
        !          6328:                        /* } /\* i *\/ */
        !          6329:                } /* end bad */
        !          6330:                
        !          6331:                for (age=bage; age<=fage; age++){
        !          6332:                        printf("%d %d ", cptcod, (int)age);
        !          6333:                        sumnewp[cptcod]=0.;
        !          6334:                        sumnewm[cptcod]=0.;
        !          6335:                        for (i=1; i<=nlstate;i++){
        !          6336:                                sumnewp[cptcod]+=probs[(int)age][i][cptcod];
        !          6337:                                sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
        !          6338:                                /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
        !          6339:                        }
        !          6340:                        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
        !          6341:                }
        !          6342:                /* printf("\n"); */
        !          6343:     /* } */
1.218     brouard  6344:     /* brutal averaging */
                   6345:     for (i=1; i<=nlstate;i++){
                   6346:       for (age=1; age<=bage; age++){
1.219   ! brouard  6347:                                mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
        !          6348:                                /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
1.218     brouard  6349:       }        
                   6350:       for (age=fage; age<=AGESUP; age++){
1.219   ! brouard  6351:                                mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
        !          6352:                                /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
1.218     brouard  6353:       }
                   6354:     } /* end i status */
                   6355:     for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6356:       for (age=1; age<=AGESUP; age++){
1.219   ! brouard  6357:                                /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
        !          6358:                                mobaverage[(int)age][i][cptcod]=0.;
1.218     brouard  6359:       }
                   6360:     }
                   6361:   }/* end cptcod */
                   6362:   free_vector(sumnewm,1, modcovmax);
                   6363:   free_vector(sumnewp,1, modcovmax);
                   6364:   free_vector(agemaxgood,1, modcovmax);
                   6365:   free_vector(agemingood,1, modcovmax);
1.126     brouard  6366:   return 0;
                   6367: }/* End movingaverage */
1.218     brouard  6368:  
1.126     brouard  6369: 
                   6370: /************** Forecasting ******************/
1.169     brouard  6371: 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  6372:   /* proj1, year, month, day of starting projection 
                   6373:      agemin, agemax range of age
                   6374:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6375:      anproj2 year of en of projection (same day and month as proj1).
                   6376:   */
1.164     brouard  6377:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6378:   double agec; /* generic age */
                   6379:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6380:   double *popeffectif,*popcount;
                   6381:   double ***p3mat;
1.218     brouard  6382:   /* double ***mobaverage; */
1.126     brouard  6383:   char fileresf[FILENAMELENGTH];
                   6384: 
                   6385:   agelim=AGESUP;
1.211     brouard  6386:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6387:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6388:      We still use firstpass and lastpass as another selection.
                   6389:   */
1.214     brouard  6390:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6391:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6392:  
1.201     brouard  6393:   strcpy(fileresf,"F_"); 
                   6394:   strcat(fileresf,fileresu);
1.126     brouard  6395:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6396:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6397:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6398:   }
1.215     brouard  6399:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6400:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6401: 
                   6402:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6403: 
                   6404: 
                   6405:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6406:   if (stepm<=12) stepsize=1;
                   6407:   if(estepm < stepm){
                   6408:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6409:   }
                   6410:   else  hstepm=estepm;   
                   6411: 
                   6412:   hstepm=hstepm/stepm; 
                   6413:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6414:                                fractional in yp1 */
                   6415:   anprojmean=yp;
                   6416:   yp2=modf((yp1*12),&yp);
                   6417:   mprojmean=yp;
                   6418:   yp1=modf((yp2*30.5),&yp);
                   6419:   jprojmean=yp;
                   6420:   if(jprojmean==0) jprojmean=1;
                   6421:   if(mprojmean==0) jprojmean=1;
                   6422: 
                   6423:   i1=cptcoveff;
                   6424:   if (cptcovn < 1){i1=1;}
                   6425:   
                   6426:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6427:   
                   6428:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6429: 
                   6430: /*           if (h==(int)(YEARM*yearp)){ */
                   6431:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   6432:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6433:       k=k+1;
1.211     brouard  6434:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  6435:       for(j=1;j<=cptcoveff;j++) {
1.219   ! brouard  6436:                                fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6437:       }
1.211     brouard  6438:       fprintf(ficresf," yearproj age");
1.126     brouard  6439:       for(j=1; j<=nlstate+ndeath;j++){ 
1.219   ! brouard  6440:                                for(i=1; i<=nlstate;i++)              
1.126     brouard  6441:           fprintf(ficresf," p%d%d",i,j);
1.219   ! brouard  6442:                                fprintf(ficresf," wp.%d",j);
1.126     brouard  6443:       }
1.217     brouard  6444:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
1.219   ! brouard  6445:                                fprintf(ficresf,"\n");
        !          6446:                                fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
        !          6447:                                for (agec=fage; agec>=(ageminpar-1); agec--){ 
        !          6448:                                        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
        !          6449:                                        nhstepm = nhstepm/hstepm; 
        !          6450:                                        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          6451:                                        oldm=oldms;savm=savms;
        !          6452:                                        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
        !          6453:                                        
        !          6454:                                        for (h=0; h<=nhstepm; h++){
        !          6455:                                                if (h*hstepm/YEARM*stepm ==yearp) {
1.126     brouard  6456:               fprintf(ficresf,"\n");
                   6457:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6458:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219   ! brouard  6459:                                                        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
        !          6460:                                                } 
        !          6461:                                                for(j=1; j<=nlstate+ndeath;j++) {
        !          6462:                                                        ppij=0.;
        !          6463:                                                        for(i=1; i<=nlstate;i++) {
        !          6464:                                                                if (mobilav==1) 
        !          6465:                                                                        ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
        !          6466:                                                                else {
        !          6467:                                                                        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
        !          6468:                                                                }
        !          6469:                                                                if (h*hstepm/YEARM*stepm== yearp) {
        !          6470:                                                                        fprintf(ficresf," %.3f", p3mat[i][j][h]);
        !          6471:                                                                }
        !          6472:                                                        } /* end i */
        !          6473:                                                        if (h*hstepm/YEARM*stepm==yearp) {
        !          6474:                                                                fprintf(ficresf," %.3f", ppij);
        !          6475:                                                        }
        !          6476:                                                }/* end j */
        !          6477:                                        } /* end h */
        !          6478:                                        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          6479:                                } /* end agec */
1.126     brouard  6480:       } /* end yearp */
                   6481:     } /* end cptcod */
                   6482:   } /* end  cptcov */
1.219   ! brouard  6483:        
1.126     brouard  6484:   fclose(ficresf);
1.215     brouard  6485:   printf("End of Computing forecasting \n");
                   6486:   fprintf(ficlog,"End of Computing forecasting\n");
                   6487: 
1.126     brouard  6488: }
                   6489: 
1.218     brouard  6490: /* /\************** Back Forecasting ******************\/ */
                   6491: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
                   6492: /*   /\* back1, year, month, day of starting backection  */
                   6493: /*      agemin, agemax range of age */
                   6494: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   6495: /*      anback2 year of en of backection (same day and month as back1). */
                   6496: /*   *\/ */
                   6497: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   6498: /*   double agec; /\* generic age *\/ */
                   6499: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   6500: /*   double *popeffectif,*popcount; */
                   6501: /*   double ***p3mat; */
                   6502: /*   /\* double ***mobaverage; *\/ */
                   6503: /*   char fileresfb[FILENAMELENGTH]; */
                   6504:        
                   6505: /*   agelim=AGESUP; */
                   6506: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   6507: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   6508: /*      We still use firstpass and lastpass as another selection. */
                   6509: /*   *\/ */
                   6510: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   6511: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   6512: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   6513:        
                   6514: /*   strcpy(fileresfb,"FB_");  */
                   6515: /*   strcat(fileresfb,fileresu); */
                   6516: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   6517: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   6518: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   6519: /*   } */
                   6520: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6521: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6522:        
                   6523: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   6524:        
                   6525: /*   /\* if (mobilav!=0) { *\/ */
                   6526: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6527: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   6528: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6529: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6530: /*   /\*   } *\/ */
                   6531: /*   /\* } *\/ */
                   6532:        
                   6533: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   6534: /*   if (stepm<=12) stepsize=1; */
                   6535: /*   if(estepm < stepm){ */
                   6536: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   6537: /*   } */
                   6538: /*   else  hstepm=estepm;    */
                   6539:        
                   6540: /*   hstepm=hstepm/stepm;  */
                   6541: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   6542: /*                                fractional in yp1 *\/ */
                   6543: /*   anprojmean=yp; */
                   6544: /*   yp2=modf((yp1*12),&yp); */
                   6545: /*   mprojmean=yp; */
                   6546: /*   yp1=modf((yp2*30.5),&yp); */
                   6547: /*   jprojmean=yp; */
                   6548: /*   if(jprojmean==0) jprojmean=1; */
                   6549: /*   if(mprojmean==0) jprojmean=1; */
                   6550:        
                   6551: /*   i1=cptcoveff; */
                   6552: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  6553:   
1.218     brouard  6554: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  6555:   
1.218     brouard  6556: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   6557:        
                   6558: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   6559: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
                   6560: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   6561: /*       k=k+1; */
                   6562: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
                   6563: /*       for(j=1;j<=cptcoveff;j++) { */
                   6564: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6565: /*       } */
                   6566: /*       fprintf(ficresfb," yearbproj age"); */
                   6567: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   6568: /*                             for(i=1; i<=nlstate;i++)               */
                   6569: /*           fprintf(ficresfb," p%d%d",i,j); */
                   6570: /*                             fprintf(ficresfb," p.%d",j); */
                   6571: /*       } */
                   6572: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   6573: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   6574: /*                             fprintf(ficresfb,"\n"); */
                   6575: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   6576: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   6577: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   6578: /*                                     nhstepm = nhstepm/hstepm;  */
                   6579: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6580: /*                                     oldm=oldms;savm=savms; */
                   6581: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   6582: /*                                     for (h=0; h<=nhstepm; h++){ */
                   6583: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   6584: /*               fprintf(ficresfb,"\n"); */
                   6585: /*               for(j=1;j<=cptcoveff;j++)  */
                   6586: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6587: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   6588: /*                                             }  */
                   6589: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   6590: /*                                                     ppij=0.; */
                   6591: /*                                                     for(i=1; i<=nlstate;i++) { */
                   6592: /*                                                             if (mobilav==1)  */
                   6593: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   6594: /*                                                             else { */
                   6595: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   6596: /*                                                             } */
                   6597: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   6598: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   6599: /*                                                             } */
                   6600: /*                                                     } /\* end i *\/ */
                   6601: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   6602: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   6603: /*                                                     } */
                   6604: /*                                             }/\* end j *\/ */
                   6605: /*                                     } /\* end h *\/ */
                   6606: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6607: /*                             } /\* end agec *\/ */
                   6608: /*       } /\* end yearp *\/ */
                   6609: /*     } /\* end cptcod *\/ */
                   6610: /*   } /\* end  cptcov *\/ */
                   6611:        
                   6612: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6613:        
                   6614: /*   fclose(ficresfb); */
                   6615: /*   printf("End of Computing Back forecasting \n"); */
                   6616: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  6617:        
1.218     brouard  6618: /* } */
1.217     brouard  6619: 
1.126     brouard  6620: /************** Forecasting *****not tested NB*************/
1.169     brouard  6621: 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  6622:   
                   6623:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6624:   int *popage;
                   6625:   double calagedatem, agelim, kk1, kk2;
                   6626:   double *popeffectif,*popcount;
                   6627:   double ***p3mat,***tabpop,***tabpopprev;
1.218     brouard  6628:   /* double ***mobaverage; */
1.126     brouard  6629:   char filerespop[FILENAMELENGTH];
                   6630: 
                   6631:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6632:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6633:   agelim=AGESUP;
                   6634:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6635:   
                   6636:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6637:   
                   6638:   
1.201     brouard  6639:   strcpy(filerespop,"POP_"); 
                   6640:   strcat(filerespop,fileresu);
1.126     brouard  6641:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6642:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6643:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6644:   }
                   6645:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6646:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6647: 
                   6648:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6649: 
1.218     brouard  6650:   /* if (mobilav!=0) { */
                   6651:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6652:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
                   6653:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6654:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6655:   /*   } */
                   6656:   /* } */
1.126     brouard  6657: 
                   6658:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6659:   if (stepm<=12) stepsize=1;
                   6660:   
                   6661:   agelim=AGESUP;
                   6662:   
                   6663:   hstepm=1;
                   6664:   hstepm=hstepm/stepm; 
1.218     brouard  6665:        
1.126     brouard  6666:   if (popforecast==1) {
                   6667:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6668:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6669:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6670:     } 
                   6671:     popage=ivector(0,AGESUP);
                   6672:     popeffectif=vector(0,AGESUP);
                   6673:     popcount=vector(0,AGESUP);
                   6674:     
                   6675:     i=1;   
                   6676:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
1.218     brouard  6677:     
1.126     brouard  6678:     imx=i;
                   6679:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6680:   }
1.218     brouard  6681:   
1.126     brouard  6682:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
1.218     brouard  6683:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
1.126     brouard  6684:       k=k+1;
                   6685:       fprintf(ficrespop,"\n#******");
                   6686:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6687:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6688:       }
                   6689:       fprintf(ficrespop,"******\n");
                   6690:       fprintf(ficrespop,"# Age");
                   6691:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   6692:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   6693:       
                   6694:       for (cpt=0; cpt<=0;cpt++) { 
                   6695:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6696:        
1.218     brouard  6697:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
1.126     brouard  6698:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6699:          nhstepm = nhstepm/hstepm; 
                   6700:          
                   6701:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6702:          oldm=oldms;savm=savms;
                   6703:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
1.218     brouard  6704:          
1.126     brouard  6705:          for (h=0; h<=nhstepm; h++){
                   6706:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6707:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6708:            } 
                   6709:            for(j=1; j<=nlstate+ndeath;j++) {
                   6710:              kk1=0.;kk2=0;
                   6711:              for(i=1; i<=nlstate;i++) {              
                   6712:                if (mobilav==1) 
                   6713:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   6714:                else {
                   6715:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   6716:                }
                   6717:              }
                   6718:              if (h==(int)(calagedatem+12*cpt)){
                   6719:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
1.218     brouard  6720:                /*fprintf(ficrespop," %.3f", kk1);
                   6721:                  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
1.126     brouard  6722:              }
                   6723:            }
                   6724:            for(i=1; i<=nlstate;i++){
                   6725:              kk1=0.;
1.218     brouard  6726:              for(j=1; j<=nlstate;j++){
                   6727:                kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   6728:              }
                   6729:              tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
1.126     brouard  6730:            }
1.218     brouard  6731:            
                   6732:            if (h==(int)(calagedatem+12*cpt))
                   6733:              for(j=1; j<=nlstate;j++) 
                   6734:                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
1.126     brouard  6735:          }
                   6736:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6737:        }
                   6738:       }
1.218     brouard  6739:       
                   6740:       /******/
                   6741:       
1.126     brouard  6742:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   6743:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6744:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6745:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6746:          nhstepm = nhstepm/hstepm; 
                   6747:          
                   6748:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6749:          oldm=oldms;savm=savms;
                   6750:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6751:          for (h=0; h<=nhstepm; h++){
                   6752:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6753:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6754:            } 
                   6755:            for(j=1; j<=nlstate+ndeath;j++) {
                   6756:              kk1=0.;kk2=0;
                   6757:              for(i=1; i<=nlstate;i++) {              
                   6758:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   6759:              }
                   6760:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   6761:            }
                   6762:          }
                   6763:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6764:        }
                   6765:       }
1.218     brouard  6766:     } 
1.126     brouard  6767:   }
1.218     brouard  6768:   
                   6769:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6770:   
1.126     brouard  6771:   if (popforecast==1) {
                   6772:     free_ivector(popage,0,AGESUP);
                   6773:     free_vector(popeffectif,0,AGESUP);
                   6774:     free_vector(popcount,0,AGESUP);
                   6775:   }
                   6776:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6777:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6778:   fclose(ficrespop);
                   6779: } /* End of popforecast */
1.218     brouard  6780:  
1.126     brouard  6781: int fileappend(FILE *fichier, char *optionfich)
                   6782: {
                   6783:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   6784:     printf("Problem with file: %s\n", optionfich);
                   6785:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   6786:     return (0);
                   6787:   }
                   6788:   fflush(fichier);
                   6789:   return (1);
                   6790: }
                   6791: 
                   6792: 
                   6793: /**************** function prwizard **********************/
                   6794: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   6795: {
                   6796: 
                   6797:   /* Wizard to print covariance matrix template */
                   6798: 
1.164     brouard  6799:   char ca[32], cb[32];
                   6800:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  6801:   int numlinepar;
                   6802: 
                   6803:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6804:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6805:   for(i=1; i <=nlstate; i++){
                   6806:     jj=0;
                   6807:     for(j=1; j <=nlstate+ndeath; j++){
                   6808:       if(j==i) continue;
                   6809:       jj++;
                   6810:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6811:       printf("%1d%1d",i,j);
                   6812:       fprintf(ficparo,"%1d%1d",i,j);
                   6813:       for(k=1; k<=ncovmodel;k++){
                   6814:        /*        printf(" %lf",param[i][j][k]); */
                   6815:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6816:        printf(" 0.");
                   6817:        fprintf(ficparo," 0.");
                   6818:       }
                   6819:       printf("\n");
                   6820:       fprintf(ficparo,"\n");
                   6821:     }
                   6822:   }
                   6823:   printf("# Scales (for hessian or gradient estimation)\n");
                   6824:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6825:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6826:   for(i=1; i <=nlstate; i++){
                   6827:     jj=0;
                   6828:     for(j=1; j <=nlstate+ndeath; j++){
                   6829:       if(j==i) continue;
                   6830:       jj++;
                   6831:       fprintf(ficparo,"%1d%1d",i,j);
                   6832:       printf("%1d%1d",i,j);
                   6833:       fflush(stdout);
                   6834:       for(k=1; k<=ncovmodel;k++){
                   6835:        /*      printf(" %le",delti3[i][j][k]); */
                   6836:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6837:        printf(" 0.");
                   6838:        fprintf(ficparo," 0.");
                   6839:       }
                   6840:       numlinepar++;
                   6841:       printf("\n");
                   6842:       fprintf(ficparo,"\n");
                   6843:     }
                   6844:   }
                   6845:   printf("# Covariance matrix\n");
                   6846: /* # 121 Var(a12)\n\ */
                   6847: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6848: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6849: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6850: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6851: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6852: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6853: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6854:   fflush(stdout);
                   6855:   fprintf(ficparo,"# Covariance matrix\n");
                   6856:   /* # 121 Var(a12)\n\ */
                   6857:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6858:   /* #   ...\n\ */
                   6859:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6860:   
                   6861:   for(itimes=1;itimes<=2;itimes++){
                   6862:     jj=0;
                   6863:     for(i=1; i <=nlstate; i++){
                   6864:       for(j=1; j <=nlstate+ndeath; j++){
                   6865:        if(j==i) continue;
                   6866:        for(k=1; k<=ncovmodel;k++){
                   6867:          jj++;
                   6868:          ca[0]= k+'a'-1;ca[1]='\0';
                   6869:          if(itimes==1){
                   6870:            printf("#%1d%1d%d",i,j,k);
                   6871:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6872:          }else{
                   6873:            printf("%1d%1d%d",i,j,k);
                   6874:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6875:            /*  printf(" %.5le",matcov[i][j]); */
                   6876:          }
                   6877:          ll=0;
                   6878:          for(li=1;li <=nlstate; li++){
                   6879:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6880:              if(lj==li) continue;
                   6881:              for(lk=1;lk<=ncovmodel;lk++){
                   6882:                ll++;
                   6883:                if(ll<=jj){
                   6884:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6885:                  if(ll<jj){
                   6886:                    if(itimes==1){
                   6887:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6888:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6889:                    }else{
                   6890:                      printf(" 0.");
                   6891:                      fprintf(ficparo," 0.");
                   6892:                    }
                   6893:                  }else{
                   6894:                    if(itimes==1){
                   6895:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   6896:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   6897:                    }else{
                   6898:                      printf(" 0.");
                   6899:                      fprintf(ficparo," 0.");
                   6900:                    }
                   6901:                  }
                   6902:                }
                   6903:              } /* end lk */
                   6904:            } /* end lj */
                   6905:          } /* end li */
                   6906:          printf("\n");
                   6907:          fprintf(ficparo,"\n");
                   6908:          numlinepar++;
                   6909:        } /* end k*/
                   6910:       } /*end j */
                   6911:     } /* end i */
                   6912:   } /* end itimes */
                   6913: 
                   6914: } /* end of prwizard */
                   6915: /******************* Gompertz Likelihood ******************************/
                   6916: double gompertz(double x[])
                   6917: { 
                   6918:   double A,B,L=0.0,sump=0.,num=0.;
                   6919:   int i,n=0; /* n is the size of the sample */
                   6920: 
                   6921:   for (i=0;i<=imx-1 ; i++) {
                   6922:     sump=sump+weight[i];
                   6923:     /*    sump=sump+1;*/
                   6924:     num=num+1;
                   6925:   }
                   6926:  
                   6927:  
                   6928:   /* for (i=0; i<=imx; i++) 
                   6929:      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]);*/
                   6930: 
                   6931:   for (i=1;i<=imx ; i++)
                   6932:     {
                   6933:       if (cens[i] == 1 && wav[i]>1)
                   6934:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   6935:       
                   6936:       if (cens[i] == 0 && wav[i]>1)
                   6937:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   6938:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   6939:       
                   6940:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6941:       if (wav[i] > 1 ) { /* ??? */
                   6942:        L=L+A*weight[i];
                   6943:        /*      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]);*/
                   6944:       }
                   6945:     }
                   6946: 
                   6947:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6948:  
                   6949:   return -2*L*num/sump;
                   6950: }
                   6951: 
1.136     brouard  6952: #ifdef GSL
                   6953: /******************* Gompertz_f Likelihood ******************************/
                   6954: double gompertz_f(const gsl_vector *v, void *params)
                   6955: { 
                   6956:   double A,B,LL=0.0,sump=0.,num=0.;
                   6957:   double *x= (double *) v->data;
                   6958:   int i,n=0; /* n is the size of the sample */
                   6959: 
                   6960:   for (i=0;i<=imx-1 ; i++) {
                   6961:     sump=sump+weight[i];
                   6962:     /*    sump=sump+1;*/
                   6963:     num=num+1;
                   6964:   }
                   6965:  
                   6966:  
                   6967:   /* for (i=0; i<=imx; i++) 
                   6968:      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]);*/
                   6969:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   6970:   for (i=1;i<=imx ; i++)
                   6971:     {
                   6972:       if (cens[i] == 1 && wav[i]>1)
                   6973:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   6974:       
                   6975:       if (cens[i] == 0 && wav[i]>1)
                   6976:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   6977:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   6978:       
                   6979:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6980:       if (wav[i] > 1 ) { /* ??? */
                   6981:        LL=LL+A*weight[i];
                   6982:        /*      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]);*/
                   6983:       }
                   6984:     }
                   6985: 
                   6986:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6987:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   6988:  
                   6989:   return -2*LL*num/sump;
                   6990: }
                   6991: #endif
                   6992: 
1.126     brouard  6993: /******************* Printing html file ***********/
1.201     brouard  6994: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6995:                  int lastpass, int stepm, int weightopt, char model[],\
                   6996:                  int imx,  double p[],double **matcov,double agemortsup){
                   6997:   int i,k;
                   6998: 
                   6999:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7000:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7001:   for (i=1;i<=2;i++) 
                   7002:     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  7003:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7004:   fprintf(fichtm,"</ul>");
                   7005: 
                   7006: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7007: 
                   7008:  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>");
                   7009: 
                   7010:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7011:    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]);
                   7012: 
                   7013:  
                   7014:   fflush(fichtm);
                   7015: }
                   7016: 
                   7017: /******************* Gnuplot file **************/
1.201     brouard  7018: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7019: 
                   7020:   char dirfileres[132],optfileres[132];
1.164     brouard  7021: 
1.126     brouard  7022:   int ng;
                   7023: 
                   7024: 
                   7025:   /*#ifdef windows */
                   7026:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7027:     /*#endif */
                   7028: 
                   7029: 
                   7030:   strcpy(dirfileres,optionfilefiname);
                   7031:   strcpy(optfileres,"vpl");
1.199     brouard  7032:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7033:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7034:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7035:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7036:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7037: 
                   7038: } 
                   7039: 
1.136     brouard  7040: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7041: {
1.126     brouard  7042: 
1.136     brouard  7043:   /*-------- data file ----------*/
                   7044:   FILE *fic;
                   7045:   char dummy[]="                         ";
1.164     brouard  7046:   int i=0, j=0, n=0;
1.136     brouard  7047:   int linei, month, year,iout;
                   7048:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7049:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7050:   char *stratrunc;
                   7051:   int lstra;
1.126     brouard  7052: 
                   7053: 
1.136     brouard  7054:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7055:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7056:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7057:   }
1.126     brouard  7058: 
1.136     brouard  7059:   i=1;
                   7060:   linei=0;
                   7061:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7062:     linei=linei+1;
                   7063:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7064:       if(line[j] == '\t')
                   7065:        line[j] = ' ';
                   7066:     }
                   7067:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7068:       ;
                   7069:     };
                   7070:     line[j+1]=0;  /* Trims blanks at end of line */
                   7071:     if(line[0]=='#'){
                   7072:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7073:       printf("Comment line\n%s\n",line);
                   7074:       continue;
                   7075:     }
                   7076:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7077:     strcpy(line, linetmp);
1.136     brouard  7078:   
1.126     brouard  7079: 
1.136     brouard  7080:     for (j=maxwav;j>=1;j--){
1.137     brouard  7081:       cutv(stra, strb, line, ' '); 
1.136     brouard  7082:       if(strb[0]=='.') { /* Missing status */
                   7083:        lval=-1;
                   7084:       }else{
                   7085:        errno=0;
                   7086:        lval=strtol(strb,&endptr,10); 
                   7087:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7088:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7089:          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);
                   7090:          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  7091:          return 1;
                   7092:        }
                   7093:       }
                   7094:       s[j][i]=lval;
                   7095:       
                   7096:       strcpy(line,stra);
                   7097:       cutv(stra, strb,line,' ');
1.169     brouard  7098:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7099:       }
1.169     brouard  7100:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7101:        month=99;
                   7102:        year=9999;
                   7103:       }else{
1.141     brouard  7104:        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);
                   7105:        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  7106:        return 1;
                   7107:       }
                   7108:       anint[j][i]= (double) year; 
                   7109:       mint[j][i]= (double)month; 
                   7110:       strcpy(line,stra);
                   7111:     } /* ENd Waves */
                   7112:     
                   7113:     cutv(stra, strb,line,' '); 
1.169     brouard  7114:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7115:     }
1.169     brouard  7116:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7117:       month=99;
                   7118:       year=9999;
                   7119:     }else{
1.141     brouard  7120:       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);
                   7121:        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  7122:        return 1;
                   7123:     }
                   7124:     andc[i]=(double) year; 
                   7125:     moisdc[i]=(double) month; 
                   7126:     strcpy(line,stra);
                   7127:     
                   7128:     cutv(stra, strb,line,' '); 
1.169     brouard  7129:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7130:     }
1.169     brouard  7131:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7132:       month=99;
                   7133:       year=9999;
                   7134:     }else{
1.141     brouard  7135:       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);
                   7136:       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  7137:        return 1;
                   7138:     }
                   7139:     if (year==9999) {
1.141     brouard  7140:       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);
                   7141:       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  7142:        return 1;
1.126     brouard  7143: 
1.136     brouard  7144:     }
                   7145:     annais[i]=(double)(year);
                   7146:     moisnais[i]=(double)(month); 
                   7147:     strcpy(line,stra);
                   7148:     
                   7149:     cutv(stra, strb,line,' '); 
                   7150:     errno=0;
                   7151:     dval=strtod(strb,&endptr); 
                   7152:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7153:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7154:       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  7155:       fflush(ficlog);
                   7156:       return 1;
                   7157:     }
                   7158:     weight[i]=dval; 
                   7159:     strcpy(line,stra);
                   7160:     
                   7161:     for (j=ncovcol;j>=1;j--){
                   7162:       cutv(stra, strb,line,' '); 
                   7163:       if(strb[0]=='.') { /* Missing status */
                   7164:        lval=-1;
                   7165:       }else{
                   7166:        errno=0;
                   7167:        lval=strtol(strb,&endptr,10); 
                   7168:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7169:          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);
                   7170:          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  7171:          return 1;
                   7172:        }
                   7173:       }
                   7174:       if(lval <-1 || lval >1){
1.141     brouard  7175:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7176:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7177:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7178:  For example, for multinomial values like 1, 2 and 3,\n \
                   7179:  build V1=0 V2=0 for the reference value (1),\n \
                   7180:         V1=1 V2=0 for (2) \n \
                   7181:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7182:  output of IMaCh is often meaningless.\n \
                   7183:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  7184:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7185:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7186:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7187:  For example, for multinomial values like 1, 2 and 3,\n \
                   7188:  build V1=0 V2=0 for the reference value (1),\n \
                   7189:         V1=1 V2=0 for (2) \n \
                   7190:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7191:  output of IMaCh is often meaningless.\n \
                   7192:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   7193:        return 1;
                   7194:       }
                   7195:       covar[j][i]=(double)(lval);
                   7196:       strcpy(line,stra);
                   7197:     }  
                   7198:     lstra=strlen(stra);
                   7199:      
                   7200:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7201:       stratrunc = &(stra[lstra-9]);
                   7202:       num[i]=atol(stratrunc);
                   7203:     }
                   7204:     else
                   7205:       num[i]=atol(stra);
                   7206:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7207:       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;}*/
                   7208:     
                   7209:     i=i+1;
                   7210:   } /* End loop reading  data */
1.126     brouard  7211: 
1.136     brouard  7212:   *imax=i-1; /* Number of individuals */
                   7213:   fclose(fic);
                   7214:  
                   7215:   return (0);
1.164     brouard  7216:   /* endread: */
1.136     brouard  7217:     printf("Exiting readdata: ");
                   7218:     fclose(fic);
                   7219:     return (1);
1.126     brouard  7220: 
                   7221: 
                   7222: 
1.136     brouard  7223: }
1.145     brouard  7224: void removespace(char *str) {
                   7225:   char *p1 = str, *p2 = str;
                   7226:   do
                   7227:     while (*p2 == ' ')
                   7228:       p2++;
1.169     brouard  7229:   while (*p1++ == *p2++);
1.145     brouard  7230: }
                   7231: 
                   7232: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  7233:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   7234:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   7235:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   7236:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  7237:    * - cptcovage number of covariates with age*products =2
                   7238:    * - cptcovs number of simple covariates
                   7239:    * - 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
                   7240:    *     which is a new column after the 9 (ncovcol) variables. 
                   7241:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   7242:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   7243:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   7244:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   7245:  */
1.136     brouard  7246: {
1.145     brouard  7247:   int i, j, k, ks;
1.164     brouard  7248:   int  j1, k1, k2;
1.136     brouard  7249:   char modelsav[80];
1.145     brouard  7250:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  7251:   char *strpt;
1.136     brouard  7252: 
1.145     brouard  7253:   /*removespace(model);*/
1.136     brouard  7254:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  7255:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  7256:     if (strstr(model,"AGE") !=0){
1.192     brouard  7257:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7258:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  7259:       return 1;
                   7260:     }
1.141     brouard  7261:     if (strstr(model,"v") !=0){
                   7262:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7263:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7264:       return 1;
                   7265:     }
1.187     brouard  7266:     strcpy(modelsav,model); 
                   7267:     if ((strpt=strstr(model,"age*age")) !=0){
                   7268:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7269:       if(strpt != model){
                   7270:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7271:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7272:  corresponding column of parameters.\n",model);
                   7273:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7274:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7275:  corresponding column of parameters.\n",model); fflush(ficlog);
                   7276:       return 1;
                   7277:     }
                   7278: 
                   7279:       nagesqr=1;
                   7280:       if (strstr(model,"+age*age") !=0)
                   7281:        substrchaine(modelsav, model, "+age*age");
                   7282:       else if (strstr(model,"age*age+") !=0)
                   7283:        substrchaine(modelsav, model, "age*age+");
                   7284:       else 
                   7285:        substrchaine(modelsav, model, "age*age");
                   7286:     }else
                   7287:       nagesqr=0;
                   7288:     if (strlen(modelsav) >1){
                   7289:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7290:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   7291:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   7292:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   7293:                   * cst, age and age*age 
                   7294:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   7295:                   /* including age products which are counted in cptcovage.
                   7296:                  * but the covariates which are products must be treated 
                   7297:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   7298:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7299:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7300: 
                   7301:     
                   7302:       /*   Design
                   7303:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7304:        *  <          ncovcol=8                >
                   7305:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7306:        *   k=  1    2      3       4     5       6      7        8
                   7307:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7308:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   7309:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   7310:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   7311:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7312:        *  Tage[++cptcovage]=k
                   7313:        *       if products, new covar are created after ncovcol with k1
                   7314:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7315:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7316:        *  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
                   7317:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7318:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7319:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7320:        *  <          ncovcol=8                >
                   7321:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7322:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7323:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7324:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7325:        * p Tprod[1]@2={                         6, 5}
                   7326:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7327:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7328:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7329:        *How to reorganize?
                   7330:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7331:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7332:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7333:        * Struct []
                   7334:        */
1.145     brouard  7335: 
1.187     brouard  7336:       /* This loop fills the array Tvar from the string 'model'.*/
                   7337:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7338:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7339:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7340:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7341:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7342:       /*       k=1 Tvar[1]=2 (from V2) */
                   7343:       /*       k=5 Tvar[5] */
                   7344:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  7345:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  7346:       /*       } */
1.198     brouard  7347:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  7348:       /*
                   7349:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7350:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  7351:         Tvar[k]=0;
1.187     brouard  7352:       cptcovage=0;
                   7353:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   7354:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   7355:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   7356:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   7357:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   7358:        /*scanf("%d",i);*/
                   7359:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   7360:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   7361:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   7362:            /* covar is not filled and then is empty */
                   7363:            cptcovprod--;
                   7364:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   7365:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   7366:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   7367:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7368:            /*printf("stre=%s ", stre);*/
                   7369:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   7370:            cptcovprod--;
                   7371:            cutl(stre,strb,strc,'V');
                   7372:            Tvar[k]=atoi(stre);
                   7373:            cptcovage++;
                   7374:            Tage[cptcovage]=k;
                   7375:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   7376:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   7377:            cptcovn++;
                   7378:            cptcovprodnoage++;k1++;
                   7379:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   7380:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   7381:                                   because this model-covariate is a construction we invent a new column
                   7382:                                   ncovcol + k1
                   7383:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   7384:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   7385:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   7386:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   7387:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   7388:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   7389:            k2=k2+2;
                   7390:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   7391:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   7392:            for (i=1; i<=lastobs;i++){
                   7393:              /* Computes the new covariate which is a product of
                   7394:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   7395:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   7396:            }
                   7397:          } /* End age is not in the model */
                   7398:        } /* End if model includes a product */
                   7399:        else { /* no more sum */
                   7400:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   7401:          /*  scanf("%d",i);*/
                   7402:          cutl(strd,strc,strb,'V');
                   7403:          ks++; /**< Number of simple covariates */
1.145     brouard  7404:          cptcovn++;
1.187     brouard  7405:          Tvar[k]=atoi(strd);
                   7406:        }
                   7407:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   7408:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   7409:          scanf("%d",i);*/
                   7410:       } /* end of loop + on total covariates */
                   7411:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7412:   } /* end if strlen(model == 0) */
1.136     brouard  7413:   
                   7414:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7415:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7416: 
                   7417:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   7418:   printf("cptcovprod=%d ", cptcovprod);
                   7419:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   7420: 
                   7421:   scanf("%d ",i);*/
                   7422: 
                   7423: 
1.137     brouard  7424:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  7425:   /*endread:*/
1.136     brouard  7426:     printf("Exiting decodemodel: ");
                   7427:     return (1);
                   7428: }
                   7429: 
1.169     brouard  7430: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  7431: {
                   7432:   int i, m;
1.218     brouard  7433:   int firstone=0;
                   7434:   
1.136     brouard  7435:   for (i=1; i<=imx; i++) {
                   7436:     for(m=2; (m<= maxwav); m++) {
                   7437:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7438:        anint[m][i]=9999;
1.216     brouard  7439:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7440:          s[m][i]=-1;
1.136     brouard  7441:       }
                   7442:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  7443:        *nberr = *nberr + 1;
1.218     brouard  7444:        if(firstone == 0){
                   7445:          firstone=1;
                   7446:        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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   7447:        }
                   7448:        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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
1.136     brouard  7449:        s[m][i]=-1;
                   7450:       }
                   7451:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  7452:        (*nberr)++;
1.136     brouard  7453:        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]); 
                   7454:        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]); 
                   7455:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7456:       }
                   7457:     }
                   7458:   }
                   7459: 
                   7460:   for (i=1; i<=imx; i++)  {
                   7461:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7462:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  7463:       if(s[m][i] >0  || s[m][i]==-1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ /* What if s[m][i]=-1 */
1.136     brouard  7464:        if (s[m][i] >= nlstate+1) {
1.169     brouard  7465:          if(agedc[i]>0){
                   7466:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  7467:              agev[m][i]=agedc[i];
1.214     brouard  7468:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  7469:            }else {
1.136     brouard  7470:              if ((int)andc[i]!=9999){
                   7471:                nbwarn++;
                   7472:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7473:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7474:                agev[m][i]=-1;
                   7475:              }
                   7476:            }
1.169     brouard  7477:          } /* agedc > 0 */
1.214     brouard  7478:        } /* end if */
1.136     brouard  7479:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7480:                                 years but with the precision of a month */
                   7481:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7482:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7483:            agev[m][i]=1;
                   7484:          else if(agev[m][i] < *agemin){ 
                   7485:            *agemin=agev[m][i];
                   7486:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7487:          }
                   7488:          else if(agev[m][i] >*agemax){
                   7489:            *agemax=agev[m][i];
1.156     brouard  7490:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  7491:          }
                   7492:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7493:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  7494:        } /* en if 9*/
1.136     brouard  7495:        else { /* =9 */
1.214     brouard  7496:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  7497:          agev[m][i]=1;
                   7498:          s[m][i]=-1;
                   7499:        }
                   7500:       }
1.214     brouard  7501:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  7502:        agev[m][i]=1;
1.214     brouard  7503:       else{
                   7504:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7505:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7506:        agev[m][i]=0;
                   7507:       }
                   7508:     } /* End for lastpass */
                   7509:   }
1.136     brouard  7510:     
                   7511:   for (i=1; i<=imx; i++)  {
                   7512:     for(m=firstpass; (m<=lastpass); m++){
                   7513:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  7514:        (*nberr)++;
1.136     brouard  7515:        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);     
                   7516:        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);     
                   7517:        return 1;
                   7518:       }
                   7519:     }
                   7520:   }
                   7521: 
                   7522:   /*for (i=1; i<=imx; i++){
                   7523:   for (m=firstpass; (m<lastpass); m++){
                   7524:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7525: }
                   7526: 
                   7527: }*/
                   7528: 
                   7529: 
1.139     brouard  7530:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7531:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  7532: 
                   7533:   return (0);
1.164     brouard  7534:  /* endread:*/
1.136     brouard  7535:     printf("Exiting calandcheckages: ");
                   7536:     return (1);
                   7537: }
                   7538: 
1.172     brouard  7539: #if defined(_MSC_VER)
                   7540: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7541: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7542: //#include "stdafx.h"
                   7543: //#include <stdio.h>
                   7544: //#include <tchar.h>
                   7545: //#include <windows.h>
                   7546: //#include <iostream>
                   7547: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7548: 
                   7549: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7550: 
                   7551: BOOL IsWow64()
                   7552: {
                   7553:        BOOL bIsWow64 = FALSE;
                   7554: 
                   7555:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7556:        //  (HANDLE, PBOOL);
                   7557: 
                   7558:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7559: 
                   7560:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7561:        const char funcName[] = "IsWow64Process";
                   7562:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7563:                GetProcAddress(module, funcName);
                   7564: 
                   7565:        if (NULL != fnIsWow64Process)
                   7566:        {
                   7567:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7568:                        &bIsWow64))
                   7569:                        //throw std::exception("Unknown error");
                   7570:                        printf("Unknown error\n");
                   7571:        }
                   7572:        return bIsWow64 != FALSE;
                   7573: }
                   7574: #endif
1.177     brouard  7575: 
1.191     brouard  7576: void syscompilerinfo(int logged)
1.167     brouard  7577:  {
                   7578:    /* #include "syscompilerinfo.h"*/
1.185     brouard  7579:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7580:    /* /GS /W3 /Gy
                   7581:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7582:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7583:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  7584:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   7585:    */ 
                   7586:    /* 64 bits */
1.185     brouard  7587:    /*
                   7588:      /GS /W3 /Gy
                   7589:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   7590:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   7591:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   7592:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   7593:    /* Optimization are useless and O3 is slower than O2 */
                   7594:    /*
                   7595:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   7596:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   7597:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   7598:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   7599:    */
1.186     brouard  7600:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  7601:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   7602:       /PDB:"visual studio
                   7603:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   7604:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   7605:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   7606:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   7607:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   7608:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   7609:       uiAccess='false'"
                   7610:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   7611:       /NOLOGO /TLBID:1
                   7612:    */
1.177     brouard  7613: #if defined __INTEL_COMPILER
1.178     brouard  7614: #if defined(__GNUC__)
                   7615:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   7616: #endif
1.177     brouard  7617: #elif defined(__GNUC__) 
1.179     brouard  7618: #ifndef  __APPLE__
1.174     brouard  7619: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  7620: #endif
1.177     brouard  7621:    struct utsname sysInfo;
1.178     brouard  7622:    int cross = CROSS;
                   7623:    if (cross){
                   7624:           printf("Cross-");
1.191     brouard  7625:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  7626:    }
1.174     brouard  7627: #endif
                   7628: 
1.171     brouard  7629: #include <stdint.h>
1.178     brouard  7630: 
1.191     brouard  7631:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  7632: #if defined(__clang__)
1.191     brouard  7633:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  7634: #endif
                   7635: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  7636:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  7637: #endif
                   7638: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  7639:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  7640: #endif
                   7641: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  7642:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  7643: #endif
                   7644: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  7645:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  7646: #endif
                   7647: #if defined(_MSC_VER)
1.191     brouard  7648:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  7649: #endif
                   7650: #if defined(__PGI)
1.191     brouard  7651:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  7652: #endif
                   7653: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  7654:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  7655: #endif
1.191     brouard  7656:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  7657:    
1.167     brouard  7658: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   7659: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   7660:     // Windows (x64 and x86)
1.191     brouard  7661:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  7662: #elif __unix__ // all unices, not all compilers
                   7663:     // Unix
1.191     brouard  7664:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  7665: #elif __linux__
                   7666:     // linux
1.191     brouard  7667:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  7668: #elif __APPLE__
1.174     brouard  7669:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  7670:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  7671: #endif
                   7672: 
                   7673: /*  __MINGW32__          */
                   7674: /*  __CYGWIN__  */
                   7675: /* __MINGW64__  */
                   7676: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   7677: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   7678: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   7679: /* _WIN64  // Defined for applications for Win64. */
                   7680: /* _M_X64 // Defined for compilations that target x64 processors. */
                   7681: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  7682: 
1.167     brouard  7683: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  7684:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  7685: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  7686:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  7687: #else
1.191     brouard  7688:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  7689: #endif
                   7690: 
1.169     brouard  7691: #if defined(__GNUC__)
                   7692: # if defined(__GNUC_PATCHLEVEL__)
                   7693: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7694:                             + __GNUC_MINOR__ * 100 \
                   7695:                             + __GNUC_PATCHLEVEL__)
                   7696: # else
                   7697: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7698:                             + __GNUC_MINOR__ * 100)
                   7699: # endif
1.174     brouard  7700:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  7701:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  7702: 
                   7703:    if (uname(&sysInfo) != -1) {
                   7704:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  7705:         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  7706:    }
                   7707:    else
                   7708:       perror("uname() error");
1.179     brouard  7709:    //#ifndef __INTEL_COMPILER 
                   7710: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  7711:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  7712:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  7713: #endif
1.169     brouard  7714: #endif
1.172     brouard  7715: 
                   7716:    //   void main()
                   7717:    //   {
1.169     brouard  7718: #if defined(_MSC_VER)
1.174     brouard  7719:    if (IsWow64()){
1.191     brouard  7720:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7721:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  7722:    }
                   7723:    else{
1.191     brouard  7724:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7725:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  7726:    }
1.172     brouard  7727:    //     printf("\nPress Enter to continue...");
                   7728:    //     getchar();
                   7729:    //   }
                   7730: 
1.169     brouard  7731: #endif
                   7732:    
1.167     brouard  7733: 
1.219   ! brouard  7734: }
1.136     brouard  7735: 
1.219   ! brouard  7736: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  7737:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   7738:   int i, j, k, i1 ;
1.202     brouard  7739:   /* double ftolpl = 1.e-10; */
1.180     brouard  7740:   double age, agebase, agelim;
1.203     brouard  7741:   double tot;
1.180     brouard  7742: 
1.202     brouard  7743:   strcpy(filerespl,"PL_");
                   7744:   strcat(filerespl,fileresu);
                   7745:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   7746:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7747:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7748:   }
                   7749:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7750:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7751:   pstamp(ficrespl);
1.203     brouard  7752:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  7753:   fprintf(ficrespl,"#Age ");
                   7754:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   7755:   fprintf(ficrespl,"\n");
1.180     brouard  7756:   
1.219   ! brouard  7757:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  7758: 
1.219   ! brouard  7759:   agebase=ageminpar;
        !          7760:   agelim=agemaxpar;
1.180     brouard  7761: 
1.219   ! brouard  7762:   i1=pow(2,cptcoveff);
        !          7763:   if (cptcovn < 1){i1=1;}
1.180     brouard  7764: 
1.219   ! brouard  7765:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
1.180     brouard  7766:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219   ! brouard  7767:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
        !          7768:     k=k+1;
        !          7769:     /* to clean */
        !          7770:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
        !          7771:     fprintf(ficrespl,"#******");
        !          7772:     printf("#******");
        !          7773:     fprintf(ficlog,"#******");
        !          7774:     for(j=1;j<=cptcoveff;j++) {
        !          7775:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7776:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7777:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7778:     }
        !          7779:     fprintf(ficrespl,"******\n");
        !          7780:     printf("******\n");
        !          7781:     fprintf(ficlog,"******\n");
        !          7782: 
        !          7783:     fprintf(ficrespl,"#Age ");
        !          7784:     for(j=1;j<=cptcoveff;j++) {
        !          7785:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7786:     }
        !          7787:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
        !          7788:     fprintf(ficrespl,"Total Years_to_converge\n");
        !          7789:        
        !          7790:     for (age=agebase; age<=agelim; age++){
        !          7791:       /* for (age=agebase; age<=agebase; age++){ */
        !          7792:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
        !          7793:       fprintf(ficrespl,"%.0f ",age );
        !          7794:       for(j=1;j<=cptcoveff;j++)
        !          7795:        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7796:       tot=0.;
        !          7797:       for(i=1; i<=nlstate;i++){
        !          7798:        tot +=  prlim[i][i];
        !          7799:        fprintf(ficrespl," %.5f", prlim[i][i]);
        !          7800:       }
        !          7801:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
        !          7802:     } /* Age */
        !          7803:     /* was end of cptcod */
        !          7804:   } /* cptcov */
        !          7805:   return 0;
1.180     brouard  7806: }
                   7807: 
1.218     brouard  7808: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
                   7809:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   7810:        
                   7811:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   7812:    * at any age between ageminpar and agemaxpar
                   7813:         */
1.217     brouard  7814:   int i, j, k, i1 ;
                   7815:   /* double ftolpl = 1.e-10; */
                   7816:   double age, agebase, agelim;
                   7817:   double tot;
1.218     brouard  7818:   /* double ***mobaverage; */
                   7819:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  7820: 
                   7821:   strcpy(fileresplb,"PLB_");
                   7822:   strcat(fileresplb,fileresu);
                   7823:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   7824:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   7825:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   7826:   }
                   7827:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   7828:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   7829:   pstamp(ficresplb);
                   7830:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   7831:   fprintf(ficresplb,"#Age ");
                   7832:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   7833:   fprintf(ficresplb,"\n");
                   7834:   
1.218     brouard  7835:   
                   7836:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   7837:   
                   7838:   agebase=ageminpar;
                   7839:   agelim=agemaxpar;
                   7840:   
                   7841:   
                   7842:   i1=pow(2,cptcoveff);
                   7843:   if (cptcovn < 1){i1=1;}
                   7844:   
                   7845:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
1.217     brouard  7846:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.218     brouard  7847:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   7848:     k=k+1;
                   7849:     /* to clean */
                   7850:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   7851:     fprintf(ficresplb,"#******");
                   7852:     printf("#******");
                   7853:     fprintf(ficlog,"#******");
                   7854:     for(j=1;j<=cptcoveff;j++) {
                   7855:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7856:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7857:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7858:     }
                   7859:     fprintf(ficresplb,"******\n");
                   7860:     printf("******\n");
                   7861:     fprintf(ficlog,"******\n");
                   7862:     
                   7863:     fprintf(ficresplb,"#Age ");
                   7864:     for(j=1;j<=cptcoveff;j++) {
                   7865:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7866:     }
                   7867:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   7868:     fprintf(ficresplb,"Total Years_to_converge\n");
                   7869:     
                   7870:     
                   7871:     for (age=agebase; age<=agelim; age++){
                   7872:       /* for (age=agebase; age<=agebase; age++){ */
                   7873:       if(mobilavproj > 0){
                   7874:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   7875:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.219   ! brouard  7876:                                bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  7877:       }else if (mobilavproj == 0){
1.219   ! brouard  7878:                                printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
        !          7879:                                fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
        !          7880:                                exit(1);
1.218     brouard  7881:       }else{
1.219   ! brouard  7882:                                /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
        !          7883:                                bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  7884:       }
                   7885:       fprintf(ficresplb,"%.0f ",age );
                   7886:       for(j=1;j<=cptcoveff;j++)
1.219   ! brouard  7887:                                fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  7888:       tot=0.;
                   7889:       for(i=1; i<=nlstate;i++){
1.219   ! brouard  7890:                                tot +=  bprlim[i][i];
        !          7891:                                fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  7892:       }
                   7893:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   7894:     } /* Age */
                   7895:     /* was end of cptcod */
                   7896:   } /* cptcov */
                   7897:   
                   7898:   /* hBijx(p, bage, fage); */
                   7899:   /* fclose(ficrespijb); */
                   7900:   
                   7901:   return 0;
1.217     brouard  7902: }
1.218     brouard  7903:  
1.180     brouard  7904: int hPijx(double *p, int bage, int fage){
                   7905:     /*------------- h Pij x at various ages ------------*/
                   7906: 
                   7907:   int stepsize;
                   7908:   int agelim;
                   7909:   int hstepm;
                   7910:   int nhstepm;
                   7911:   int h, i, i1, j, k;
                   7912: 
                   7913:   double agedeb;
                   7914:   double ***p3mat;
                   7915: 
1.201     brouard  7916:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  7917:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   7918:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7919:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7920:     }
                   7921:     printf("Computing pij: result on file '%s' \n", filerespij);
                   7922:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   7923:   
                   7924:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7925:     /*if (stepm<=24) stepsize=2;*/
                   7926: 
                   7927:     agelim=AGESUP;
                   7928:     hstepm=stepsize*YEARM; /* Every year of age */
                   7929:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  7930:                
1.180     brouard  7931:     /* hstepm=1;   aff par mois*/
                   7932:     pstamp(ficrespij);
                   7933:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   7934:     i1= pow(2,cptcoveff);
1.218     brouard  7935:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   7936:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   7937:                /*      k=k+1;  */
1.183     brouard  7938:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7939:       fprintf(ficrespij,"\n#****** ");
                   7940:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  7941:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  7942:       fprintf(ficrespij,"******\n");
                   7943:       
                   7944:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   7945:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7946:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7947:        
                   7948:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  7949:        
1.183     brouard  7950:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7951:        oldm=oldms;savm=savms;
                   7952:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   7953:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   7954:        for(i=1; i<=nlstate;i++)
                   7955:          for(j=1; j<=nlstate+ndeath;j++)
                   7956:            fprintf(ficrespij," %1d-%1d",i,j);
                   7957:        fprintf(ficrespij,"\n");
                   7958:        for (h=0; h<=nhstepm; h++){
                   7959:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   7960:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  7961:          for(i=1; i<=nlstate;i++)
                   7962:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  7963:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  7964:          fprintf(ficrespij,"\n");
                   7965:        }
1.183     brouard  7966:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7967:        fprintf(ficrespij,"\n");
                   7968:       }
1.180     brouard  7969:       /*}*/
                   7970:     }
1.218     brouard  7971:     return 0;
1.180     brouard  7972: }
1.218     brouard  7973:  
                   7974:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  7975:     /*------------- h Bij x at various ages ------------*/
                   7976: 
                   7977:   int stepsize;
1.218     brouard  7978:   /* int agelim; */
                   7979:        int ageminl;
1.217     brouard  7980:   int hstepm;
                   7981:   int nhstepm;
                   7982:   int h, i, i1, j, k;
1.218     brouard  7983:        
1.217     brouard  7984:   double agedeb;
                   7985:   double ***p3mat;
1.218     brouard  7986:        
                   7987:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   7988:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   7989:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   7990:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   7991:   }
                   7992:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   7993:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   7994:   
                   7995:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7996:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  7997:   
1.218     brouard  7998:   /* agelim=AGESUP; */
                   7999:   ageminl=30;
                   8000:   hstepm=stepsize*YEARM; /* Every year of age */
                   8001:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8002:   
                   8003:   /* hstepm=1;   aff par mois*/
                   8004:   pstamp(ficrespijb);
                   8005:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
                   8006:   i1= pow(2,cptcoveff);
                   8007:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8008:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8009:   /*   k=k+1;  */
                   8010:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8011:     fprintf(ficrespijb,"\n#****** ");
                   8012:     for(j=1;j<=cptcoveff;j++)
                   8013:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8014:     fprintf(ficrespijb,"******\n");
                   8015:     
                   8016:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8017:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8018:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8019:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8020:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8021:       
                   8022:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8023:       
                   8024:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8025:       /* oldm=oldms;savm=savms; */
                   8026:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8027:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8028:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8029:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8030:       for(i=1; i<=nlstate;i++)
                   8031:        for(j=1; j<=nlstate+ndeath;j++)
                   8032:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8033:       fprintf(ficrespijb,"\n");
                   8034:       for (h=0; h<=nhstepm; h++){
                   8035:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8036:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8037:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  8038:        for(i=1; i<=nlstate;i++)
                   8039:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  8040:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  8041:        fprintf(ficrespijb,"\n");
                   8042:       }
1.218     brouard  8043:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8044:       fprintf(ficrespijb,"\n");
1.217     brouard  8045:     }
1.218     brouard  8046:     /*}*/
                   8047:   }
                   8048:   return 0;
                   8049:  } /*  hBijx */
1.217     brouard  8050: 
1.180     brouard  8051: 
1.136     brouard  8052: /***********************************************/
                   8053: /**************** Main Program *****************/
                   8054: /***********************************************/
                   8055: 
                   8056: int main(int argc, char *argv[])
                   8057: {
                   8058: #ifdef GSL
                   8059:   const gsl_multimin_fminimizer_type *T;
                   8060:   size_t iteri = 0, it;
                   8061:   int rval = GSL_CONTINUE;
                   8062:   int status = GSL_SUCCESS;
                   8063:   double ssval;
                   8064: #endif
                   8065:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  8066:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  8067:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  8068:   int jj, ll, li, lj, lk;
1.136     brouard  8069:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  8070:   int num_filled;
1.136     brouard  8071:   int itimes;
                   8072:   int NDIM=2;
                   8073:   int vpopbased=0;
                   8074: 
1.164     brouard  8075:   char ca[32], cb[32];
1.136     brouard  8076:   /*  FILE *fichtm; *//* Html File */
                   8077:   /* FILE *ficgp;*/ /*Gnuplot File */
                   8078:   struct stat info;
1.191     brouard  8079:   double agedeb=0.;
1.194     brouard  8080: 
                   8081:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219   ! brouard  8082:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  8083: 
1.165     brouard  8084:   double fret;
1.191     brouard  8085:   double dum=0.; /* Dummy variable */
1.136     brouard  8086:   double ***p3mat;
1.218     brouard  8087:   /* double ***mobaverage; */
1.164     brouard  8088: 
                   8089:   char line[MAXLINE];
1.197     brouard  8090:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   8091: 
                   8092:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  8093:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  8094:   char *tok, *val; /* pathtot */
1.136     brouard  8095:   int firstobs=1, lastobs=10;
1.195     brouard  8096:   int c,  h , cpt, c2;
1.191     brouard  8097:   int jl=0;
                   8098:   int i1, j1, jk, stepsize=0;
1.194     brouard  8099:   int count=0;
                   8100: 
1.164     brouard  8101:   int *tab; 
1.136     brouard  8102:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  8103:   int backcast=0;
1.136     brouard  8104:   int mobilav=0,popforecast=0;
1.191     brouard  8105:   int hstepm=0, nhstepm=0;
1.136     brouard  8106:   int agemortsup;
                   8107:   float  sumlpop=0.;
                   8108:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   8109:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   8110: 
1.191     brouard  8111:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  8112:   double ftolpl=FTOL;
                   8113:   double **prlim;
1.217     brouard  8114:   double **bprlim;
1.136     brouard  8115:   double ***param; /* Matrix of parameters */
                   8116:   double  *p;
                   8117:   double **matcov; /* Matrix of covariance */
1.203     brouard  8118:   double **hess; /* Hessian matrix */
1.136     brouard  8119:   double ***delti3; /* Scale */
                   8120:   double *delti; /* Scale */
                   8121:   double ***eij, ***vareij;
                   8122:   double **varpl; /* Variances of prevalence limits by age */
                   8123:   double *epj, vepp;
1.164     brouard  8124: 
1.136     brouard  8125:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  8126:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   8127: 
1.136     brouard  8128:   double **ximort;
1.145     brouard  8129:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  8130:   int *dcwave;
                   8131: 
1.164     brouard  8132:   char z[1]="c";
1.136     brouard  8133: 
                   8134:   /*char  *strt;*/
                   8135:   char strtend[80];
1.126     brouard  8136: 
1.164     brouard  8137: 
1.126     brouard  8138: /*   setlocale (LC_ALL, ""); */
                   8139: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   8140: /*   textdomain (PACKAGE); */
                   8141: /*   setlocale (LC_CTYPE, ""); */
                   8142: /*   setlocale (LC_MESSAGES, ""); */
                   8143: 
                   8144:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  8145:   rstart_time = time(NULL);  
                   8146:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   8147:   start_time = *localtime(&rstart_time);
1.126     brouard  8148:   curr_time=start_time;
1.157     brouard  8149:   /*tml = *localtime(&start_time.tm_sec);*/
                   8150:   /* strcpy(strstart,asctime(&tml)); */
                   8151:   strcpy(strstart,asctime(&start_time));
1.126     brouard  8152: 
                   8153: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  8154: /*  tp.tm_sec = tp.tm_sec +86400; */
                   8155: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  8156: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   8157: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   8158: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  8159: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  8160: /*   strt=asctime(&tmg); */
                   8161: /*   printf("Time(after) =%s",strstart);  */
                   8162: /*  (void) time (&time_value);
                   8163: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   8164: *  tm = *localtime(&time_value);
                   8165: *  strstart=asctime(&tm);
                   8166: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   8167: */
                   8168: 
                   8169:   nberr=0; /* Number of errors and warnings */
                   8170:   nbwarn=0;
1.184     brouard  8171: #ifdef WIN32
                   8172:   _getcwd(pathcd, size);
                   8173: #else
1.126     brouard  8174:   getcwd(pathcd, size);
1.184     brouard  8175: #endif
1.191     brouard  8176:   syscompilerinfo(0);
1.196     brouard  8177:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  8178:   if(argc <=1){
                   8179:     printf("\nEnter the parameter file name: ");
1.205     brouard  8180:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   8181:       printf("ERROR Empty parameter file name\n");
                   8182:       goto end;
                   8183:     }
1.126     brouard  8184:     i=strlen(pathr);
                   8185:     if(pathr[i-1]=='\n')
                   8186:       pathr[i-1]='\0';
1.156     brouard  8187:     i=strlen(pathr);
1.205     brouard  8188:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  8189:       pathr[i-1]='\0';
1.205     brouard  8190:     }
                   8191:     i=strlen(pathr);
                   8192:     if( i==0 ){
                   8193:       printf("ERROR Empty parameter file name\n");
                   8194:       goto end;
                   8195:     }
                   8196:     for (tok = pathr; tok != NULL; ){
1.126     brouard  8197:       printf("Pathr |%s|\n",pathr);
                   8198:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   8199:       printf("val= |%s| pathr=%s\n",val,pathr);
                   8200:       strcpy (pathtot, val);
                   8201:       if(pathr[0] == '\0') break; /* Dirty */
                   8202:     }
                   8203:   }
                   8204:   else{
                   8205:     strcpy(pathtot,argv[1]);
                   8206:   }
                   8207:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   8208:   /*cygwin_split_path(pathtot,path,optionfile);
                   8209:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   8210:   /* cutv(path,optionfile,pathtot,'\\');*/
                   8211: 
                   8212:   /* Split argv[0], imach program to get pathimach */
                   8213:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   8214:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8215:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8216:  /*   strcpy(pathimach,argv[0]); */
                   8217:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   8218:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8219:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  8220: #ifdef WIN32
                   8221:   _chdir(path); /* Can be a relative path */
                   8222:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   8223: #else
1.126     brouard  8224:   chdir(path); /* Can be a relative path */
1.184     brouard  8225:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   8226: #endif
                   8227:   printf("Current directory %s!\n",pathcd);
1.126     brouard  8228:   strcpy(command,"mkdir ");
                   8229:   strcat(command,optionfilefiname);
                   8230:   if((outcmd=system(command)) != 0){
1.169     brouard  8231:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  8232:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   8233:     /* fclose(ficlog); */
                   8234: /*     exit(1); */
                   8235:   }
                   8236: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   8237: /*     perror("mkdir"); */
                   8238: /*   } */
                   8239: 
                   8240:   /*-------- arguments in the command line --------*/
                   8241: 
1.186     brouard  8242:   /* Main Log file */
1.126     brouard  8243:   strcat(filelog, optionfilefiname);
                   8244:   strcat(filelog,".log");    /* */
                   8245:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   8246:     printf("Problem with logfile %s\n",filelog);
                   8247:     goto end;
                   8248:   }
                   8249:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  8250:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  8251:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   8252:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   8253:  path=%s \n\
                   8254:  optionfile=%s\n\
                   8255:  optionfilext=%s\n\
1.156     brouard  8256:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  8257: 
1.197     brouard  8258:   syscompilerinfo(1);
1.167     brouard  8259: 
1.126     brouard  8260:   printf("Local time (at start):%s",strstart);
                   8261:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   8262:   fflush(ficlog);
                   8263: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  8264: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  8265: 
                   8266:   /* */
                   8267:   strcpy(fileres,"r");
                   8268:   strcat(fileres, optionfilefiname);
1.201     brouard  8269:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  8270:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  8271:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  8272: 
1.186     brouard  8273:   /* Main ---------arguments file --------*/
1.126     brouard  8274: 
                   8275:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  8276:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8277:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  8278:     fflush(ficlog);
1.149     brouard  8279:     /* goto end; */
                   8280:     exit(70); 
1.126     brouard  8281:   }
                   8282: 
                   8283: 
                   8284: 
                   8285:   strcpy(filereso,"o");
1.201     brouard  8286:   strcat(filereso,fileresu);
1.126     brouard  8287:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   8288:     printf("Problem with Output resultfile: %s\n", filereso);
                   8289:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   8290:     fflush(ficlog);
                   8291:     goto end;
                   8292:   }
                   8293: 
                   8294:   /* Reads comments: lines beginning with '#' */
                   8295:   numlinepar=0;
1.197     brouard  8296: 
                   8297:     /* First parameter line */
                   8298:   while(fgets(line, MAXLINE, ficpar)) {
                   8299:     /* If line starts with a # it is a comment */
                   8300:     if (line[0] == '#') {
                   8301:       numlinepar++;
                   8302:       fputs(line,stdout);
                   8303:       fputs(line,ficparo);
                   8304:       fputs(line,ficlog);
                   8305:       continue;
                   8306:     }else
                   8307:       break;
                   8308:   }
                   8309:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   8310:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   8311:     if (num_filled != 5) {
                   8312:       printf("Should be 5 parameters\n");
                   8313:     }
1.126     brouard  8314:     numlinepar++;
1.197     brouard  8315:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8316:   }
                   8317:   /* Second parameter line */
                   8318:   while(fgets(line, MAXLINE, ficpar)) {
                   8319:     /* If line starts with a # it is a comment */
                   8320:     if (line[0] == '#') {
                   8321:       numlinepar++;
                   8322:       fputs(line,stdout);
                   8323:       fputs(line,ficparo);
                   8324:       fputs(line,ficlog);
                   8325:       continue;
                   8326:     }else
                   8327:       break;
                   8328:   }
                   8329:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   8330:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   8331:     if (num_filled != 8) {
1.209     brouard  8332:       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
                   8333:       printf("but line=%s\n",line);
1.197     brouard  8334:     }
                   8335:     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  8336:   }
1.203     brouard  8337:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  8338:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  8339:   /* Third parameter line */
                   8340:   while(fgets(line, MAXLINE, ficpar)) {
                   8341:     /* If line starts with a # it is a comment */
                   8342:     if (line[0] == '#') {
                   8343:       numlinepar++;
                   8344:       fputs(line,stdout);
                   8345:       fputs(line,ficparo);
                   8346:       fputs(line,ficlog);
                   8347:       continue;
                   8348:     }else
                   8349:       break;
                   8350:   }
1.201     brouard  8351:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8352:     if (num_filled == 0)
                   8353:             model[0]='\0';
                   8354:     else if (num_filled != 1){
1.197     brouard  8355:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8356:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8357:       model[0]='\0';
                   8358:       goto end;
                   8359:     }
                   8360:     else{
                   8361:       if (model[0]=='+'){
                   8362:        for(i=1; i<=strlen(model);i++)
                   8363:          modeltemp[i-1]=model[i];
1.201     brouard  8364:        strcpy(model,modeltemp); 
1.197     brouard  8365:       }
                   8366:     }
1.199     brouard  8367:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  8368:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  8369:   }
                   8370:   /* 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); */
                   8371:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8372:   /* 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  8373:   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);
                   8374:   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  8375:   fflush(ficlog);
1.190     brouard  8376:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8377:   if(model[0]=='#'){
1.187     brouard  8378:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8379:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8380:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8381:     if(mle != -1){
                   8382:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8383:       exit(1);
                   8384:     }
                   8385:   }
1.126     brouard  8386:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8387:     ungetc(c,ficpar);
                   8388:     fgets(line, MAXLINE, ficpar);
                   8389:     numlinepar++;
1.195     brouard  8390:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8391:       z[0]=line[1];
                   8392:     }
                   8393:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  8394:     fputs(line, stdout);
                   8395:     //puts(line);
1.126     brouard  8396:     fputs(line,ficparo);
                   8397:     fputs(line,ficlog);
                   8398:   }
                   8399:   ungetc(c,ficpar);
                   8400: 
                   8401:    
1.145     brouard  8402:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  8403:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8404:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8405:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8406:   */
                   8407:   if (strlen(model)>1) 
1.187     brouard  8408:     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  8409:   else
1.187     brouard  8410:     ncovmodel=2; /* Constant and age */
1.133     brouard  8411:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8412:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  8413:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8414:     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);
                   8415:     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);
                   8416:     fflush(stdout);
                   8417:     fclose (ficlog);
                   8418:     goto end;
                   8419:   }
1.126     brouard  8420:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8421:   delti=delti3[1][1];
                   8422:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8423:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8424:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  8425:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8426:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8427:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8428:     fclose (ficparo);
                   8429:     fclose (ficlog);
                   8430:     goto end;
                   8431:     exit(0);
                   8432:   }
1.186     brouard  8433:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  8434:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  8435:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8436:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8437:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8438:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8439:     hess=matrix(1,npar,1,npar);
1.126     brouard  8440:   }
                   8441:   else{
1.145     brouard  8442:     /* Read guessed parameters */
1.126     brouard  8443:     /* Reads comments: lines beginning with '#' */
                   8444:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8445:       ungetc(c,ficpar);
                   8446:       fgets(line, MAXLINE, ficpar);
                   8447:       numlinepar++;
1.141     brouard  8448:       fputs(line,stdout);
1.126     brouard  8449:       fputs(line,ficparo);
                   8450:       fputs(line,ficlog);
                   8451:     }
                   8452:     ungetc(c,ficpar);
                   8453:     
                   8454:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8455:     for(i=1; i <=nlstate; i++){
                   8456:       j=0;
                   8457:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   8458:        if(jj==i) continue;
                   8459:        j++;
                   8460:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  8461:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  8462:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   8463: It might be a problem of design; if ncovcol and the model are correct\n \
                   8464: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   8465:          exit(1);
                   8466:        }
                   8467:        fprintf(ficparo,"%1d%1d",i1,j1);
                   8468:        if(mle==1)
1.193     brouard  8469:          printf("%1d%1d",i,jj);
                   8470:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  8471:        for(k=1; k<=ncovmodel;k++){
                   8472:          fscanf(ficpar," %lf",&param[i][j][k]);
                   8473:          if(mle==1){
                   8474:            printf(" %lf",param[i][j][k]);
                   8475:            fprintf(ficlog," %lf",param[i][j][k]);
                   8476:          }
                   8477:          else
                   8478:            fprintf(ficlog," %lf",param[i][j][k]);
                   8479:          fprintf(ficparo," %lf",param[i][j][k]);
                   8480:        }
                   8481:        fscanf(ficpar,"\n");
                   8482:        numlinepar++;
                   8483:        if(mle==1)
                   8484:          printf("\n");
                   8485:        fprintf(ficlog,"\n");
                   8486:        fprintf(ficparo,"\n");
                   8487:       }
                   8488:     }  
                   8489:     fflush(ficlog);
                   8490: 
1.145     brouard  8491:     /* Reads scales values */
1.126     brouard  8492:     p=param[1][1];
                   8493:     
                   8494:     /* Reads comments: lines beginning with '#' */
                   8495:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8496:       ungetc(c,ficpar);
                   8497:       fgets(line, MAXLINE, ficpar);
                   8498:       numlinepar++;
1.141     brouard  8499:       fputs(line,stdout);
1.126     brouard  8500:       fputs(line,ficparo);
                   8501:       fputs(line,ficlog);
                   8502:     }
                   8503:     ungetc(c,ficpar);
                   8504: 
                   8505:     for(i=1; i <=nlstate; i++){
                   8506:       for(j=1; j <=nlstate+ndeath-1; j++){
                   8507:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  8508:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  8509:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8510:          exit(1);
                   8511:        }
                   8512:        printf("%1d%1d",i,j);
                   8513:        fprintf(ficparo,"%1d%1d",i1,j1);
                   8514:        fprintf(ficlog,"%1d%1d",i1,j1);
                   8515:        for(k=1; k<=ncovmodel;k++){
                   8516:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8517:          printf(" %le",delti3[i][j][k]);
                   8518:          fprintf(ficparo," %le",delti3[i][j][k]);
                   8519:          fprintf(ficlog," %le",delti3[i][j][k]);
                   8520:        }
                   8521:        fscanf(ficpar,"\n");
                   8522:        numlinepar++;
                   8523:        printf("\n");
                   8524:        fprintf(ficparo,"\n");
                   8525:        fprintf(ficlog,"\n");
                   8526:       }
                   8527:     }
                   8528:     fflush(ficlog);
                   8529: 
1.145     brouard  8530:     /* Reads covariance matrix */
1.126     brouard  8531:     delti=delti3[1][1];
                   8532: 
                   8533: 
                   8534:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   8535:   
                   8536:     /* Reads comments: lines beginning with '#' */
                   8537:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8538:       ungetc(c,ficpar);
                   8539:       fgets(line, MAXLINE, ficpar);
                   8540:       numlinepar++;
1.141     brouard  8541:       fputs(line,stdout);
1.126     brouard  8542:       fputs(line,ficparo);
                   8543:       fputs(line,ficlog);
                   8544:     }
                   8545:     ungetc(c,ficpar);
                   8546:   
                   8547:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8548:     hess=matrix(1,npar,1,npar);
1.131     brouard  8549:     for(i=1; i <=npar; i++)
                   8550:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   8551:       
1.194     brouard  8552:     /* Scans npar lines */
1.126     brouard  8553:     for(i=1; i <=npar; i++){
1.194     brouard  8554:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8555:       if(count != 3){
                   8556:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   8557: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8558: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   8559:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   8560: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8561: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   8562:        exit(1);
                   8563:       }else
1.218     brouard  8564:        if(mle==1)
                   8565:          printf("%1d%1d%1d",i1,j1,jk);
1.194     brouard  8566:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   8567:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  8568:       for(j=1; j <=i; j++){
                   8569:        fscanf(ficpar," %le",&matcov[i][j]);
                   8570:        if(mle==1){
                   8571:          printf(" %.5le",matcov[i][j]);
                   8572:        }
                   8573:        fprintf(ficlog," %.5le",matcov[i][j]);
                   8574:        fprintf(ficparo," %.5le",matcov[i][j]);
                   8575:       }
                   8576:       fscanf(ficpar,"\n");
                   8577:       numlinepar++;
                   8578:       if(mle==1)
                   8579:        printf("\n");
                   8580:       fprintf(ficlog,"\n");
                   8581:       fprintf(ficparo,"\n");
                   8582:     }
1.194     brouard  8583:     /* End of read covariance matrix npar lines */
1.126     brouard  8584:     for(i=1; i <=npar; i++)
                   8585:       for(j=i+1;j<=npar;j++)
                   8586:        matcov[i][j]=matcov[j][i];
                   8587:     
                   8588:     if(mle==1)
                   8589:       printf("\n");
                   8590:     fprintf(ficlog,"\n");
                   8591:     
                   8592:     fflush(ficlog);
                   8593:     
                   8594:     /*-------- Rewriting parameter file ----------*/
                   8595:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   8596:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   8597:     strcat(rfileres,".");    /* */
                   8598:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   8599:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  8600:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   8601:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  8602:     }
                   8603:     fprintf(ficres,"#%s\n",version);
                   8604:   }    /* End of mle != -3 */
1.218     brouard  8605:   
1.186     brouard  8606:   /*  Main data
                   8607:    */
1.126     brouard  8608:   n= lastobs;
                   8609:   num=lvector(1,n);
                   8610:   moisnais=vector(1,n);
                   8611:   annais=vector(1,n);
                   8612:   moisdc=vector(1,n);
                   8613:   andc=vector(1,n);
                   8614:   agedc=vector(1,n);
                   8615:   cod=ivector(1,n);
                   8616:   weight=vector(1,n);
                   8617:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   8618:   mint=matrix(1,maxwav,1,n);
                   8619:   anint=matrix(1,maxwav,1,n);
1.131     brouard  8620:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  8621:   tab=ivector(1,NCOVMAX);
1.144     brouard  8622:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  8623:   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  8624: 
1.136     brouard  8625:   /* Reads data from file datafile */
                   8626:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   8627:     goto end;
                   8628: 
                   8629:   /* Calculation of the number of parameters from char model */
1.137     brouard  8630:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   8631:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   8632:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   8633:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   8634:        k=1 Tvar[1]=2 (from V2)
                   8635:     */
                   8636:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   8637:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   8638:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   8639:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   8640:   */
                   8641:   /* For model-covariate k tells which data-covariate to use but
                   8642:     because this model-covariate is a construction we invent a new column
                   8643:     ncovcol + k1
                   8644:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   8645:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  8646:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  8647:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   8648:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   8649:   */
1.145     brouard  8650:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   8651:   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  8652:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   8653:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  8654:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  8655:                         4 covariates (3 plus signs)
                   8656:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   8657:                      */  
1.136     brouard  8658: 
1.186     brouard  8659: /* Main decodemodel */
                   8660: 
1.187     brouard  8661: 
1.136     brouard  8662:   if(decodemodel(model, lastobs) == 1)
                   8663:     goto end;
                   8664: 
1.137     brouard  8665:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   8666:     nbwarn++;
                   8667:     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); 
                   8668:     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); 
                   8669:   }
1.136     brouard  8670:     /*  if(mle==1){*/
1.137     brouard  8671:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   8672:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  8673:   }
                   8674: 
                   8675:     /*-calculation of age at interview from date of interview and age at death -*/
                   8676:   agev=matrix(1,maxwav,1,imx);
                   8677: 
                   8678:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   8679:     goto end;
                   8680: 
1.126     brouard  8681: 
1.136     brouard  8682:   agegomp=(int)agemin;
                   8683:   free_vector(moisnais,1,n);
                   8684:   free_vector(annais,1,n);
1.126     brouard  8685:   /* free_matrix(mint,1,maxwav,1,n);
                   8686:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  8687:   /* free_vector(moisdc,1,n); */
                   8688:   /* free_vector(andc,1,n); */
1.145     brouard  8689:   /* */
                   8690:   
1.126     brouard  8691:   wav=ivector(1,imx);
1.214     brouard  8692:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8693:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8694:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8695:   dh=imatrix(1,lastpass-firstpass+2,1,imx); /* We are adding a wave if status is unknown at last wave but death occurs after last wave.*/
                   8696:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   8697:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  8698:    
                   8699:   /* Concatenates waves */
1.214     brouard  8700:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   8701:      Death is a valid wave (if date is known).
                   8702:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   8703:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   8704:      and mw[mi+1][i]. dh depends on stepm.
                   8705:   */
                   8706: 
1.126     brouard  8707:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  8708:   /* */
                   8709:  
1.215     brouard  8710:   free_vector(moisdc,1,n);
                   8711:   free_vector(andc,1,n);
                   8712: 
1.126     brouard  8713:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   8714: 
                   8715:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   8716:   ncodemax[1]=1;
1.145     brouard  8717:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  8718:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  8719:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211     brouard  8720:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  8721:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  8722:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  8723: 
1.200     brouard  8724:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  8725:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  8726:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  8727:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   8728:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   8729:    * (currently 0 or 1) in the data.
                   8730:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   8731:    * corresponding modality (h,j).
                   8732:    */
                   8733: 
1.145     brouard  8734:   h=0;
                   8735: 
                   8736: 
                   8737:   /*if (cptcovn > 0) */
1.126     brouard  8738:       
1.145     brouard  8739:  
1.126     brouard  8740:   m=pow(2,cptcoveff);
                   8741:  
1.144     brouard  8742:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  8743:           * For k=4 covariates, h goes from 1 to m=2**k
                   8744:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   8745:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  8746:           *     h\k   1     2     3     4
1.143     brouard  8747:           *______________________________  
                   8748:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   8749:           *     2     2     1     1     1
                   8750:           *     3 i=2 1     2     1     1
                   8751:           *     4     2     2     1     1
                   8752:           *     5 i=3 1 i=2 1     2     1
                   8753:           *     6     2     1     2     1
                   8754:           *     7 i=4 1     2     2     1
                   8755:           *     8     2     2     2     1
1.197     brouard  8756:           *     9 i=5 1 i=3 1 i=2 1     2
                   8757:           *    10     2     1     1     2
                   8758:           *    11 i=6 1     2     1     2
                   8759:           *    12     2     2     1     2
                   8760:           *    13 i=7 1 i=4 1     2     2    
                   8761:           *    14     2     1     2     2
                   8762:           *    15 i=8 1     2     2     2
                   8763:           *    16     2     2     2     2
1.143     brouard  8764:           */
1.212     brouard  8765:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  8766:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   8767:      * and the value of each covariate?
                   8768:      * V1=1, V2=1, V3=2, V4=1 ?
                   8769:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   8770:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   8771:      * In order to get the real value in the data, we use nbcode
                   8772:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   8773:      * We are keeping this crazy system in order to be able (in the future?) 
                   8774:      * to have more than 2 values (0 or 1) for a covariate.
                   8775:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   8776:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   8777:      *              bbbbbbbb
                   8778:      *              76543210     
                   8779:      *   h-1        00000101 (6-1=5)
1.219   ! brouard  8780:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  8781:      *           &
                   8782:      *     1        00000001 (1)
1.219   ! brouard  8783:      *              00000000        = 1 & ((h-1) >> (k-1))
        !          8784:      *          +1= 00000001 =1 
1.211     brouard  8785:      *
                   8786:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   8787:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   8788:      *    >>k'            11
                   8789:      *          &   00000001
                   8790:      *            = 00000001
                   8791:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   8792:      * Reverse h=6 and m=16?
                   8793:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   8794:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   8795:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   8796:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   8797:      * V3=decodtabm(14,3,2**4)=2
                   8798:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   8799:      *(h-1) >> (j-1)    0011 =13 >> 2
                   8800:      *          &1 000000001
                   8801:      *           = 000000001
                   8802:      *         +1= 000000010 =2
                   8803:      *                  2211
                   8804:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   8805:      *                  V3=2
                   8806:      */
                   8807: 
1.202     brouard  8808:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   8809:   /*   /\* printf("h=%2d ", h); *\/ */
                   8810:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   8811:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   8812:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   8813:   /*    /\* } *\/ */
                   8814:   /*    /\* printf("\n"); *\/ */
                   8815:   /* } */
1.197     brouard  8816:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   8817:   /*   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 *\/  */
                   8818:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   8819:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   8820:   /*     h++; */
                   8821:   /*     if (h>m)  */
                   8822:   /*       h=1; */
                   8823:   /*     codtab[h][k]=j; */
                   8824:   /*     /\* codtab[12][3]=1; *\/ */
                   8825:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   8826:   /*     /\* 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]]); *\/ */
                   8827:   /*   }  */
                   8828:   /*     } */
                   8829:   /*   } */
                   8830:   /* }  */
1.126     brouard  8831:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   8832:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  8833:   /* for(i=1; i <=m ;i++){  */
                   8834:   /*    for(k=1; k <=cptcovn; k++){ */
                   8835:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   8836:   /*    } */
                   8837:   /*    printf("\n"); */
                   8838:   /* } */
                   8839:   /*   scanf("%d",i);*/
1.145     brouard  8840: 
                   8841:  free_ivector(Ndum,-1,NCOVMAX);
                   8842: 
                   8843: 
1.126     brouard  8844:     
1.186     brouard  8845:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  8846:   strcpy(optionfilegnuplot,optionfilefiname);
                   8847:   if(mle==-3)
1.201     brouard  8848:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  8849:   strcat(optionfilegnuplot,".gp");
                   8850: 
                   8851:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   8852:     printf("Problem with file %s",optionfilegnuplot);
                   8853:   }
                   8854:   else{
1.204     brouard  8855:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  8856:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  8857:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   8858:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  8859:   }
                   8860:   /*  fclose(ficgp);*/
1.186     brouard  8861: 
                   8862: 
                   8863:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  8864: 
                   8865:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   8866:   if(mle==-3)
1.201     brouard  8867:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  8868:   strcat(optionfilehtm,".htm");
                   8869:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  8870:     printf("Problem with %s \n",optionfilehtm);
                   8871:     exit(0);
1.126     brouard  8872:   }
                   8873: 
                   8874:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   8875:   strcat(optionfilehtmcov,"-cov.htm");
                   8876:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   8877:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   8878:   }
                   8879:   else{
                   8880:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   8881: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8882: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  8883:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   8884:   }
                   8885: 
1.213     brouard  8886:   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é-2013-2016-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-2018</a></font><br>  \
1.204     brouard  8887: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   8888: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  8889: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8890: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  8891: \n\
                   8892: <hr  size=\"2\" color=\"#EC5E5E\">\
                   8893:  <ul><li><h4>Parameter files</h4>\n\
                   8894:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   8895:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   8896:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   8897:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   8898:  - Date and time at start: %s</ul>\n",\
                   8899:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   8900:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   8901:          fileres,fileres,\
                   8902:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   8903:   fflush(fichtm);
                   8904: 
                   8905:   strcpy(pathr,path);
                   8906:   strcat(pathr,optionfilefiname);
1.184     brouard  8907: #ifdef WIN32
                   8908:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   8909: #else
1.126     brouard  8910:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  8911: #endif
                   8912:          
1.126     brouard  8913:   
                   8914:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   8915:      and prints on file fileres'p'. */
1.214     brouard  8916:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
                   8917:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  8918: 
                   8919:   fprintf(fichtm,"\n");
                   8920:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   8921: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   8922: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   8923:          imx,agemin,agemax,jmin,jmax,jmean);
                   8924:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8925:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8926:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8927:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8928:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  8929: 
1.126     brouard  8930:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   8931:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   8932:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   8933: 
                   8934:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  8935:   /* For mortality only */
1.126     brouard  8936:   if (mle==-3){
1.136     brouard  8937:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  8938:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  8939:     cens=ivector(1,n);
                   8940:     ageexmed=vector(1,n);
                   8941:     agecens=vector(1,n);
                   8942:     dcwave=ivector(1,n);
                   8943:  
                   8944:     for (i=1; i<=imx; i++){
                   8945:       dcwave[i]=-1;
                   8946:       for (m=firstpass; m<=lastpass; m++)
1.218     brouard  8947:                                if (s[m][i]>nlstate) {
                   8948:                                        dcwave[i]=m;
                   8949:                                        /*      printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   8950:                                        break;
                   8951:                                }
1.126     brouard  8952:     }
1.218     brouard  8953:                
1.126     brouard  8954:     for (i=1; i<=imx; i++) {
                   8955:       if (wav[i]>0){
1.218     brouard  8956:                                ageexmed[i]=agev[mw[1][i]][i];
                   8957:                                j=wav[i];
                   8958:                                agecens[i]=1.; 
                   8959:                                
                   8960:                                if (ageexmed[i]> 1 && wav[i] > 0){
                   8961:                                        agecens[i]=agev[mw[j][i]][i];
                   8962:                                        cens[i]= 1;
                   8963:                                }else if (ageexmed[i]< 1) 
                   8964:                                        cens[i]= -1;
                   8965:                                if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   8966:                                        cens[i]=0 ;
1.126     brouard  8967:       }
                   8968:       else cens[i]=-1;
                   8969:     }
                   8970:     
                   8971:     for (i=1;i<=NDIM;i++) {
                   8972:       for (j=1;j<=NDIM;j++)
1.218     brouard  8973:                                ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  8974:     }
                   8975:     
1.145     brouard  8976:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  8977:     /*printf("%lf %lf", p[1], p[2]);*/
                   8978:     
                   8979:     
1.136     brouard  8980: #ifdef GSL
                   8981:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  8982: #else
1.126     brouard  8983:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  8984: #endif
1.201     brouard  8985:     strcpy(filerespow,"POW-MORT_"); 
                   8986:     strcat(filerespow,fileresu);
1.126     brouard  8987:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   8988:       printf("Problem with resultfile: %s\n", filerespow);
                   8989:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   8990:     }
1.136     brouard  8991: #ifdef GSL
                   8992:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  8993: #else
1.126     brouard  8994:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  8995: #endif
1.126     brouard  8996:     /*  for (i=1;i<=nlstate;i++)
                   8997:        for(j=1;j<=nlstate+ndeath;j++)
                   8998:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   8999:     */
                   9000:     fprintf(ficrespow,"\n");
1.136     brouard  9001: #ifdef GSL
                   9002:     /* gsl starts here */ 
                   9003:     T = gsl_multimin_fminimizer_nmsimplex;
                   9004:     gsl_multimin_fminimizer *sfm = NULL;
                   9005:     gsl_vector *ss, *x;
                   9006:     gsl_multimin_function minex_func;
                   9007: 
                   9008:     /* Initial vertex size vector */
                   9009:     ss = gsl_vector_alloc (NDIM);
                   9010:     
                   9011:     if (ss == NULL){
                   9012:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9013:     }
                   9014:     /* Set all step sizes to 1 */
                   9015:     gsl_vector_set_all (ss, 0.001);
                   9016: 
                   9017:     /* Starting point */
1.126     brouard  9018:     
1.136     brouard  9019:     x = gsl_vector_alloc (NDIM);
                   9020:     
                   9021:     if (x == NULL){
                   9022:       gsl_vector_free(ss);
                   9023:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9024:     }
                   9025:   
                   9026:     /* Initialize method and iterate */
                   9027:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  9028:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9029:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  9030:     gsl_vector_set(x, 0, p[1]);
                   9031:     gsl_vector_set(x, 1, p[2]);
                   9032: 
                   9033:     minex_func.f = &gompertz_f;
                   9034:     minex_func.n = NDIM;
                   9035:     minex_func.params = (void *)&p; /* ??? */
                   9036:     
                   9037:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9038:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9039:     
                   9040:     printf("Iterations beginning .....\n\n");
                   9041:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9042: 
                   9043:     iteri=0;
                   9044:     while (rval == GSL_CONTINUE){
                   9045:       iteri++;
                   9046:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9047:       
                   9048:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9049:       fflush(0);
                   9050:       
                   9051:       if (status) 
                   9052:         break;
                   9053:       
                   9054:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   9055:       ssval = gsl_multimin_fminimizer_size (sfm);
                   9056:       
                   9057:       if (rval == GSL_SUCCESS)
                   9058:         printf ("converged to a local maximum at\n");
                   9059:       
                   9060:       printf("%5d ", iteri);
                   9061:       for (it = 0; it < NDIM; it++){
                   9062:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   9063:       }
                   9064:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   9065:     }
                   9066:     
                   9067:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   9068:     
                   9069:     gsl_vector_free(x); /* initial values */
                   9070:     gsl_vector_free(ss); /* inital step size */
                   9071:     for (it=0; it<NDIM; it++){
                   9072:       p[it+1]=gsl_vector_get(sfm->x,it);
                   9073:       fprintf(ficrespow," %.12lf", p[it]);
                   9074:     }
                   9075:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   9076: #endif
                   9077: #ifdef POWELL
                   9078:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   9079: #endif  
1.126     brouard  9080:     fclose(ficrespow);
                   9081:     
1.203     brouard  9082:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  9083: 
                   9084:     for(i=1; i <=NDIM; i++)
                   9085:       for(j=i+1;j<=NDIM;j++)
                   9086:        matcov[i][j]=matcov[j][i];
                   9087:     
                   9088:     printf("\nCovariance matrix\n ");
1.203     brouard  9089:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  9090:     for(i=1; i <=NDIM; i++) {
                   9091:       for(j=1;j<=NDIM;j++){ 
                   9092:        printf("%f ",matcov[i][j]);
1.203     brouard  9093:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  9094:       }
1.203     brouard  9095:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  9096:     }
                   9097:     
                   9098:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  9099:     for (i=1;i<=NDIM;i++) {
1.126     brouard  9100:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  9101:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9102:     }
1.126     brouard  9103:     lsurv=vector(1,AGESUP);
                   9104:     lpop=vector(1,AGESUP);
                   9105:     tpop=vector(1,AGESUP);
                   9106:     lsurv[agegomp]=100000;
                   9107:     
                   9108:     for (k=agegomp;k<=AGESUP;k++) {
                   9109:       agemortsup=k;
                   9110:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   9111:     }
                   9112:     
                   9113:     for (k=agegomp;k<agemortsup;k++)
                   9114:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   9115:     
                   9116:     for (k=agegomp;k<agemortsup;k++){
                   9117:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   9118:       sumlpop=sumlpop+lpop[k];
                   9119:     }
                   9120:     
                   9121:     tpop[agegomp]=sumlpop;
                   9122:     for (k=agegomp;k<(agemortsup-3);k++){
                   9123:       /*  tpop[k+1]=2;*/
                   9124:       tpop[k+1]=tpop[k]-lpop[k];
                   9125:     }
                   9126:     
                   9127:     
                   9128:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   9129:     for (k=agegomp;k<(agemortsup-2);k++) 
                   9130:       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]);
                   9131:     
                   9132:     
                   9133:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9134:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   9135:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9136: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9137: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9138:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9139: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9140: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9141:     }else
1.201     brouard  9142:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   9143:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  9144:                     stepm, weightopt,\
                   9145:                     model,imx,p,matcov,agemortsup);
                   9146:     
                   9147:     free_vector(lsurv,1,AGESUP);
                   9148:     free_vector(lpop,1,AGESUP);
                   9149:     free_vector(tpop,1,AGESUP);
1.136     brouard  9150: #ifdef GSL
                   9151:     free_ivector(cens,1,n);
                   9152:     free_vector(agecens,1,n);
                   9153:     free_ivector(dcwave,1,n);
                   9154:     free_matrix(ximort,1,NDIM,1,NDIM);
                   9155: #endif
1.186     brouard  9156:   } /* Endof if mle==-3 mortality only */
1.205     brouard  9157:   /* Standard  */
                   9158:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   9159:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9160:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  9161:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  9162:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9163:     for (k=1; k<=npar;k++)
                   9164:       printf(" %d %8.5f",k,p[k]);
                   9165:     printf("\n");
1.205     brouard  9166:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   9167:       /* mlikeli uses func not funcone */
                   9168:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   9169:     }
                   9170:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   9171:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9172:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9173:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9174:     }
                   9175:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  9176:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9177:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9178:     for (k=1; k<=npar;k++)
                   9179:       printf(" %d %8.5f",k,p[k]);
                   9180:     printf("\n");
                   9181:     
                   9182:     /*--------- results files --------------*/
1.192     brouard  9183:     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  9184:     
                   9185:     
                   9186:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9187:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9188:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9189:     for(i=1,jk=1; i <=nlstate; i++){
                   9190:       for(k=1; k <=(nlstate+ndeath); k++){
                   9191:        if (k != i) {
                   9192:          printf("%d%d ",i,k);
                   9193:          fprintf(ficlog,"%d%d ",i,k);
                   9194:          fprintf(ficres,"%1d%1d ",i,k);
                   9195:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  9196:            printf("%12.7f ",p[jk]);
                   9197:            fprintf(ficlog,"%12.7f ",p[jk]);
                   9198:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  9199:            jk++; 
                   9200:          }
                   9201:          printf("\n");
                   9202:          fprintf(ficlog,"\n");
                   9203:          fprintf(ficres,"\n");
                   9204:        }
                   9205:       }
                   9206:     }
1.203     brouard  9207:     if(mle != 0){
                   9208:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  9209:       ftolhess=ftol; /* Usually correct */
1.203     brouard  9210:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   9211:       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");
                   9212:       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");
                   9213:       for(i=1,jk=1; i <=nlstate; i++){
                   9214:        for(k=1; k <=(nlstate+ndeath); k++){
                   9215:          if (k != i) {
                   9216:            printf("%d%d ",i,k);
                   9217:            fprintf(ficlog,"%d%d ",i,k);
                   9218:            for(j=1; j <=ncovmodel; j++){
                   9219:              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]));
                   9220:              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]));
                   9221:              jk++; 
                   9222:            }
                   9223:            printf("\n");
                   9224:            fprintf(ficlog,"\n");
1.193     brouard  9225:          }
                   9226:        }
                   9227:       }
1.203     brouard  9228:     } /* end of hesscov and Wald tests */
1.193     brouard  9229: 
1.203     brouard  9230:     /*  */
1.126     brouard  9231:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   9232:     printf("# Scales (for hessian or gradient estimation)\n");
                   9233:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   9234:     for(i=1,jk=1; i <=nlstate; i++){
                   9235:       for(j=1; j <=nlstate+ndeath; j++){
                   9236:        if (j!=i) {
                   9237:          fprintf(ficres,"%1d%1d",i,j);
                   9238:          printf("%1d%1d",i,j);
                   9239:          fprintf(ficlog,"%1d%1d",i,j);
                   9240:          for(k=1; k<=ncovmodel;k++){
                   9241:            printf(" %.5e",delti[jk]);
                   9242:            fprintf(ficlog," %.5e",delti[jk]);
                   9243:            fprintf(ficres," %.5e",delti[jk]);
                   9244:            jk++;
                   9245:          }
                   9246:          printf("\n");
                   9247:          fprintf(ficlog,"\n");
                   9248:          fprintf(ficres,"\n");
                   9249:        }
                   9250:       }
                   9251:     }
                   9252:     
                   9253:     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  9254:     if(mle >= 1) /* To big for the screen */
1.126     brouard  9255:       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");
                   9256:     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");
                   9257:     /* # 121 Var(a12)\n\ */
                   9258:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9259:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9260:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9261:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9262:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9263:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9264:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9265:     
                   9266:     
                   9267:     /* Just to have a covariance matrix which will be more understandable
                   9268:        even is we still don't want to manage dictionary of variables
                   9269:     */
                   9270:     for(itimes=1;itimes<=2;itimes++){
                   9271:       jj=0;
                   9272:       for(i=1; i <=nlstate; i++){
                   9273:        for(j=1; j <=nlstate+ndeath; j++){
                   9274:          if(j==i) continue;
                   9275:          for(k=1; k<=ncovmodel;k++){
                   9276:            jj++;
                   9277:            ca[0]= k+'a'-1;ca[1]='\0';
                   9278:            if(itimes==1){
                   9279:              if(mle>=1)
                   9280:                printf("#%1d%1d%d",i,j,k);
                   9281:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   9282:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   9283:            }else{
                   9284:              if(mle>=1)
                   9285:                printf("%1d%1d%d",i,j,k);
                   9286:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   9287:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   9288:            }
                   9289:            ll=0;
                   9290:            for(li=1;li <=nlstate; li++){
                   9291:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   9292:                if(lj==li) continue;
                   9293:                for(lk=1;lk<=ncovmodel;lk++){
                   9294:                  ll++;
                   9295:                  if(ll<=jj){
                   9296:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   9297:                    if(ll<jj){
                   9298:                      if(itimes==1){
                   9299:                        if(mle>=1)
                   9300:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9301:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9302:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9303:                      }else{
                   9304:                        if(mle>=1)
                   9305:                          printf(" %.5e",matcov[jj][ll]); 
                   9306:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   9307:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   9308:                      }
                   9309:                    }else{
                   9310:                      if(itimes==1){
                   9311:                        if(mle>=1)
                   9312:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   9313:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9314:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9315:                      }else{
                   9316:                        if(mle>=1)
1.203     brouard  9317:                          printf(" %.7e",matcov[jj][ll]); 
                   9318:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9319:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  9320:                      }
                   9321:                    }
                   9322:                  }
                   9323:                } /* end lk */
                   9324:              } /* end lj */
                   9325:            } /* end li */
                   9326:            if(mle>=1)
                   9327:              printf("\n");
                   9328:            fprintf(ficlog,"\n");
                   9329:            fprintf(ficres,"\n");
                   9330:            numlinepar++;
                   9331:          } /* end k*/
                   9332:        } /*end j */
                   9333:       } /* end i */
                   9334:     } /* end itimes */
                   9335:     
                   9336:     fflush(ficlog);
                   9337:     fflush(ficres);
1.209     brouard  9338:       while(fgets(line, MAXLINE, ficpar)) {
                   9339:     /* If line starts with a # it is a comment */
                   9340:     if (line[0] == '#') {
                   9341:       numlinepar++;
1.141     brouard  9342:       fputs(line,stdout);
1.126     brouard  9343:       fputs(line,ficparo);
1.209     brouard  9344:       fputs(line,ficlog);
                   9345:       continue;
                   9346:     }else
                   9347:       break;
                   9348:   }
                   9349: 
                   9350:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9351:     /*   ungetc(c,ficpar); */
                   9352:     /*   fgets(line, MAXLINE, ficpar); */
                   9353:     /*   fputs(line,stdout); */
                   9354:     /*   fputs(line,ficparo); */
                   9355:     /* } */
                   9356:     /* ungetc(c,ficpar); */
1.126     brouard  9357:     
                   9358:     estepm=0;
1.209     brouard  9359:     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
                   9360: 
                   9361:     if (num_filled != 6) {
1.219   ! brouard  9362:       printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
        !          9363:       fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
1.209     brouard  9364:       goto end;
                   9365:     }
                   9366:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9367:   }
                   9368:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9369:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9370: 
                   9371:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  9372:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9373:     if (fage <= 2) {
                   9374:       bage = ageminpar;
                   9375:       fage = agemaxpar;
                   9376:     }
                   9377:     
                   9378:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  9379:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9380:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186     brouard  9381: 
                   9382:     /* Other stuffs, more or less useful */    
1.126     brouard  9383:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9384:       ungetc(c,ficpar);
                   9385:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9386:       fputs(line,stdout);
1.126     brouard  9387:       fputs(line,ficparo);
                   9388:     }
                   9389:     ungetc(c,ficpar);
                   9390:     
                   9391:     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);
                   9392:     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);
                   9393:     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);
                   9394:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9395:     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);
                   9396:     
                   9397:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9398:       ungetc(c,ficpar);
                   9399:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9400:       fputs(line,stdout);
1.126     brouard  9401:       fputs(line,ficparo);
                   9402:     }
                   9403:     ungetc(c,ficpar);
                   9404:     
                   9405:     
                   9406:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9407:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9408:     
                   9409:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  9410:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  9411:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9412:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9413:     
                   9414:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9415:       ungetc(c,ficpar);
                   9416:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9417:       fputs(line,stdout);
1.126     brouard  9418:       fputs(line,ficparo);
                   9419:     }
                   9420:     ungetc(c,ficpar);
                   9421:     
                   9422:     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);
                   9423:     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);
                   9424:     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);
                   9425:     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);
                   9426:     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);
                   9427:     /* day and month of proj2 are not used but only year anproj2.*/
                   9428:     
1.217     brouard  9429:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9430:       ungetc(c,ficpar);
                   9431:       fgets(line, MAXLINE, ficpar);
                   9432:       fputs(line,stdout);
                   9433:       fputs(line,ficparo);
                   9434:     }
                   9435:     ungetc(c,ficpar);
                   9436:     
                   9437:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.219   ! brouard  9438:     fprintf(ficparo,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
        !          9439:     fprintf(ficlog,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
        !          9440:     fprintf(ficres,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
1.217     brouard  9441:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  9442:     
                   9443:     
1.145     brouard  9444:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   9445:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  9446:     
                   9447:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9448:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   9449:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9450: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9451: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9452:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9453: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9454: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9455:     }else
1.218     brouard  9456:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.126     brouard  9457:     
1.201     brouard  9458:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.217     brouard  9459:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
1.213     brouard  9460:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.126     brouard  9461:       
                   9462:    /*------------ free_vector  -------------*/
                   9463:    /*  chdir(path); */
                   9464:  
1.215     brouard  9465:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9466:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9467:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9468:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  9469:     free_lvector(num,1,n);
                   9470:     free_vector(agedc,1,n);
                   9471:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9472:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9473:     fclose(ficparo);
                   9474:     fclose(ficres);
                   9475: 
                   9476: 
1.186     brouard  9477:     /* Other results (useful)*/
                   9478: 
                   9479: 
1.126     brouard  9480:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  9481:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9482:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  9483:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  9484:     fclose(ficrespl);
                   9485: 
                   9486:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  9487:     /*#include "hpijx.h"*/
                   9488:     hPijx(p, bage, fage);
1.145     brouard  9489:     fclose(ficrespij);
1.126     brouard  9490: 
1.219   ! brouard  9491:     ncovcombmax=  pow(2,cptcoveff);
        !          9492:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  9493:     k=1;
1.126     brouard  9494:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9495: 
1.219   ! brouard  9496:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  9497:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  9498:     for(i=1;i<=AGESUP;i++)
1.219   ! brouard  9499:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.218     brouard  9500:                                for(k=1;k<=ncovcombmax;k++)
                   9501:                                        probs[i][j][k]=0.;
1.219   ! brouard  9502:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
        !          9503:     if (mobilav!=0 ||mobilavproj !=0 ) {
        !          9504:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
        !          9505:                        for(i=1;i<=AGESUP;i++)
        !          9506:                                for(j=1;j<=nlstate;j++)
        !          9507:                                        for(k=1;k<=ncovcombmax;k++)
        !          9508:                                                mobaverages[i][j][k]=0.;
        !          9509:       mobaverage=mobaverages;
        !          9510:       if (mobilav!=0) {
1.218     brouard  9511:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   9512:                                        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9513:                                        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9514:                                }
1.219   ! brouard  9515:       }
        !          9516:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
        !          9517:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
        !          9518:       else if (mobilavproj !=0) {
1.218     brouard  9519:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   9520:                                        fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9521:                                        printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9522:                                }
1.219   ! brouard  9523:       }
        !          9524:     }/* end if moving average */
        !          9525:                
1.126     brouard  9526:     /*---------- Forecasting ------------------*/
                   9527:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9528:     if(prevfcast==1){
                   9529:       /*    if(stepm ==1){*/
1.201     brouard  9530:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  9531:     }
1.217     brouard  9532:     if(backcast==1){
1.219   ! brouard  9533:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
        !          9534:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
        !          9535:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
        !          9536: 
        !          9537:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
        !          9538: 
        !          9539:       bprlim=matrix(1,nlstate,1,nlstate);
        !          9540:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
        !          9541:       fclose(ficresplb);
        !          9542: 
        !          9543:       hBijx(p, bage, fage, mobaverage);
        !          9544:       fclose(ficrespijb);
        !          9545:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
        !          9546: 
        !          9547:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
        !          9548:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
        !          9549:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
        !          9550:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
        !          9551:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
        !          9552:     }
1.217     brouard  9553:     
1.186     brouard  9554:  
                   9555:     /* ------ Other prevalence ratios------------ */
1.126     brouard  9556: 
1.215     brouard  9557:     free_ivector(wav,1,imx);
                   9558:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9559:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9560:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  9561:                
                   9562:                
1.127     brouard  9563:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  9564:                
1.201     brouard  9565:     strcpy(filerese,"E_");
                   9566:     strcat(filerese,fileresu);
1.126     brouard  9567:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9568:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9569:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9570:     }
1.208     brouard  9571:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9572:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219   ! brouard  9573:                
1.145     brouard  9574:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.219   ! brouard  9575:       fprintf(ficreseij,"\n#****** ");
        !          9576:       for(j=1;j<=cptcoveff;j++) {
        !          9577:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9578:       }
        !          9579:       fprintf(ficreseij,"******\n");
        !          9580:       
        !          9581:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
        !          9582:       oldm=oldms;savm=savms;
        !          9583:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
1.127     brouard  9584:       
1.219   ! brouard  9585:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  9586:     }
                   9587:     fclose(ficreseij);
1.208     brouard  9588:     printf("done evsij\n");fflush(stdout);
                   9589:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  9590:                
1.127     brouard  9591:     /*---------- Health expectancies and variances ------------*/
1.218     brouard  9592:                
                   9593:                
1.201     brouard  9594:     strcpy(filerest,"T_");
                   9595:     strcat(filerest,fileresu);
1.127     brouard  9596:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   9597:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   9598:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   9599:     }
1.208     brouard  9600:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   9601:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  9602:                
1.126     brouard  9603: 
1.201     brouard  9604:     strcpy(fileresstde,"STDE_");
                   9605:     strcat(fileresstde,fileresu);
1.126     brouard  9606:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   9607:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9608:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9609:     }
1.208     brouard  9610:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9611:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  9612: 
1.201     brouard  9613:     strcpy(filerescve,"CVE_");
                   9614:     strcat(filerescve,fileresu);
1.126     brouard  9615:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   9616:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9617:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9618:     }
1.208     brouard  9619:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9620:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  9621: 
1.201     brouard  9622:     strcpy(fileresv,"V_");
                   9623:     strcat(fileresv,fileresu);
1.126     brouard  9624:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   9625:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9626:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9627:     }
1.208     brouard  9628:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   9629:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  9630: 
1.145     brouard  9631:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9632:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9633:           
                   9634:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  9635:       fprintf(ficrest,"\n#****** ");
                   9636:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9637:                                fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9638:       fprintf(ficrest,"******\n");
                   9639:       
                   9640:       fprintf(ficresstdeij,"\n#****** ");
                   9641:       fprintf(ficrescveij,"\n#****** ");
                   9642:       for(j=1;j<=cptcoveff;j++) {
1.218     brouard  9643:                                fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9644:                                fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9645:       }
                   9646:       fprintf(ficresstdeij,"******\n");
                   9647:       fprintf(ficrescveij,"******\n");
                   9648:       
                   9649:       fprintf(ficresvij,"\n#****** ");
                   9650:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9651:                                fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9652:       fprintf(ficresvij,"******\n");
                   9653:       
                   9654:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9655:       oldm=oldms;savm=savms;
                   9656:       printf(" cvevsij %d, ",k);
                   9657:       fprintf(ficlog, " cvevsij %d, ",k);
                   9658:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   9659:       printf(" end cvevsij \n ");
                   9660:       fprintf(ficlog, " end cvevsij \n ");
                   9661:       
                   9662:       /*
                   9663:        */
                   9664:       /* goto endfree; */
                   9665:       
                   9666:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9667:       pstamp(ficrest);
                   9668:       
                   9669:       
                   9670:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.219   ! brouard  9671:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
        !          9672:        cptcod= 0; /* To be deleted */
        !          9673:        printf("varevsij %d \n",vpopbased);
        !          9674:        fprintf(ficlog, "varevsij %d \n",vpopbased);
        !          9675:        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 */
        !          9676:        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 ");
        !          9677:        if(vpopbased==1)
        !          9678:          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);
        !          9679:        else
        !          9680:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
        !          9681:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
        !          9682:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
        !          9683:        fprintf(ficrest,"\n");
        !          9684:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
        !          9685:        epj=vector(1,nlstate+1);
        !          9686:        printf("Computing age specific period (stable) prevalences in each health state \n");
        !          9687:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
        !          9688:        for(age=bage; age <=fage ;age++){
        !          9689:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
        !          9690:          if (vpopbased==1) {
        !          9691:            if(mobilav ==0){
        !          9692:              for(i=1; i<=nlstate;i++)
        !          9693:                prlim[i][i]=probs[(int)age][i][k];
        !          9694:            }else{ /* mobilav */ 
        !          9695:              for(i=1; i<=nlstate;i++)
        !          9696:                prlim[i][i]=mobaverage[(int)age][i][k];
        !          9697:            }
        !          9698:          }
        !          9699:          
        !          9700:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
        !          9701:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
        !          9702:          /* printf(" age %4.0f ",age); */
        !          9703:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
        !          9704:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
        !          9705:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
        !          9706:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
        !          9707:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
        !          9708:            }
        !          9709:            epj[nlstate+1] +=epj[j];
        !          9710:          }
        !          9711:          /* printf(" age %4.0f \n",age); */
        !          9712:          
        !          9713:          for(i=1, vepp=0.;i <=nlstate;i++)
        !          9714:            for(j=1;j <=nlstate;j++)
        !          9715:              vepp += vareij[i][j][(int)age];
        !          9716:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
        !          9717:          for(j=1;j <=nlstate;j++){
        !          9718:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
        !          9719:          }
        !          9720:          fprintf(ficrest,"\n");
        !          9721:        }
1.208     brouard  9722:       } /* End vpopbased */
                   9723:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9724:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9725:       free_vector(epj,1,nlstate+1);
                   9726:       printf("done \n");fflush(stdout);
                   9727:       fprintf(ficlog,"done\n");fflush(ficlog);
                   9728:       
1.145     brouard  9729:       /*}*/
1.208     brouard  9730:     } /* End k */
1.126     brouard  9731:     free_vector(weight,1,n);
1.145     brouard  9732:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  9733:     free_imatrix(s,1,maxwav+1,1,n);
                   9734:     free_matrix(anint,1,maxwav,1,n); 
                   9735:     free_matrix(mint,1,maxwav,1,n);
                   9736:     free_ivector(cod,1,n);
                   9737:     free_ivector(tab,1,NCOVMAX);
                   9738:     fclose(ficresstdeij);
                   9739:     fclose(ficrescveij);
                   9740:     fclose(ficresvij);
                   9741:     fclose(ficrest);
1.208     brouard  9742:     printf("done Health expectancies\n");fflush(stdout);
                   9743:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  9744:     fclose(ficpar);
                   9745:   
                   9746:     /*------- Variance of period (stable) prevalence------*/   
                   9747: 
1.201     brouard  9748:     strcpy(fileresvpl,"VPL_");
                   9749:     strcat(fileresvpl,fileresu);
1.126     brouard  9750:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   9751:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   9752:       exit(0);
                   9753:     }
1.208     brouard  9754:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9755:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  9756: 
1.145     brouard  9757:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9758:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9759:           
                   9760:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   9761:        fprintf(ficresvpl,"\n#****** ");
1.218     brouard  9762:                        for(j=1;j<=cptcoveff;j++) 
                   9763:                                fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9764:                        fprintf(ficresvpl,"******\n");
                   9765:       
                   9766:                        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9767:                        oldm=oldms;savm=savms;
                   9768:                        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   9769:                        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  9770:       /*}*/
1.126     brouard  9771:     }
1.218     brouard  9772:                
1.126     brouard  9773:     fclose(ficresvpl);
1.208     brouard  9774:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   9775:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  9776: 
                   9777:     /*---------- End : free ----------------*/
1.219   ! brouard  9778:     if (mobilav!=0 ||mobilavproj !=0)
        !          9779:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
1.218     brouard  9780:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  9781:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  9782:  /* endfree:*/
1.141     brouard  9783:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  9784:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   9785:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9786:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9787:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9788:     free_matrix(covar,0,NCOVMAX,1,n);
                   9789:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  9790:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  9791:     /*free_vector(delti,1,npar);*/
                   9792:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9793:     free_matrix(agev,1,maxwav,1,imx);
                   9794:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   9795: 
1.145     brouard  9796:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  9797:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  9798:     free_ivector(Tvar,1,NCOVMAX);
                   9799:     free_ivector(Tprod,1,NCOVMAX);
                   9800:     free_ivector(Tvaraff,1,NCOVMAX);
                   9801:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  9802: 
                   9803:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  9804:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  9805:   fflush(fichtm);
                   9806:   fflush(ficgp);
                   9807:   
                   9808: 
                   9809:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  9810:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   9811:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
1.126     brouard  9812:   }else{
                   9813:     printf("End of Imach\n");
                   9814:     fprintf(ficlog,"End of Imach\n");
                   9815:   }
                   9816:   printf("See log file on %s\n",filelog);
                   9817:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  9818:   /*(void) gettimeofday(&end_time,&tzp);*/
                   9819:   rend_time = time(NULL);  
                   9820:   end_time = *localtime(&rend_time);
                   9821:   /* tml = *localtime(&end_time.tm_sec); */
                   9822:   strcpy(strtend,asctime(&end_time));
1.126     brouard  9823:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   9824:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  9825:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  9826: 
1.157     brouard  9827:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   9828:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   9829:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  9830:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   9831: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   9832:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9833:   fclose(fichtm);
                   9834:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9835:   fclose(fichtmcov);
                   9836:   fclose(ficgp);
                   9837:   fclose(ficlog);
                   9838:   /*------ End -----------*/
                   9839: 
                   9840: 
                   9841:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  9842: #ifdef WIN32
                   9843:    if (_chdir(pathcd) != 0)
                   9844:           printf("Can't move to directory %s!\n",path);
                   9845:    if(_getcwd(pathcd,MAXLINE) > 0)
                   9846: #else
1.126     brouard  9847:    if(chdir(pathcd) != 0)
1.184     brouard  9848:           printf("Can't move to directory %s!\n", path);
                   9849:    if (getcwd(pathcd, MAXLINE) > 0)
                   9850: #endif 
1.126     brouard  9851:     printf("Current directory %s!\n",pathcd);
                   9852:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   9853:   sprintf(plotcmd,"gnuplot");
1.157     brouard  9854: #ifdef _WIN32
1.126     brouard  9855:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   9856: #endif
                   9857:   if(!stat(plotcmd,&info)){
1.158     brouard  9858:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9859:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  9860:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  9861:     }else
                   9862:       strcpy(pplotcmd,plotcmd);
1.157     brouard  9863: #ifdef __unix
1.126     brouard  9864:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   9865:     if(!stat(plotcmd,&info)){
1.158     brouard  9866:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9867:     }else
                   9868:       strcpy(pplotcmd,plotcmd);
                   9869: #endif
                   9870:   }else
                   9871:     strcpy(pplotcmd,plotcmd);
                   9872:   
                   9873:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  9874:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9875: 
                   9876:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  9877:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  9878:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  9879:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  9880:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  9881:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  9882:   }
1.158     brouard  9883:   printf(" Successful, please wait...");
1.126     brouard  9884:   while (z[0] != 'q') {
                   9885:     /* chdir(path); */
1.154     brouard  9886:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  9887:     scanf("%s",z);
                   9888: /*     if (z[0] == 'c') system("./imach"); */
                   9889:     if (z[0] == 'e') {
1.158     brouard  9890: #ifdef __APPLE__
1.152     brouard  9891:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  9892: #elif __linux
                   9893:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  9894: #else
1.152     brouard  9895:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  9896: #endif
                   9897:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   9898:       system(pplotcmd);
1.126     brouard  9899:     }
                   9900:     else if (z[0] == 'g') system(plotcmd);
                   9901:     else if (z[0] == 'q') exit(0);
                   9902:   }
                   9903:   end:
                   9904:   while (z[0] != 'q') {
1.195     brouard  9905:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  9906:     scanf("%s",z);
                   9907:   }
                   9908: }

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