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

1.217   ! brouard     1: /* $Id: imach.c,v 1.216 2015/12/18 17:32:11 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.217   ! brouard     4:   Revision 1.216  2015/12/18 17:32:11  brouard
        !             5:   Summary: 0.98r4 Warning and status=-2
        !             6: 
        !             7:   Version 0.98r4 is now:
        !             8:    - displaying an error when status is -1, date of interview unknown and date of death known;
        !             9:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
        !            10:   Older changes concerning s=-2, dating from 2005 have been supersed.
        !            11: 
1.216     brouard    12:   Revision 1.215  2015/12/16 08:52:24  brouard
                     13:   Summary: 0.98r4 working
                     14: 
1.215     brouard    15:   Revision 1.214  2015/12/16 06:57:54  brouard
                     16:   Summary: temporary not working
                     17: 
1.214     brouard    18:   Revision 1.213  2015/12/11 18:22:17  brouard
                     19:   Summary: 0.98r4
                     20: 
1.213     brouard    21:   Revision 1.212  2015/11/21 12:47:24  brouard
                     22:   Summary: minor typo
                     23: 
1.212     brouard    24:   Revision 1.211  2015/11/21 12:41:11  brouard
                     25:   Summary: 0.98r3 with some graph of projected cross-sectional
                     26: 
                     27:   Author: Nicolas Brouard
                     28: 
1.211     brouard    29:   Revision 1.210  2015/11/18 17:41:20  brouard
                     30:   Summary: Start working on projected prevalences
                     31: 
1.210     brouard    32:   Revision 1.209  2015/11/17 22:12:03  brouard
                     33:   Summary: Adding ftolpl parameter
                     34:   Author: N Brouard
                     35: 
                     36:   We had difficulties to get smoothed confidence intervals. It was due
                     37:   to the period prevalence which wasn't computed accurately. The inner
                     38:   parameter ftolpl is now an outer parameter of the .imach parameter
                     39:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     40:   computation are long.
                     41: 
1.209     brouard    42:   Revision 1.208  2015/11/17 14:31:57  brouard
                     43:   Summary: temporary
                     44: 
1.208     brouard    45:   Revision 1.207  2015/10/27 17:36:57  brouard
                     46:   *** empty log message ***
                     47: 
1.207     brouard    48:   Revision 1.206  2015/10/24 07:14:11  brouard
                     49:   *** empty log message ***
                     50: 
1.206     brouard    51:   Revision 1.205  2015/10/23 15:50:53  brouard
                     52:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     53: 
1.205     brouard    54:   Revision 1.204  2015/10/01 16:20:26  brouard
                     55:   Summary: Some new graphs of contribution to likelihood
                     56: 
1.204     brouard    57:   Revision 1.203  2015/09/30 17:45:14  brouard
                     58:   Summary: looking at better estimation of the hessian
                     59: 
                     60:   Also a better criteria for convergence to the period prevalence And
                     61:   therefore adding the number of years needed to converge. (The
                     62:   prevalence in any alive state shold sum to one
                     63: 
1.203     brouard    64:   Revision 1.202  2015/09/22 19:45:16  brouard
                     65:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     66: 
1.202     brouard    67:   Revision 1.201  2015/09/15 17:34:58  brouard
                     68:   Summary: 0.98r0
                     69: 
                     70:   - Some new graphs like suvival functions
                     71:   - Some bugs fixed like model=1+age+V2.
                     72: 
1.201     brouard    73:   Revision 1.200  2015/09/09 16:53:55  brouard
                     74:   Summary: Big bug thanks to Flavia
                     75: 
                     76:   Even model=1+age+V2. did not work anymore
                     77: 
1.200     brouard    78:   Revision 1.199  2015/09/07 14:09:23  brouard
                     79:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     80: 
1.199     brouard    81:   Revision 1.198  2015/09/03 07:14:39  brouard
                     82:   Summary: 0.98q5 Flavia
                     83: 
1.198     brouard    84:   Revision 1.197  2015/09/01 18:24:39  brouard
                     85:   *** empty log message ***
                     86: 
1.197     brouard    87:   Revision 1.196  2015/08/18 23:17:52  brouard
                     88:   Summary: 0.98q5
                     89: 
1.196     brouard    90:   Revision 1.195  2015/08/18 16:28:39  brouard
                     91:   Summary: Adding a hack for testing purpose
                     92: 
                     93:   After reading the title, ftol and model lines, if the comment line has
                     94:   a q, starting with #q, the answer at the end of the run is quit. It
                     95:   permits to run test files in batch with ctest. The former workaround was
                     96:   $ echo q | imach foo.imach
                     97: 
1.195     brouard    98:   Revision 1.194  2015/08/18 13:32:00  brouard
                     99:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    100: 
1.194     brouard   101:   Revision 1.193  2015/08/04 07:17:42  brouard
                    102:   Summary: 0.98q4
                    103: 
1.193     brouard   104:   Revision 1.192  2015/07/16 16:49:02  brouard
                    105:   Summary: Fixing some outputs
                    106: 
1.192     brouard   107:   Revision 1.191  2015/07/14 10:00:33  brouard
                    108:   Summary: Some fixes
                    109: 
1.191     brouard   110:   Revision 1.190  2015/05/05 08:51:13  brouard
                    111:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    112: 
                    113:   Fix 1+age+.
                    114: 
1.190     brouard   115:   Revision 1.189  2015/04/30 14:45:16  brouard
                    116:   Summary: 0.98q2
                    117: 
1.189     brouard   118:   Revision 1.188  2015/04/30 08:27:53  brouard
                    119:   *** empty log message ***
                    120: 
1.188     brouard   121:   Revision 1.187  2015/04/29 09:11:15  brouard
                    122:   *** empty log message ***
                    123: 
1.187     brouard   124:   Revision 1.186  2015/04/23 12:01:52  brouard
                    125:   Summary: V1*age is working now, version 0.98q1
                    126: 
                    127:   Some codes had been disabled in order to simplify and Vn*age was
                    128:   working in the optimization phase, ie, giving correct MLE parameters,
                    129:   but, as usual, outputs were not correct and program core dumped.
                    130: 
1.186     brouard   131:   Revision 1.185  2015/03/11 13:26:42  brouard
                    132:   Summary: Inclusion of compile and links command line for Intel Compiler
                    133: 
1.185     brouard   134:   Revision 1.184  2015/03/11 11:52:39  brouard
                    135:   Summary: Back from Windows 8. Intel Compiler
                    136: 
1.184     brouard   137:   Revision 1.183  2015/03/10 20:34:32  brouard
                    138:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    139: 
                    140:   We use directest instead of original Powell test; probably no
                    141:   incidence on the results, but better justifications;
                    142:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    143:   wrong results.
                    144: 
1.183     brouard   145:   Revision 1.182  2015/02/12 08:19:57  brouard
                    146:   Summary: Trying to keep directest which seems simpler and more general
                    147:   Author: Nicolas Brouard
                    148: 
1.182     brouard   149:   Revision 1.181  2015/02/11 23:22:24  brouard
                    150:   Summary: Comments on Powell added
                    151: 
                    152:   Author:
                    153: 
1.181     brouard   154:   Revision 1.180  2015/02/11 17:33:45  brouard
                    155:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    156: 
1.180     brouard   157:   Revision 1.179  2015/01/04 09:57:06  brouard
                    158:   Summary: back to OS/X
                    159: 
1.179     brouard   160:   Revision 1.178  2015/01/04 09:35:48  brouard
                    161:   *** empty log message ***
                    162: 
1.178     brouard   163:   Revision 1.177  2015/01/03 18:40:56  brouard
                    164:   Summary: Still testing ilc32 on OSX
                    165: 
1.177     brouard   166:   Revision 1.176  2015/01/03 16:45:04  brouard
                    167:   *** empty log message ***
                    168: 
1.176     brouard   169:   Revision 1.175  2015/01/03 16:33:42  brouard
                    170:   *** empty log message ***
                    171: 
1.175     brouard   172:   Revision 1.174  2015/01/03 16:15:49  brouard
                    173:   Summary: Still in cross-compilation
                    174: 
1.174     brouard   175:   Revision 1.173  2015/01/03 12:06:26  brouard
                    176:   Summary: trying to detect cross-compilation
                    177: 
1.173     brouard   178:   Revision 1.172  2014/12/27 12:07:47  brouard
                    179:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    180: 
1.172     brouard   181:   Revision 1.171  2014/12/23 13:26:59  brouard
                    182:   Summary: Back from Visual C
                    183: 
                    184:   Still problem with utsname.h on Windows
                    185: 
1.171     brouard   186:   Revision 1.170  2014/12/23 11:17:12  brouard
                    187:   Summary: Cleaning some \%% back to %%
                    188: 
                    189:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    190: 
1.170     brouard   191:   Revision 1.169  2014/12/22 23:08:31  brouard
                    192:   Summary: 0.98p
                    193: 
                    194:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    195: 
1.169     brouard   196:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   197:   Summary: update
1.169     brouard   198: 
1.168     brouard   199:   Revision 1.167  2014/12/22 13:50:56  brouard
                    200:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    201: 
                    202:   Testing on Linux 64
                    203: 
1.167     brouard   204:   Revision 1.166  2014/12/22 11:40:47  brouard
                    205:   *** empty log message ***
                    206: 
1.166     brouard   207:   Revision 1.165  2014/12/16 11:20:36  brouard
                    208:   Summary: After compiling on Visual C
                    209: 
                    210:   * imach.c (Module): Merging 1.61 to 1.162
                    211: 
1.165     brouard   212:   Revision 1.164  2014/12/16 10:52:11  brouard
                    213:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    214: 
                    215:   * imach.c (Module): Merging 1.61 to 1.162
                    216: 
1.164     brouard   217:   Revision 1.163  2014/12/16 10:30:11  brouard
                    218:   * imach.c (Module): Merging 1.61 to 1.162
                    219: 
1.163     brouard   220:   Revision 1.162  2014/09/25 11:43:39  brouard
                    221:   Summary: temporary backup 0.99!
                    222: 
1.162     brouard   223:   Revision 1.1  2014/09/16 11:06:58  brouard
                    224:   Summary: With some code (wrong) for nlopt
                    225: 
                    226:   Author:
                    227: 
                    228:   Revision 1.161  2014/09/15 20:41:41  brouard
                    229:   Summary: Problem with macro SQR on Intel compiler
                    230: 
1.161     brouard   231:   Revision 1.160  2014/09/02 09:24:05  brouard
                    232:   *** empty log message ***
                    233: 
1.160     brouard   234:   Revision 1.159  2014/09/01 10:34:10  brouard
                    235:   Summary: WIN32
                    236:   Author: Brouard
                    237: 
1.159     brouard   238:   Revision 1.158  2014/08/27 17:11:51  brouard
                    239:   *** empty log message ***
                    240: 
1.158     brouard   241:   Revision 1.157  2014/08/27 16:26:55  brouard
                    242:   Summary: Preparing windows Visual studio version
                    243:   Author: Brouard
                    244: 
                    245:   In order to compile on Visual studio, time.h is now correct and time_t
                    246:   and tm struct should be used. difftime should be used but sometimes I
                    247:   just make the differences in raw time format (time(&now).
                    248:   Trying to suppress #ifdef LINUX
                    249:   Add xdg-open for __linux in order to open default browser.
                    250: 
1.157     brouard   251:   Revision 1.156  2014/08/25 20:10:10  brouard
                    252:   *** empty log message ***
                    253: 
1.156     brouard   254:   Revision 1.155  2014/08/25 18:32:34  brouard
                    255:   Summary: New compile, minor changes
                    256:   Author: Brouard
                    257: 
1.155     brouard   258:   Revision 1.154  2014/06/20 17:32:08  brouard
                    259:   Summary: Outputs now all graphs of convergence to period prevalence
                    260: 
1.154     brouard   261:   Revision 1.153  2014/06/20 16:45:46  brouard
                    262:   Summary: If 3 live state, convergence to period prevalence on same graph
                    263:   Author: Brouard
                    264: 
1.153     brouard   265:   Revision 1.152  2014/06/18 17:54:09  brouard
                    266:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    267: 
1.152     brouard   268:   Revision 1.151  2014/06/18 16:43:30  brouard
                    269:   *** empty log message ***
                    270: 
1.151     brouard   271:   Revision 1.150  2014/06/18 16:42:35  brouard
                    272:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    273:   Author: brouard
                    274: 
1.150     brouard   275:   Revision 1.149  2014/06/18 15:51:14  brouard
                    276:   Summary: Some fixes in parameter files errors
                    277:   Author: Nicolas Brouard
                    278: 
1.149     brouard   279:   Revision 1.148  2014/06/17 17:38:48  brouard
                    280:   Summary: Nothing new
                    281:   Author: Brouard
                    282: 
                    283:   Just a new packaging for OS/X version 0.98nS
                    284: 
1.148     brouard   285:   Revision 1.147  2014/06/16 10:33:11  brouard
                    286:   *** empty log message ***
                    287: 
1.147     brouard   288:   Revision 1.146  2014/06/16 10:20:28  brouard
                    289:   Summary: Merge
                    290:   Author: Brouard
                    291: 
                    292:   Merge, before building revised version.
                    293: 
1.146     brouard   294:   Revision 1.145  2014/06/10 21:23:15  brouard
                    295:   Summary: Debugging with valgrind
                    296:   Author: Nicolas Brouard
                    297: 
                    298:   Lot of changes in order to output the results with some covariates
                    299:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    300:   improve the code.
                    301:   No more memory valgrind error but a lot has to be done in order to
                    302:   continue the work of splitting the code into subroutines.
                    303:   Also, decodemodel has been improved. Tricode is still not
                    304:   optimal. nbcode should be improved. Documentation has been added in
                    305:   the source code.
                    306: 
1.144     brouard   307:   Revision 1.143  2014/01/26 09:45:38  brouard
                    308:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    309: 
                    310:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    311:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    312: 
1.143     brouard   313:   Revision 1.142  2014/01/26 03:57:36  brouard
                    314:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    315: 
                    316:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    317: 
1.142     brouard   318:   Revision 1.141  2014/01/26 02:42:01  brouard
                    319:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    320: 
1.141     brouard   321:   Revision 1.140  2011/09/02 10:37:54  brouard
                    322:   Summary: times.h is ok with mingw32 now.
                    323: 
1.140     brouard   324:   Revision 1.139  2010/06/14 07:50:17  brouard
                    325:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    326:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    327: 
1.139     brouard   328:   Revision 1.138  2010/04/30 18:19:40  brouard
                    329:   *** empty log message ***
                    330: 
1.138     brouard   331:   Revision 1.137  2010/04/29 18:11:38  brouard
                    332:   (Module): Checking covariates for more complex models
                    333:   than V1+V2. A lot of change to be done. Unstable.
                    334: 
1.137     brouard   335:   Revision 1.136  2010/04/26 20:30:53  brouard
                    336:   (Module): merging some libgsl code. Fixing computation
                    337:   of likelione (using inter/intrapolation if mle = 0) in order to
                    338:   get same likelihood as if mle=1.
                    339:   Some cleaning of code and comments added.
                    340: 
1.136     brouard   341:   Revision 1.135  2009/10/29 15:33:14  brouard
                    342:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    343: 
1.135     brouard   344:   Revision 1.134  2009/10/29 13:18:53  brouard
                    345:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    346: 
1.134     brouard   347:   Revision 1.133  2009/07/06 10:21:25  brouard
                    348:   just nforces
                    349: 
1.133     brouard   350:   Revision 1.132  2009/07/06 08:22:05  brouard
                    351:   Many tings
                    352: 
1.132     brouard   353:   Revision 1.131  2009/06/20 16:22:47  brouard
                    354:   Some dimensions resccaled
                    355: 
1.131     brouard   356:   Revision 1.130  2009/05/26 06:44:34  brouard
                    357:   (Module): Max Covariate is now set to 20 instead of 8. A
                    358:   lot of cleaning with variables initialized to 0. Trying to make
                    359:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    360: 
1.130     brouard   361:   Revision 1.129  2007/08/31 13:49:27  lievre
                    362:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    363: 
1.129     lievre    364:   Revision 1.128  2006/06/30 13:02:05  brouard
                    365:   (Module): Clarifications on computing e.j
                    366: 
1.128     brouard   367:   Revision 1.127  2006/04/28 18:11:50  brouard
                    368:   (Module): Yes the sum of survivors was wrong since
                    369:   imach-114 because nhstepm was no more computed in the age
                    370:   loop. Now we define nhstepma in the age loop.
                    371:   (Module): In order to speed up (in case of numerous covariates) we
                    372:   compute health expectancies (without variances) in a first step
                    373:   and then all the health expectancies with variances or standard
                    374:   deviation (needs data from the Hessian matrices) which slows the
                    375:   computation.
                    376:   In the future we should be able to stop the program is only health
                    377:   expectancies and graph are needed without standard deviations.
                    378: 
1.127     brouard   379:   Revision 1.126  2006/04/28 17:23:28  brouard
                    380:   (Module): Yes the sum of survivors was wrong since
                    381:   imach-114 because nhstepm was no more computed in the age
                    382:   loop. Now we define nhstepma in the age loop.
                    383:   Version 0.98h
                    384: 
1.126     brouard   385:   Revision 1.125  2006/04/04 15:20:31  lievre
                    386:   Errors in calculation of health expectancies. Age was not initialized.
                    387:   Forecasting file added.
                    388: 
                    389:   Revision 1.124  2006/03/22 17:13:53  lievre
                    390:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    391:   The log-likelihood is printed in the log file
                    392: 
                    393:   Revision 1.123  2006/03/20 10:52:43  brouard
                    394:   * imach.c (Module): <title> changed, corresponds to .htm file
                    395:   name. <head> headers where missing.
                    396: 
                    397:   * imach.c (Module): Weights can have a decimal point as for
                    398:   English (a comma might work with a correct LC_NUMERIC environment,
                    399:   otherwise the weight is truncated).
                    400:   Modification of warning when the covariates values are not 0 or
                    401:   1.
                    402:   Version 0.98g
                    403: 
                    404:   Revision 1.122  2006/03/20 09:45:41  brouard
                    405:   (Module): Weights can have a decimal point as for
                    406:   English (a comma might work with a correct LC_NUMERIC environment,
                    407:   otherwise the weight is truncated).
                    408:   Modification of warning when the covariates values are not 0 or
                    409:   1.
                    410:   Version 0.98g
                    411: 
                    412:   Revision 1.121  2006/03/16 17:45:01  lievre
                    413:   * imach.c (Module): Comments concerning covariates added
                    414: 
                    415:   * imach.c (Module): refinements in the computation of lli if
                    416:   status=-2 in order to have more reliable computation if stepm is
                    417:   not 1 month. Version 0.98f
                    418: 
                    419:   Revision 1.120  2006/03/16 15:10:38  lievre
                    420:   (Module): refinements in the computation of lli if
                    421:   status=-2 in order to have more reliable computation if stepm is
                    422:   not 1 month. Version 0.98f
                    423: 
                    424:   Revision 1.119  2006/03/15 17:42:26  brouard
                    425:   (Module): Bug if status = -2, the loglikelihood was
                    426:   computed as likelihood omitting the logarithm. Version O.98e
                    427: 
                    428:   Revision 1.118  2006/03/14 18:20:07  brouard
                    429:   (Module): varevsij Comments added explaining the second
                    430:   table of variances if popbased=1 .
                    431:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    432:   (Module): Function pstamp added
                    433:   (Module): Version 0.98d
                    434: 
                    435:   Revision 1.117  2006/03/14 17:16:22  brouard
                    436:   (Module): varevsij Comments added explaining the second
                    437:   table of variances if popbased=1 .
                    438:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    439:   (Module): Function pstamp added
                    440:   (Module): Version 0.98d
                    441: 
                    442:   Revision 1.116  2006/03/06 10:29:27  brouard
                    443:   (Module): Variance-covariance wrong links and
                    444:   varian-covariance of ej. is needed (Saito).
                    445: 
                    446:   Revision 1.115  2006/02/27 12:17:45  brouard
                    447:   (Module): One freematrix added in mlikeli! 0.98c
                    448: 
                    449:   Revision 1.114  2006/02/26 12:57:58  brouard
                    450:   (Module): Some improvements in processing parameter
                    451:   filename with strsep.
                    452: 
                    453:   Revision 1.113  2006/02/24 14:20:24  brouard
                    454:   (Module): Memory leaks checks with valgrind and:
                    455:   datafile was not closed, some imatrix were not freed and on matrix
                    456:   allocation too.
                    457: 
                    458:   Revision 1.112  2006/01/30 09:55:26  brouard
                    459:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    460: 
                    461:   Revision 1.111  2006/01/25 20:38:18  brouard
                    462:   (Module): Lots of cleaning and bugs added (Gompertz)
                    463:   (Module): Comments can be added in data file. Missing date values
                    464:   can be a simple dot '.'.
                    465: 
                    466:   Revision 1.110  2006/01/25 00:51:50  brouard
                    467:   (Module): Lots of cleaning and bugs added (Gompertz)
                    468: 
                    469:   Revision 1.109  2006/01/24 19:37:15  brouard
                    470:   (Module): Comments (lines starting with a #) are allowed in data.
                    471: 
                    472:   Revision 1.108  2006/01/19 18:05:42  lievre
                    473:   Gnuplot problem appeared...
                    474:   To be fixed
                    475: 
                    476:   Revision 1.107  2006/01/19 16:20:37  brouard
                    477:   Test existence of gnuplot in imach path
                    478: 
                    479:   Revision 1.106  2006/01/19 13:24:36  brouard
                    480:   Some cleaning and links added in html output
                    481: 
                    482:   Revision 1.105  2006/01/05 20:23:19  lievre
                    483:   *** empty log message ***
                    484: 
                    485:   Revision 1.104  2005/09/30 16:11:43  lievre
                    486:   (Module): sump fixed, loop imx fixed, and simplifications.
                    487:   (Module): If the status is missing at the last wave but we know
                    488:   that the person is alive, then we can code his/her status as -2
                    489:   (instead of missing=-1 in earlier versions) and his/her
                    490:   contributions to the likelihood is 1 - Prob of dying from last
                    491:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    492:   the healthy state at last known wave). Version is 0.98
                    493: 
                    494:   Revision 1.103  2005/09/30 15:54:49  lievre
                    495:   (Module): sump fixed, loop imx fixed, and simplifications.
                    496: 
                    497:   Revision 1.102  2004/09/15 17:31:30  brouard
                    498:   Add the possibility to read data file including tab characters.
                    499: 
                    500:   Revision 1.101  2004/09/15 10:38:38  brouard
                    501:   Fix on curr_time
                    502: 
                    503:   Revision 1.100  2004/07/12 18:29:06  brouard
                    504:   Add version for Mac OS X. Just define UNIX in Makefile
                    505: 
                    506:   Revision 1.99  2004/06/05 08:57:40  brouard
                    507:   *** empty log message ***
                    508: 
                    509:   Revision 1.98  2004/05/16 15:05:56  brouard
                    510:   New version 0.97 . First attempt to estimate force of mortality
                    511:   directly from the data i.e. without the need of knowing the health
                    512:   state at each age, but using a Gompertz model: log u =a + b*age .
                    513:   This is the basic analysis of mortality and should be done before any
                    514:   other analysis, in order to test if the mortality estimated from the
                    515:   cross-longitudinal survey is different from the mortality estimated
                    516:   from other sources like vital statistic data.
                    517: 
                    518:   The same imach parameter file can be used but the option for mle should be -3.
                    519: 
1.133     brouard   520:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   521:   former routines in order to include the new code within the former code.
                    522: 
                    523:   The output is very simple: only an estimate of the intercept and of
                    524:   the slope with 95% confident intervals.
                    525: 
                    526:   Current limitations:
                    527:   A) Even if you enter covariates, i.e. with the
                    528:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    529:   B) There is no computation of Life Expectancy nor Life Table.
                    530: 
                    531:   Revision 1.97  2004/02/20 13:25:42  lievre
                    532:   Version 0.96d. Population forecasting command line is (temporarily)
                    533:   suppressed.
                    534: 
                    535:   Revision 1.96  2003/07/15 15:38:55  brouard
                    536:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    537:   rewritten within the same printf. Workaround: many printfs.
                    538: 
                    539:   Revision 1.95  2003/07/08 07:54:34  brouard
                    540:   * imach.c (Repository):
                    541:   (Repository): Using imachwizard code to output a more meaningful covariance
                    542:   matrix (cov(a12,c31) instead of numbers.
                    543: 
                    544:   Revision 1.94  2003/06/27 13:00:02  brouard
                    545:   Just cleaning
                    546: 
                    547:   Revision 1.93  2003/06/25 16:33:55  brouard
                    548:   (Module): On windows (cygwin) function asctime_r doesn't
                    549:   exist so I changed back to asctime which exists.
                    550:   (Module): Version 0.96b
                    551: 
                    552:   Revision 1.92  2003/06/25 16:30:45  brouard
                    553:   (Module): On windows (cygwin) function asctime_r doesn't
                    554:   exist so I changed back to asctime which exists.
                    555: 
                    556:   Revision 1.91  2003/06/25 15:30:29  brouard
                    557:   * imach.c (Repository): Duplicated warning errors corrected.
                    558:   (Repository): Elapsed time after each iteration is now output. It
                    559:   helps to forecast when convergence will be reached. Elapsed time
                    560:   is stamped in powell.  We created a new html file for the graphs
                    561:   concerning matrix of covariance. It has extension -cov.htm.
                    562: 
                    563:   Revision 1.90  2003/06/24 12:34:15  brouard
                    564:   (Module): Some bugs corrected for windows. Also, when
                    565:   mle=-1 a template is output in file "or"mypar.txt with the design
                    566:   of the covariance matrix to be input.
                    567: 
                    568:   Revision 1.89  2003/06/24 12:30:52  brouard
                    569:   (Module): Some bugs corrected for windows. Also, when
                    570:   mle=-1 a template is output in file "or"mypar.txt with the design
                    571:   of the covariance matrix to be input.
                    572: 
                    573:   Revision 1.88  2003/06/23 17:54:56  brouard
                    574:   * 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.
                    575: 
                    576:   Revision 1.87  2003/06/18 12:26:01  brouard
                    577:   Version 0.96
                    578: 
                    579:   Revision 1.86  2003/06/17 20:04:08  brouard
                    580:   (Module): Change position of html and gnuplot routines and added
                    581:   routine fileappend.
                    582: 
                    583:   Revision 1.85  2003/06/17 13:12:43  brouard
                    584:   * imach.c (Repository): Check when date of death was earlier that
                    585:   current date of interview. It may happen when the death was just
                    586:   prior to the death. In this case, dh was negative and likelihood
                    587:   was wrong (infinity). We still send an "Error" but patch by
                    588:   assuming that the date of death was just one stepm after the
                    589:   interview.
                    590:   (Repository): Because some people have very long ID (first column)
                    591:   we changed int to long in num[] and we added a new lvector for
                    592:   memory allocation. But we also truncated to 8 characters (left
                    593:   truncation)
                    594:   (Repository): No more line truncation errors.
                    595: 
                    596:   Revision 1.84  2003/06/13 21:44:43  brouard
                    597:   * imach.c (Repository): Replace "freqsummary" at a correct
                    598:   place. It differs from routine "prevalence" which may be called
                    599:   many times. Probs is memory consuming and must be used with
                    600:   parcimony.
                    601:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    602: 
                    603:   Revision 1.83  2003/06/10 13:39:11  lievre
                    604:   *** empty log message ***
                    605: 
                    606:   Revision 1.82  2003/06/05 15:57:20  brouard
                    607:   Add log in  imach.c and  fullversion number is now printed.
                    608: 
                    609: */
                    610: /*
                    611:    Interpolated Markov Chain
                    612: 
                    613:   Short summary of the programme:
                    614:   
                    615:   This program computes Healthy Life Expectancies from
                    616:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    617:   first survey ("cross") where individuals from different ages are
                    618:   interviewed on their health status or degree of disability (in the
                    619:   case of a health survey which is our main interest) -2- at least a
                    620:   second wave of interviews ("longitudinal") which measure each change
                    621:   (if any) in individual health status.  Health expectancies are
                    622:   computed from the time spent in each health state according to a
                    623:   model. More health states you consider, more time is necessary to reach the
                    624:   Maximum Likelihood of the parameters involved in the model.  The
                    625:   simplest model is the multinomial logistic model where pij is the
                    626:   probability to be observed in state j at the second wave
                    627:   conditional to be observed in state i at the first wave. Therefore
                    628:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    629:   'age' is age and 'sex' is a covariate. If you want to have a more
                    630:   complex model than "constant and age", you should modify the program
                    631:   where the markup *Covariates have to be included here again* invites
                    632:   you to do it.  More covariates you add, slower the
                    633:   convergence.
                    634: 
                    635:   The advantage of this computer programme, compared to a simple
                    636:   multinomial logistic model, is clear when the delay between waves is not
                    637:   identical for each individual. Also, if a individual missed an
                    638:   intermediate interview, the information is lost, but taken into
                    639:   account using an interpolation or extrapolation.  
                    640: 
                    641:   hPijx is the probability to be observed in state i at age x+h
                    642:   conditional to the observed state i at age x. The delay 'h' can be
                    643:   split into an exact number (nh*stepm) of unobserved intermediate
                    644:   states. This elementary transition (by month, quarter,
                    645:   semester or year) is modelled as a multinomial logistic.  The hPx
                    646:   matrix is simply the matrix product of nh*stepm elementary matrices
                    647:   and the contribution of each individual to the likelihood is simply
                    648:   hPijx.
                    649: 
                    650:   Also this programme outputs the covariance matrix of the parameters but also
                    651:   of the life expectancies. It also computes the period (stable) prevalence. 
                    652:   
1.133     brouard   653:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    654:            Institut national d'études démographiques, Paris.
1.126     brouard   655:   This software have been partly granted by Euro-REVES, a concerted action
                    656:   from the European Union.
                    657:   It is copyrighted identically to a GNU software product, ie programme and
                    658:   software can be distributed freely for non commercial use. Latest version
                    659:   can be accessed at http://euroreves.ined.fr/imach .
                    660: 
                    661:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    662:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    663:   
                    664:   **********************************************************************/
                    665: /*
                    666:   main
                    667:   read parameterfile
                    668:   read datafile
                    669:   concatwav
                    670:   freqsummary
                    671:   if (mle >= 1)
                    672:     mlikeli
                    673:   print results files
                    674:   if mle==1 
                    675:      computes hessian
                    676:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    677:       begin-prev-date,...
                    678:   open gnuplot file
                    679:   open html file
1.145     brouard   680:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    681:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    682:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    683:     freexexit2 possible for memory heap.
                    684: 
                    685:   h Pij x                         | pij_nom  ficrestpij
                    686:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    687:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    688:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    689: 
                    690:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    691:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    692:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    693:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    694:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    695: 
1.126     brouard   696:   forecasting if prevfcast==1 prevforecast call prevalence()
                    697:   health expectancies
                    698:   Variance-covariance of DFLE
                    699:   prevalence()
                    700:    movingaverage()
                    701:   varevsij() 
                    702:   if popbased==1 varevsij(,popbased)
                    703:   total life expectancies
                    704:   Variance of period (stable) prevalence
                    705:  end
                    706: */
                    707: 
1.187     brouard   708: /* #define DEBUG */
                    709: /* #define DEBUGBRENT */
1.203     brouard   710: /* #define DEBUGLINMIN */
                    711: /* #define DEBUGHESS */
                    712: #define DEBUGHESSIJ
                    713: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   714: #define POWELL /* Instead of NLOPT */
1.192     brouard   715: #define POWELLF1F3 /* Skip test */
1.186     brouard   716: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    717: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   718: 
                    719: #include <math.h>
                    720: #include <stdio.h>
                    721: #include <stdlib.h>
                    722: #include <string.h>
1.159     brouard   723: 
                    724: #ifdef _WIN32
                    725: #include <io.h>
1.172     brouard   726: #include <windows.h>
                    727: #include <tchar.h>
1.159     brouard   728: #else
1.126     brouard   729: #include <unistd.h>
1.159     brouard   730: #endif
1.126     brouard   731: 
                    732: #include <limits.h>
                    733: #include <sys/types.h>
1.171     brouard   734: 
                    735: #if defined(__GNUC__)
                    736: #include <sys/utsname.h> /* Doesn't work on Windows */
                    737: #endif
                    738: 
1.126     brouard   739: #include <sys/stat.h>
                    740: #include <errno.h>
1.159     brouard   741: /* extern int errno; */
1.126     brouard   742: 
1.157     brouard   743: /* #ifdef LINUX */
                    744: /* #include <time.h> */
                    745: /* #include "timeval.h" */
                    746: /* #else */
                    747: /* #include <sys/time.h> */
                    748: /* #endif */
                    749: 
1.126     brouard   750: #include <time.h>
                    751: 
1.136     brouard   752: #ifdef GSL
                    753: #include <gsl/gsl_errno.h>
                    754: #include <gsl/gsl_multimin.h>
                    755: #endif
                    756: 
1.167     brouard   757: 
1.162     brouard   758: #ifdef NLOPT
                    759: #include <nlopt.h>
                    760: typedef struct {
                    761:   double (* function)(double [] );
                    762: } myfunc_data ;
                    763: #endif
                    764: 
1.126     brouard   765: /* #include <libintl.h> */
                    766: /* #define _(String) gettext (String) */
                    767: 
1.141     brouard   768: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   769: 
                    770: #define GNUPLOTPROGRAM "gnuplot"
                    771: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    772: #define FILENAMELENGTH 132
                    773: 
                    774: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    775: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    776: 
1.144     brouard   777: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    778: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   779: 
                    780: #define NINTERVMAX 8
1.144     brouard   781: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    782: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    783: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   784: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   785: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    786: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   787: #define MAXN 20000
1.144     brouard   788: #define YEARM 12. /**< Number of months per year */
1.126     brouard   789: #define AGESUP 130
                    790: #define AGEBASE 40
1.194     brouard   791: #define AGEOVERFLOW 1.e20
1.164     brouard   792: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   793: #ifdef _WIN32
                    794: #define DIRSEPARATOR '\\'
                    795: #define CHARSEPARATOR "\\"
                    796: #define ODIRSEPARATOR '/'
                    797: #else
1.126     brouard   798: #define DIRSEPARATOR '/'
                    799: #define CHARSEPARATOR "/"
                    800: #define ODIRSEPARATOR '\\'
                    801: #endif
                    802: 
1.217   ! brouard   803: /* $Id: imach.c,v 1.216 2015/12/18 17:32:11 brouard Exp $ */
1.126     brouard   804: /* $State: Exp $ */
1.196     brouard   805: #include "version.h"
                    806: char version[]=__IMACH_VERSION__;
1.204     brouard   807: 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.217   ! brouard   808: char fullversion[]="$Revision: 1.216 $ $Date: 2015/12/18 17:32:11 $"; 
1.126     brouard   809: char strstart[80];
                    810: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   811: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   812: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   813: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    814: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    815: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    816: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    817: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    818: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    819: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    820: int cptcov=0; /* Working variable */
1.126     brouard   821: int npar=NPARMAX;
                    822: int nlstate=2; /* Number of live states */
                    823: int ndeath=1; /* Number of dead states */
1.130     brouard   824: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   825: int popbased=0;
                    826: 
                    827: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   828: int maxwav=0; /* Maxim number of waves */
                    829: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    830: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    831: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   832:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   833: int mle=1, weightopt=0;
1.126     brouard   834: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    835: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    836: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    837:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   838: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   839: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   840: double **matprod2(); /* test */
1.126     brouard   841: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    842: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   843: /*FILE *fic ; */ /* Used in readdata only */
1.217   ! brouard   844: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   845: FILE *ficlog, *ficrespow;
1.130     brouard   846: int globpr=0; /* Global variable for printing or not */
1.126     brouard   847: double fretone; /* Only one call to likelihood */
1.130     brouard   848: long ipmx=0; /* Number of contributions */
1.126     brouard   849: double sw; /* Sum of weights */
                    850: char filerespow[FILENAMELENGTH];
                    851: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    852: FILE *ficresilk;
                    853: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    854: FILE *ficresprobmorprev;
                    855: FILE *fichtm, *fichtmcov; /* Html File */
                    856: FILE *ficreseij;
                    857: char filerese[FILENAMELENGTH];
                    858: FILE *ficresstdeij;
                    859: char fileresstde[FILENAMELENGTH];
                    860: FILE *ficrescveij;
                    861: char filerescve[FILENAMELENGTH];
                    862: FILE  *ficresvij;
                    863: char fileresv[FILENAMELENGTH];
                    864: FILE  *ficresvpl;
                    865: char fileresvpl[FILENAMELENGTH];
                    866: char title[MAXLINE];
1.217   ! brouard   867: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   868: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    869: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    870: char command[FILENAMELENGTH];
                    871: int  outcmd=0;
                    872: 
1.217   ! brouard   873: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   874: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   875: char filelog[FILENAMELENGTH]; /* Log file */
                    876: char filerest[FILENAMELENGTH];
                    877: char fileregp[FILENAMELENGTH];
                    878: char popfile[FILENAMELENGTH];
                    879: 
                    880: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    881: 
1.157     brouard   882: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    883: /* struct timezone tzp; */
                    884: /* extern int gettimeofday(); */
                    885: struct tm tml, *gmtime(), *localtime();
                    886: 
                    887: extern time_t time();
                    888: 
                    889: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    890: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    891: struct tm tm;
                    892: 
1.126     brouard   893: char strcurr[80], strfor[80];
                    894: 
                    895: char *endptr;
                    896: long lval;
                    897: double dval;
                    898: 
                    899: #define NR_END 1
                    900: #define FREE_ARG char*
                    901: #define FTOL 1.0e-10
                    902: 
                    903: #define NRANSI 
                    904: #define ITMAX 200 
                    905: 
                    906: #define TOL 2.0e-4 
                    907: 
                    908: #define CGOLD 0.3819660 
                    909: #define ZEPS 1.0e-10 
                    910: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    911: 
                    912: #define GOLD 1.618034 
                    913: #define GLIMIT 100.0 
                    914: #define TINY 1.0e-20 
                    915: 
                    916: static double maxarg1,maxarg2;
                    917: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    918: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    919:   
                    920: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    921: #define rint(a) floor(a+0.5)
1.166     brouard   922: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   923: #define mytinydouble 1.0e-16
1.166     brouard   924: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    925: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    926: /* static double dsqrarg; */
                    927: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   928: static double sqrarg;
                    929: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    930: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    931: int agegomp= AGEGOMP;
                    932: 
                    933: int imx; 
                    934: int stepm=1;
                    935: /* Stepm, step in month: minimum step interpolation*/
                    936: 
                    937: int estepm;
                    938: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    939: 
                    940: int m,nb;
                    941: long *num;
1.197     brouard   942: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   943: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    944:                   covariate for which somebody answered excluding 
                    945:                   undefined. Usually 2: 0 and 1. */
                    946: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    947:                             covariate for which somebody answered including 
                    948:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   949: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    950: double **pmmij, ***probs;
                    951: double *ageexmed,*agecens;
                    952: double dateintmean=0;
                    953: 
                    954: double *weight;
                    955: int **s; /* Status */
1.141     brouard   956: double *agedc;
1.145     brouard   957: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   958:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   959:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   960: double  idx; 
                    961: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   962: int *Tage;
1.145     brouard   963: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   964: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   965: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   966: double *lsurv, *lpop, *tpop;
                    967: 
1.143     brouard   968: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    969: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   970: 
                    971: /**************** split *************************/
                    972: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    973: {
                    974:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    975:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    976:   */ 
                    977:   char *ss;                            /* pointer */
1.186     brouard   978:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   979: 
                    980:   l1 = strlen(path );                  /* length of path */
                    981:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    982:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    983:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    984:     strcpy( name, path );              /* we got the fullname name because no directory */
                    985:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    986:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    987:     /* get current working directory */
                    988:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   989: #ifdef WIN32
                    990:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    991: #else
                    992:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    993: #endif
1.126     brouard   994:       return( GLOCK_ERROR_GETCWD );
                    995:     }
                    996:     /* got dirc from getcwd*/
                    997:     printf(" DIRC = %s \n",dirc);
1.205     brouard   998:   } else {                             /* strip directory from path */
1.126     brouard   999:     ss++;                              /* after this, the filename */
                   1000:     l2 = strlen( ss );                 /* length of filename */
                   1001:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1002:     strcpy( name, ss );                /* save file name */
                   1003:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1004:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1005:     printf(" DIRC2 = %s \n",dirc);
                   1006:   }
                   1007:   /* We add a separator at the end of dirc if not exists */
                   1008:   l1 = strlen( dirc );                 /* length of directory */
                   1009:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1010:     dirc[l1] =  DIRSEPARATOR;
                   1011:     dirc[l1+1] = 0; 
                   1012:     printf(" DIRC3 = %s \n",dirc);
                   1013:   }
                   1014:   ss = strrchr( name, '.' );           /* find last / */
                   1015:   if (ss >0){
                   1016:     ss++;
                   1017:     strcpy(ext,ss);                    /* save extension */
                   1018:     l1= strlen( name);
                   1019:     l2= strlen(ss)+1;
                   1020:     strncpy( finame, name, l1-l2);
                   1021:     finame[l1-l2]= 0;
                   1022:   }
                   1023: 
                   1024:   return( 0 );                         /* we're done */
                   1025: }
                   1026: 
                   1027: 
                   1028: /******************************************/
                   1029: 
                   1030: void replace_back_to_slash(char *s, char*t)
                   1031: {
                   1032:   int i;
                   1033:   int lg=0;
                   1034:   i=0;
                   1035:   lg=strlen(t);
                   1036:   for(i=0; i<= lg; i++) {
                   1037:     (s[i] = t[i]);
                   1038:     if (t[i]== '\\') s[i]='/';
                   1039:   }
                   1040: }
                   1041: 
1.132     brouard  1042: char *trimbb(char *out, char *in)
1.137     brouard  1043: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1044:   char *s;
                   1045:   s=out;
                   1046:   while (*in != '\0'){
1.137     brouard  1047:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1048:       in++;
                   1049:     }
                   1050:     *out++ = *in++;
                   1051:   }
                   1052:   *out='\0';
                   1053:   return s;
                   1054: }
                   1055: 
1.187     brouard  1056: /* char *substrchaine(char *out, char *in, char *chain) */
                   1057: /* { */
                   1058: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1059: /*   char *s, *t; */
                   1060: /*   t=in;s=out; */
                   1061: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1062: /*     *out++ = *in++; */
                   1063: /*   } */
                   1064: 
                   1065: /*   /\* *in matches *chain *\/ */
                   1066: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1067: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1068: /*   } */
                   1069: /*   in--; chain--; */
                   1070: /*   while ( (*in != '\0')){ */
                   1071: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1072: /*     *out++ = *in++; */
                   1073: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1074: /*   } */
                   1075: /*   *out='\0'; */
                   1076: /*   out=s; */
                   1077: /*   return out; */
                   1078: /* } */
                   1079: char *substrchaine(char *out, char *in, char *chain)
                   1080: {
                   1081:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1082:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1083: 
                   1084:   char *strloc;
                   1085: 
                   1086:   strcpy (out, in); 
                   1087:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1088:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1089:   if(strloc != NULL){ 
                   1090:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1091:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1092:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1093:   }
                   1094:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1095:   return out;
                   1096: }
                   1097: 
                   1098: 
1.145     brouard  1099: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1100: {
1.187     brouard  1101:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1102:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1103:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1104:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1105:   */
1.160     brouard  1106:   char *s, *t;
1.145     brouard  1107:   t=in;s=in;
                   1108:   while ((*in != occ) && (*in != '\0')){
                   1109:     *alocc++ = *in++;
                   1110:   }
                   1111:   if( *in == occ){
                   1112:     *(alocc)='\0';
                   1113:     s=++in;
                   1114:   }
                   1115:  
                   1116:   if (s == t) {/* occ not found */
                   1117:     *(alocc-(in-s))='\0';
                   1118:     in=s;
                   1119:   }
                   1120:   while ( *in != '\0'){
                   1121:     *blocc++ = *in++;
                   1122:   }
                   1123: 
                   1124:   *blocc='\0';
                   1125:   return t;
                   1126: }
1.137     brouard  1127: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1128: {
1.187     brouard  1129:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1130:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1131:      gives blocc="abcdef2ghi" and alocc="j".
                   1132:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1133:   */
                   1134:   char *s, *t;
                   1135:   t=in;s=in;
                   1136:   while (*in != '\0'){
                   1137:     while( *in == occ){
                   1138:       *blocc++ = *in++;
                   1139:       s=in;
                   1140:     }
                   1141:     *blocc++ = *in++;
                   1142:   }
                   1143:   if (s == t) /* occ not found */
                   1144:     *(blocc-(in-s))='\0';
                   1145:   else
                   1146:     *(blocc-(in-s)-1)='\0';
                   1147:   in=s;
                   1148:   while ( *in != '\0'){
                   1149:     *alocc++ = *in++;
                   1150:   }
                   1151: 
                   1152:   *alocc='\0';
                   1153:   return s;
                   1154: }
                   1155: 
1.126     brouard  1156: int nbocc(char *s, char occ)
                   1157: {
                   1158:   int i,j=0;
                   1159:   int lg=20;
                   1160:   i=0;
                   1161:   lg=strlen(s);
                   1162:   for(i=0; i<= lg; i++) {
                   1163:   if  (s[i] == occ ) j++;
                   1164:   }
                   1165:   return j;
                   1166: }
                   1167: 
1.137     brouard  1168: /* void cutv(char *u,char *v, char*t, char occ) */
                   1169: /* { */
                   1170: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1171: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1172: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1173: /*   int i,lg,j,p=0; */
                   1174: /*   i=0; */
                   1175: /*   lg=strlen(t); */
                   1176: /*   for(j=0; j<=lg-1; j++) { */
                   1177: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1178: /*   } */
1.126     brouard  1179: 
1.137     brouard  1180: /*   for(j=0; j<p; j++) { */
                   1181: /*     (u[j] = t[j]); */
                   1182: /*   } */
                   1183: /*      u[p]='\0'; */
1.126     brouard  1184: 
1.137     brouard  1185: /*    for(j=0; j<= lg; j++) { */
                   1186: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1187: /*   } */
                   1188: /* } */
1.126     brouard  1189: 
1.160     brouard  1190: #ifdef _WIN32
                   1191: char * strsep(char **pp, const char *delim)
                   1192: {
                   1193:   char *p, *q;
                   1194:          
                   1195:   if ((p = *pp) == NULL)
                   1196:     return 0;
                   1197:   if ((q = strpbrk (p, delim)) != NULL)
                   1198:   {
                   1199:     *pp = q + 1;
                   1200:     *q = '\0';
                   1201:   }
                   1202:   else
                   1203:     *pp = 0;
                   1204:   return p;
                   1205: }
                   1206: #endif
                   1207: 
1.126     brouard  1208: /********************** nrerror ********************/
                   1209: 
                   1210: void nrerror(char error_text[])
                   1211: {
                   1212:   fprintf(stderr,"ERREUR ...\n");
                   1213:   fprintf(stderr,"%s\n",error_text);
                   1214:   exit(EXIT_FAILURE);
                   1215: }
                   1216: /*********************** vector *******************/
                   1217: double *vector(int nl, int nh)
                   1218: {
                   1219:   double *v;
                   1220:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1221:   if (!v) nrerror("allocation failure in vector");
                   1222:   return v-nl+NR_END;
                   1223: }
                   1224: 
                   1225: /************************ free vector ******************/
                   1226: void free_vector(double*v, int nl, int nh)
                   1227: {
                   1228:   free((FREE_ARG)(v+nl-NR_END));
                   1229: }
                   1230: 
                   1231: /************************ivector *******************************/
                   1232: int *ivector(long nl,long nh)
                   1233: {
                   1234:   int *v;
                   1235:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1236:   if (!v) nrerror("allocation failure in ivector");
                   1237:   return v-nl+NR_END;
                   1238: }
                   1239: 
                   1240: /******************free ivector **************************/
                   1241: void free_ivector(int *v, long nl, long nh)
                   1242: {
                   1243:   free((FREE_ARG)(v+nl-NR_END));
                   1244: }
                   1245: 
                   1246: /************************lvector *******************************/
                   1247: long *lvector(long nl,long nh)
                   1248: {
                   1249:   long *v;
                   1250:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1251:   if (!v) nrerror("allocation failure in ivector");
                   1252:   return v-nl+NR_END;
                   1253: }
                   1254: 
                   1255: /******************free lvector **************************/
                   1256: void free_lvector(long *v, long nl, long nh)
                   1257: {
                   1258:   free((FREE_ARG)(v+nl-NR_END));
                   1259: }
                   1260: 
                   1261: /******************* imatrix *******************************/
                   1262: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1263:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1264: { 
                   1265:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1266:   int **m; 
                   1267:   
                   1268:   /* allocate pointers to rows */ 
                   1269:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1270:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1271:   m += NR_END; 
                   1272:   m -= nrl; 
                   1273:   
                   1274:   
                   1275:   /* allocate rows and set pointers to them */ 
                   1276:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1277:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1278:   m[nrl] += NR_END; 
                   1279:   m[nrl] -= ncl; 
                   1280:   
                   1281:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1282:   
                   1283:   /* return pointer to array of pointers to rows */ 
                   1284:   return m; 
                   1285: } 
                   1286: 
                   1287: /****************** free_imatrix *************************/
                   1288: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1289:       int **m;
                   1290:       long nch,ncl,nrh,nrl; 
                   1291:      /* free an int matrix allocated by imatrix() */ 
                   1292: { 
                   1293:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1294:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1295: } 
                   1296: 
                   1297: /******************* matrix *******************************/
                   1298: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1299: {
                   1300:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1301:   double **m;
                   1302: 
                   1303:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1304:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1305:   m += NR_END;
                   1306:   m -= nrl;
                   1307: 
                   1308:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1309:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1310:   m[nrl] += NR_END;
                   1311:   m[nrl] -= ncl;
                   1312: 
                   1313:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1314:   return m;
1.145     brouard  1315:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1316: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1317: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1318:    */
                   1319: }
                   1320: 
                   1321: /*************************free matrix ************************/
                   1322: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1323: {
                   1324:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1325:   free((FREE_ARG)(m+nrl-NR_END));
                   1326: }
                   1327: 
                   1328: /******************* ma3x *******************************/
                   1329: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1330: {
                   1331:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1332:   double ***m;
                   1333: 
                   1334:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1335:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1336:   m += NR_END;
                   1337:   m -= nrl;
                   1338: 
                   1339:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1340:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1341:   m[nrl] += NR_END;
                   1342:   m[nrl] -= ncl;
                   1343: 
                   1344:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1345: 
                   1346:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1347:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1348:   m[nrl][ncl] += NR_END;
                   1349:   m[nrl][ncl] -= nll;
                   1350:   for (j=ncl+1; j<=nch; j++) 
                   1351:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1352:   
                   1353:   for (i=nrl+1; i<=nrh; i++) {
                   1354:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1355:     for (j=ncl+1; j<=nch; j++) 
                   1356:       m[i][j]=m[i][j-1]+nlay;
                   1357:   }
                   1358:   return m; 
                   1359:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1360:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1361:   */
                   1362: }
                   1363: 
                   1364: /*************************free ma3x ************************/
                   1365: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1366: {
                   1367:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1368:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1369:   free((FREE_ARG)(m+nrl-NR_END));
                   1370: }
                   1371: 
                   1372: /*************** function subdirf ***********/
                   1373: char *subdirf(char fileres[])
                   1374: {
                   1375:   /* Caution optionfilefiname is hidden */
                   1376:   strcpy(tmpout,optionfilefiname);
                   1377:   strcat(tmpout,"/"); /* Add to the right */
                   1378:   strcat(tmpout,fileres);
                   1379:   return tmpout;
                   1380: }
                   1381: 
                   1382: /*************** function subdirf2 ***********/
                   1383: char *subdirf2(char fileres[], char *preop)
                   1384: {
                   1385:   
                   1386:   /* Caution optionfilefiname is hidden */
                   1387:   strcpy(tmpout,optionfilefiname);
                   1388:   strcat(tmpout,"/");
                   1389:   strcat(tmpout,preop);
                   1390:   strcat(tmpout,fileres);
                   1391:   return tmpout;
                   1392: }
                   1393: 
                   1394: /*************** function subdirf3 ***********/
                   1395: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1396: {
                   1397:   
                   1398:   /* Caution optionfilefiname is hidden */
                   1399:   strcpy(tmpout,optionfilefiname);
                   1400:   strcat(tmpout,"/");
                   1401:   strcat(tmpout,preop);
                   1402:   strcat(tmpout,preop2);
                   1403:   strcat(tmpout,fileres);
                   1404:   return tmpout;
                   1405: }
1.213     brouard  1406:  
                   1407: /*************** function subdirfext ***********/
                   1408: char *subdirfext(char fileres[], char *preop, char *postop)
                   1409: {
                   1410:   
                   1411:   strcpy(tmpout,preop);
                   1412:   strcat(tmpout,fileres);
                   1413:   strcat(tmpout,postop);
                   1414:   return tmpout;
                   1415: }
1.126     brouard  1416: 
1.213     brouard  1417: /*************** function subdirfext3 ***********/
                   1418: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1419: {
                   1420:   
                   1421:   /* Caution optionfilefiname is hidden */
                   1422:   strcpy(tmpout,optionfilefiname);
                   1423:   strcat(tmpout,"/");
                   1424:   strcat(tmpout,preop);
                   1425:   strcat(tmpout,fileres);
                   1426:   strcat(tmpout,postop);
                   1427:   return tmpout;
                   1428: }
                   1429:  
1.162     brouard  1430: char *asc_diff_time(long time_sec, char ascdiff[])
                   1431: {
                   1432:   long sec_left, days, hours, minutes;
                   1433:   days = (time_sec) / (60*60*24);
                   1434:   sec_left = (time_sec) % (60*60*24);
                   1435:   hours = (sec_left) / (60*60) ;
                   1436:   sec_left = (sec_left) %(60*60);
                   1437:   minutes = (sec_left) /60;
                   1438:   sec_left = (sec_left) % (60);
                   1439:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1440:   return ascdiff;
                   1441: }
                   1442: 
1.126     brouard  1443: /***************** f1dim *************************/
                   1444: extern int ncom; 
                   1445: extern double *pcom,*xicom;
                   1446: extern double (*nrfunc)(double []); 
                   1447:  
                   1448: double f1dim(double x) 
                   1449: { 
                   1450:   int j; 
                   1451:   double f;
                   1452:   double *xt; 
                   1453:  
                   1454:   xt=vector(1,ncom); 
                   1455:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1456:   f=(*nrfunc)(xt); 
                   1457:   free_vector(xt,1,ncom); 
                   1458:   return f; 
                   1459: } 
                   1460: 
                   1461: /*****************brent *************************/
                   1462: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1463: {
                   1464:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1465:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1466:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1467:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1468:    * returned function value. 
                   1469:   */
1.126     brouard  1470:   int iter; 
                   1471:   double a,b,d,etemp;
1.159     brouard  1472:   double fu=0,fv,fw,fx;
1.164     brouard  1473:   double ftemp=0.;
1.126     brouard  1474:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1475:   double e=0.0; 
                   1476:  
                   1477:   a=(ax < cx ? ax : cx); 
                   1478:   b=(ax > cx ? ax : cx); 
                   1479:   x=w=v=bx; 
                   1480:   fw=fv=fx=(*f)(x); 
                   1481:   for (iter=1;iter<=ITMAX;iter++) { 
                   1482:     xm=0.5*(a+b); 
                   1483:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1484:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1485:     printf(".");fflush(stdout);
                   1486:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1487: #ifdef DEBUGBRENT
1.126     brouard  1488:     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);
                   1489:     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);
                   1490:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1491: #endif
                   1492:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1493:       *xmin=x; 
                   1494:       return fx; 
                   1495:     } 
                   1496:     ftemp=fu;
                   1497:     if (fabs(e) > tol1) { 
                   1498:       r=(x-w)*(fx-fv); 
                   1499:       q=(x-v)*(fx-fw); 
                   1500:       p=(x-v)*q-(x-w)*r; 
                   1501:       q=2.0*(q-r); 
                   1502:       if (q > 0.0) p = -p; 
                   1503:       q=fabs(q); 
                   1504:       etemp=e; 
                   1505:       e=d; 
                   1506:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1507:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1508:       else { 
                   1509:        d=p/q; 
                   1510:        u=x+d; 
                   1511:        if (u-a < tol2 || b-u < tol2) 
                   1512:          d=SIGN(tol1,xm-x); 
                   1513:       } 
                   1514:     } else { 
                   1515:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1516:     } 
                   1517:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1518:     fu=(*f)(u); 
                   1519:     if (fu <= fx) { 
                   1520:       if (u >= x) a=x; else b=x; 
                   1521:       SHFT(v,w,x,u) 
1.183     brouard  1522:       SHFT(fv,fw,fx,fu) 
                   1523:     } else { 
                   1524:       if (u < x) a=u; else b=u; 
                   1525:       if (fu <= fw || w == x) { 
                   1526:        v=w; 
                   1527:        w=u; 
                   1528:        fv=fw; 
                   1529:        fw=fu; 
                   1530:       } else if (fu <= fv || v == x || v == w) { 
                   1531:        v=u; 
                   1532:        fv=fu; 
                   1533:       } 
                   1534:     } 
1.126     brouard  1535:   } 
                   1536:   nrerror("Too many iterations in brent"); 
                   1537:   *xmin=x; 
                   1538:   return fx; 
                   1539: } 
                   1540: 
                   1541: /****************** mnbrak ***********************/
                   1542: 
                   1543: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1544:            double (*func)(double)) 
1.183     brouard  1545: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1546: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1547: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1548: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1549:    */
1.126     brouard  1550:   double ulim,u,r,q, dum;
                   1551:   double fu; 
1.187     brouard  1552: 
                   1553:   double scale=10.;
                   1554:   int iterscale=0;
                   1555: 
                   1556:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1557:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1558: 
                   1559: 
                   1560:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1561:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1562:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1563:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1564:   /* } */
                   1565: 
1.126     brouard  1566:   if (*fb > *fa) { 
                   1567:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1568:     SHFT(dum,*fb,*fa,dum) 
                   1569:   } 
1.126     brouard  1570:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1571:   *fc=(*func)(*cx); 
1.183     brouard  1572: #ifdef DEBUG
                   1573:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1574:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1575: #endif
                   1576:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1577:     r=(*bx-*ax)*(*fb-*fc); 
                   1578:     q=(*bx-*cx)*(*fb-*fa); 
                   1579:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1580:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1581:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1582:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1583:       fu=(*func)(u); 
1.163     brouard  1584: #ifdef DEBUG
                   1585:       /* f(x)=A(x-u)**2+f(u) */
                   1586:       double A, fparabu; 
                   1587:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1588:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1589:       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);
                   1590:       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  1591:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1592:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1593:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1594:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1595: #endif 
1.184     brouard  1596: #ifdef MNBRAKORIGINAL
1.183     brouard  1597: #else
1.191     brouard  1598: /*       if (fu > *fc) { */
                   1599: /* #ifdef DEBUG */
                   1600: /*       printf("mnbrak4  fu > fc \n"); */
                   1601: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1602: /* #endif */
                   1603: /*     /\* 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 *\\/  *\/ */
                   1604: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1605: /*     dum=u; /\* Shifting c and u *\/ */
                   1606: /*     u = *cx; */
                   1607: /*     *cx = dum; */
                   1608: /*     dum = fu; */
                   1609: /*     fu = *fc; */
                   1610: /*     *fc =dum; */
                   1611: /*       } else { /\* end *\/ */
                   1612: /* #ifdef DEBUG */
                   1613: /*       printf("mnbrak3  fu < fc \n"); */
                   1614: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1615: /* #endif */
                   1616: /*     dum=u; /\* Shifting c and u *\/ */
                   1617: /*     u = *cx; */
                   1618: /*     *cx = dum; */
                   1619: /*     dum = fu; */
                   1620: /*     fu = *fc; */
                   1621: /*     *fc =dum; */
                   1622: /*       } */
1.183     brouard  1623: #ifdef DEBUG
1.191     brouard  1624:       printf("mnbrak34  fu < or >= fc \n");
                   1625:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1626: #endif
1.191     brouard  1627:       dum=u; /* Shifting c and u */
                   1628:       u = *cx;
                   1629:       *cx = dum;
                   1630:       dum = fu;
                   1631:       fu = *fc;
                   1632:       *fc =dum;
1.183     brouard  1633: #endif
1.162     brouard  1634:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1635: #ifdef DEBUG
                   1636:       printf("mnbrak2  u after c but before ulim\n");
                   1637:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1638: #endif
1.126     brouard  1639:       fu=(*func)(u); 
                   1640:       if (fu < *fc) { 
1.183     brouard  1641: #ifdef DEBUG
                   1642:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1643:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1644: #endif
1.126     brouard  1645:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1646:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1647:       } 
1.162     brouard  1648:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1649: #ifdef DEBUG
                   1650:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1651:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1652: #endif
1.126     brouard  1653:       u=ulim; 
                   1654:       fu=(*func)(u); 
1.183     brouard  1655:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1656: #ifdef DEBUG
                   1657:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1658:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1659: #endif
1.126     brouard  1660:       u=(*cx)+GOLD*(*cx-*bx); 
                   1661:       fu=(*func)(u); 
1.183     brouard  1662:     } /* end tests */
1.126     brouard  1663:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1664:     SHFT(*fa,*fb,*fc,fu) 
                   1665: #ifdef DEBUG
                   1666:       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);
                   1667:       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);
                   1668: #endif
                   1669:   } /* 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  1670: } 
                   1671: 
                   1672: /*************** linmin ************************/
1.162     brouard  1673: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1674: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1675: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1676: the value of func at the returned location p . This is actually all accomplished by calling the
                   1677: routines mnbrak and brent .*/
1.126     brouard  1678: int ncom; 
                   1679: double *pcom,*xicom;
                   1680: double (*nrfunc)(double []); 
                   1681:  
                   1682: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1683: { 
                   1684:   double brent(double ax, double bx, double cx, 
                   1685:               double (*f)(double), double tol, double *xmin); 
                   1686:   double f1dim(double x); 
                   1687:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1688:              double *fc, double (*func)(double)); 
                   1689:   int j; 
                   1690:   double xx,xmin,bx,ax; 
                   1691:   double fx,fb,fa;
1.187     brouard  1692: 
1.203     brouard  1693: #ifdef LINMINORIGINAL
                   1694: #else
                   1695:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1696: #endif
                   1697:   
1.126     brouard  1698:   ncom=n; 
                   1699:   pcom=vector(1,n); 
                   1700:   xicom=vector(1,n); 
                   1701:   nrfunc=func; 
                   1702:   for (j=1;j<=n;j++) { 
                   1703:     pcom[j]=p[j]; 
1.202     brouard  1704:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1705:   } 
1.187     brouard  1706: 
1.203     brouard  1707: #ifdef LINMINORIGINAL
                   1708:   xx=1.;
                   1709: #else
                   1710:   axs=0.0;
                   1711:   xxs=1.;
                   1712:   do{
                   1713:     xx= xxs;
                   1714: #endif
1.187     brouard  1715:     ax=0.;
                   1716:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1717:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1718:     /* 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))   */
                   1719:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1720:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1721:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1722:     /* 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  1723: #ifdef LINMINORIGINAL
                   1724: #else
                   1725:     if (fx != fx){
                   1726:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1727:        printf("|");
                   1728:        fprintf(ficlog,"|");
                   1729: #ifdef DEBUGLINMIN
                   1730:        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);
                   1731: #endif
                   1732:     }
                   1733:   }while(fx != fx);
                   1734: #endif
                   1735:   
1.191     brouard  1736: #ifdef DEBUGLINMIN
                   1737:   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  1738:   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  1739: #endif
1.187     brouard  1740:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1741:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1742:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1743:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1744:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1745: #ifdef DEBUG
                   1746:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1747:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1748: #endif
1.191     brouard  1749: #ifdef DEBUGLINMIN
                   1750:   printf("linmin end ");
1.202     brouard  1751:   fprintf(ficlog,"linmin end ");
1.191     brouard  1752: #endif
1.126     brouard  1753:   for (j=1;j<=n;j++) { 
1.203     brouard  1754: #ifdef LINMINORIGINAL
                   1755:     xi[j] *= xmin; 
                   1756: #else
                   1757: #ifdef DEBUGLINMIN
                   1758:     if(xxs <1.0)
                   1759:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1760: #endif
                   1761:     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) */
                   1762: #ifdef DEBUGLINMIN
                   1763:     if(xxs <1.0)
                   1764:       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 );
                   1765: #endif
                   1766: #endif
1.187     brouard  1767:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1768:   } 
1.191     brouard  1769: #ifdef DEBUGLINMIN
1.203     brouard  1770:   printf("\n");
1.191     brouard  1771:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1772:   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  1773:   for (j=1;j<=n;j++) { 
1.202     brouard  1774:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1775:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1776:     if(j % ncovmodel == 0){
1.191     brouard  1777:       printf("\n");
1.202     brouard  1778:       fprintf(ficlog,"\n");
                   1779:     }
1.191     brouard  1780:   }
1.203     brouard  1781: #else
1.191     brouard  1782: #endif
1.126     brouard  1783:   free_vector(xicom,1,n); 
                   1784:   free_vector(pcom,1,n); 
                   1785: } 
                   1786: 
                   1787: 
                   1788: /*************** powell ************************/
1.162     brouard  1789: /*
                   1790: Minimization of a function func of n variables. Input consists of an initial starting point
                   1791: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1792: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1793: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1794: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1795: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1796:  */
1.126     brouard  1797: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1798:            double (*func)(double [])) 
                   1799: { 
                   1800:   void linmin(double p[], double xi[], int n, double *fret, 
                   1801:              double (*func)(double [])); 
                   1802:   int i,ibig,j; 
                   1803:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1804:   double directest;
1.126     brouard  1805:   double fp,fptt;
                   1806:   double *xits;
                   1807:   int niterf, itmp;
                   1808: 
                   1809:   pt=vector(1,n); 
                   1810:   ptt=vector(1,n); 
                   1811:   xit=vector(1,n); 
                   1812:   xits=vector(1,n); 
                   1813:   *fret=(*func)(p); 
                   1814:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1815:   rcurr_time = time(NULL);  
1.126     brouard  1816:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1817:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1818:     ibig=0; 
                   1819:     del=0.0; 
1.157     brouard  1820:     rlast_time=rcurr_time;
                   1821:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1822:     rcurr_time = time(NULL);  
                   1823:     curr_time = *localtime(&rcurr_time);
                   1824:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1825:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1826: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1827:     for (i=1;i<=n;i++) {
1.126     brouard  1828:       printf(" %d %.12f",i, p[i]);
                   1829:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1830:       fprintf(ficrespow," %.12lf", p[i]);
                   1831:     }
                   1832:     printf("\n");
                   1833:     fprintf(ficlog,"\n");
                   1834:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1835:     if(*iter <=3){
1.157     brouard  1836:       tml = *localtime(&rcurr_time);
                   1837:       strcpy(strcurr,asctime(&tml));
                   1838:       rforecast_time=rcurr_time; 
1.126     brouard  1839:       itmp = strlen(strcurr);
                   1840:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1841:        strcurr[itmp-1]='\0';
1.162     brouard  1842:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1843:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1844:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1845:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1846:        forecast_time = *localtime(&rforecast_time);
                   1847:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1848:        itmp = strlen(strfor);
                   1849:        if(strfor[itmp-1]=='\n')
                   1850:        strfor[itmp-1]='\0';
1.157     brouard  1851:        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);
                   1852:        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  1853:       }
                   1854:     }
1.187     brouard  1855:     for (i=1;i<=n;i++) { /* For each direction i */
                   1856:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1857:       fptt=(*fret); 
                   1858: #ifdef DEBUG
1.203     brouard  1859:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1860:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1861: #endif
1.203     brouard  1862:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1863:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1864:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1865:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1866:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1867:        /* because that direction will be replaced unless the gain del is small */
                   1868:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1869:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1870:        /* with the new direction. */
1.126     brouard  1871:        del=fabs(fptt-(*fret)); 
                   1872:        ibig=i; 
                   1873:       } 
                   1874: #ifdef DEBUG
                   1875:       printf("%d %.12e",i,(*fret));
                   1876:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1877:       for (j=1;j<=n;j++) {
                   1878:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1879:        printf(" x(%d)=%.12e",j,xit[j]);
                   1880:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1881:       }
                   1882:       for(j=1;j<=n;j++) {
1.162     brouard  1883:        printf(" p(%d)=%.12e",j,p[j]);
                   1884:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1885:       }
                   1886:       printf("\n");
                   1887:       fprintf(ficlog,"\n");
                   1888: #endif
1.187     brouard  1889:     } /* end loop on each direction i */
                   1890:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1891:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1892:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1893:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1894:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1895:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1896:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1897:       /* decreased of more than 3.84  */
                   1898:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1899:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1900:       /* By adding 10 parameters more the gain should be 18.31 */
                   1901: 
                   1902:       /* Starting the program with initial values given by a former maximization will simply change */
                   1903:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1904:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1905:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1906: #ifdef DEBUG
                   1907:       int k[2],l;
                   1908:       k[0]=1;
                   1909:       k[1]=-1;
                   1910:       printf("Max: %.12e",(*func)(p));
                   1911:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1912:       for (j=1;j<=n;j++) {
                   1913:        printf(" %.12e",p[j]);
                   1914:        fprintf(ficlog," %.12e",p[j]);
                   1915:       }
                   1916:       printf("\n");
                   1917:       fprintf(ficlog,"\n");
                   1918:       for(l=0;l<=1;l++) {
                   1919:        for (j=1;j<=n;j++) {
                   1920:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1921:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1922:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1923:        }
                   1924:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1925:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1926:       }
                   1927: #endif
                   1928: 
                   1929: 
                   1930:       free_vector(xit,1,n); 
                   1931:       free_vector(xits,1,n); 
                   1932:       free_vector(ptt,1,n); 
                   1933:       free_vector(pt,1,n); 
                   1934:       return; 
1.192     brouard  1935:     } /* enough precision */ 
1.126     brouard  1936:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1937:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1938:       ptt[j]=2.0*p[j]-pt[j]; 
                   1939:       xit[j]=p[j]-pt[j]; 
                   1940:       pt[j]=p[j]; 
                   1941:     } 
1.181     brouard  1942:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1943: #ifdef POWELLF1F3
                   1944: #else
1.161     brouard  1945:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1946: #endif
1.162     brouard  1947:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1948:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1949:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1950:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1951:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1952:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1953:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1954: #ifdef NRCORIGINAL
                   1955:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1956: #else
                   1957:       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  1958:       t= t- del*SQR(fp-fptt);
1.183     brouard  1959: #endif
1.202     brouard  1960:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1961: #ifdef DEBUG
1.181     brouard  1962:       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);
                   1963:       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  1964:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1965:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1966:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1967:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1968:       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);
                   1969:       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);
                   1970: #endif
1.183     brouard  1971: #ifdef POWELLORIGINAL
                   1972:       if (t < 0.0) { /* Then we use it for new direction */
                   1973: #else
1.182     brouard  1974:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1975:        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  1976:         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  1977:         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  1978:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1979:       } 
1.181     brouard  1980:       if (directest < 0.0) { /* Then we use it for new direction */
                   1981: #endif
1.191     brouard  1982: #ifdef DEBUGLINMIN
                   1983:        printf("Before linmin in direction P%d-P0\n",n);
                   1984:        for (j=1;j<=n;j++) { 
1.202     brouard  1985:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1986:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1987:          if(j % ncovmodel == 0){
1.191     brouard  1988:            printf("\n");
1.202     brouard  1989:            fprintf(ficlog,"\n");
                   1990:          }
1.191     brouard  1991:        }
                   1992: #endif
1.187     brouard  1993:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1994: #ifdef DEBUGLINMIN
                   1995:        for (j=1;j<=n;j++) { 
                   1996:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1997:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1998:          if(j % ncovmodel == 0){
1.191     brouard  1999:            printf("\n");
1.202     brouard  2000:            fprintf(ficlog,"\n");
                   2001:          }
1.191     brouard  2002:        }
                   2003: #endif
1.126     brouard  2004:        for (j=1;j<=n;j++) { 
1.181     brouard  2005:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2006:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  2007:        }
1.181     brouard  2008:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2009:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  2010: 
1.126     brouard  2011: #ifdef DEBUG
1.164     brouard  2012:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2013:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2014:        for(j=1;j<=n;j++){
                   2015:          printf(" %.12e",xit[j]);
                   2016:          fprintf(ficlog," %.12e",xit[j]);
                   2017:        }
                   2018:        printf("\n");
                   2019:        fprintf(ficlog,"\n");
                   2020: #endif
1.192     brouard  2021:       } /* end of t or directest negative */
                   2022: #ifdef POWELLF1F3
                   2023: #else
1.162     brouard  2024:     } /* end if (fptt < fp)  */
1.192     brouard  2025: #endif
                   2026:   } /* loop iteration */ 
1.126     brouard  2027: } 
                   2028: 
                   2029: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2030: 
1.203     brouard  2031: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2032: {
                   2033:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  2034:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2035:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2036:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2037:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2038:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2039:   /* Initial matrix pimij */
                   2040:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2041:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2042:   /*  0,                   0                  , 1} */
                   2043:   /*
                   2044:    * and after some iteration: */
                   2045:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2046:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2047:   /*  0,                   0                  , 1} */
                   2048:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2049:   /* {0.51571254859325999, 0.4842874514067399, */
                   2050:   /*  0.51326036147820708, 0.48673963852179264} */
                   2051:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2052: 
1.126     brouard  2053:   int i, ii,j,k;
1.209     brouard  2054:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2055:   /* double **matprod2(); */ /* test */
1.131     brouard  2056:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  2057:   double **newm;
1.209     brouard  2058:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2059:   int ncvloop=0;
1.169     brouard  2060:   
1.209     brouard  2061:   min=vector(1,nlstate);
                   2062:   max=vector(1,nlstate);
                   2063:   meandiff=vector(1,nlstate);
                   2064: 
1.126     brouard  2065:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2066:     for (j=1;j<=nlstate+ndeath;j++){
                   2067:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2068:     }
1.169     brouard  2069:   
                   2070:   cov[1]=1.;
                   2071:   
                   2072:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2073:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2074:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2075:     ncvloop++;
1.126     brouard  2076:     newm=savm;
                   2077:     /* Covariates have to be included here again */
1.138     brouard  2078:     cov[2]=agefin;
1.187     brouard  2079:     if(nagesqr==1)
                   2080:       cov[3]= agefin*agefin;;
1.138     brouard  2081:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2082:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2083:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2084:       /* 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  2085:     }
1.186     brouard  2086:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2087:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2088:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2089:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2090:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2091:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2092:     
                   2093:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2094:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2095:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2096:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2097:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2098:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2099:     
1.126     brouard  2100:     savm=oldm;
                   2101:     oldm=newm;
1.209     brouard  2102: 
                   2103:     for(j=1; j<=nlstate; j++){
                   2104:       max[j]=0.;
                   2105:       min[j]=1.;
                   2106:     }
                   2107:     for(i=1;i<=nlstate;i++){
                   2108:       sumnew=0;
                   2109:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2110:       for(j=1; j<=nlstate; j++){ 
                   2111:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2112:        max[j]=FMAX(max[j],prlim[i][j]);
                   2113:        min[j]=FMIN(min[j],prlim[i][j]);
                   2114:       }
                   2115:     }
                   2116: 
1.126     brouard  2117:     maxmax=0.;
1.209     brouard  2118:     for(j=1; j<=nlstate; j++){
                   2119:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2120:       maxmax=FMAX(maxmax,meandiff[j]);
                   2121:       /* 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  2122:     } /* j loop */
1.203     brouard  2123:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2124:     /* 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  2125:     if(maxmax < ftolpl){
1.209     brouard  2126:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2127:       free_vector(min,1,nlstate);
                   2128:       free_vector(max,1,nlstate);
                   2129:       free_vector(meandiff,1,nlstate);
1.126     brouard  2130:       return prlim;
                   2131:     }
1.169     brouard  2132:   } /* age loop */
1.208     brouard  2133:     /* After some age loop it doesn't converge */
1.209     brouard  2134:   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  2135: 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  2136:   /* 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); */
                   2137:   free_vector(min,1,nlstate);
                   2138:   free_vector(max,1,nlstate);
                   2139:   free_vector(meandiff,1,nlstate);
1.208     brouard  2140:   
1.169     brouard  2141:   return prlim; /* should not reach here */
1.126     brouard  2142: }
                   2143: 
1.217   ! brouard  2144: 
        !          2145:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
        !          2146: 
        !          2147: double **bprevalim(double **bprlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
        !          2148: {
        !          2149:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
        !          2150:      matrix by transitions matrix until convergence is reached with precision ftolpl */
        !          2151:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
        !          2152:   /* Wx is row vector: population in state 1, population in state 2, population dead */
        !          2153:   /* or prevalence in state 1, prevalence in state 2, 0 */
        !          2154:   /* newm is the matrix after multiplications, its rows are identical at a factor */
        !          2155:   /* Initial matrix pimij */
        !          2156:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
        !          2157:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
        !          2158:   /*  0,                   0                  , 1} */
        !          2159:   /*
        !          2160:    * and after some iteration: */
        !          2161:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
        !          2162:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
        !          2163:   /*  0,                   0                  , 1} */
        !          2164:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
        !          2165:   /* {0.51571254859325999, 0.4842874514067399, */
        !          2166:   /*  0.51326036147820708, 0.48673963852179264} */
        !          2167:   /* If we start from prlim again, prlim tends to a constant matrix */
        !          2168: 
        !          2169:   int i, ii,j,k;
        !          2170:   double *min, *max, *meandiff, maxmax,sumnew=0.;
        !          2171:   /* double **matprod2(); */ /* test */
        !          2172:   double **out, cov[NCOVMAX+1], **bmij();
        !          2173:   double **newm;
        !          2174:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
        !          2175:   int ncvloop=0;
        !          2176:   
        !          2177:   min=vector(1,nlstate);
        !          2178:   max=vector(1,nlstate);
        !          2179:   meandiff=vector(1,nlstate);
        !          2180: 
        !          2181:   for (ii=1;ii<=nlstate+ndeath;ii++)
        !          2182:     for (j=1;j<=nlstate+ndeath;j++){
        !          2183:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          2184:     }
        !          2185:   
        !          2186:   cov[1]=1.;
        !          2187:   
        !          2188:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
        !          2189:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
        !          2190:   for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){
        !          2191:     ncvloop++;
        !          2192:     newm=savm;
        !          2193:     /* Covariates have to be included here again */
        !          2194:     cov[2]=agefin;
        !          2195:     if(nagesqr==1)
        !          2196:       cov[3]= agefin*agefin;;
        !          2197:     for (k=1; k<=cptcovn;k++) {
        !          2198:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
        !          2199:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
        !          2200:       /* 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])]); */
        !          2201:     }
        !          2202:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          2203:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
        !          2204:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
        !          2205:     for (k=1; k<=cptcovprod;k++) /* Useless */
        !          2206:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
        !          2207:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
        !          2208:     
        !          2209:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
        !          2210:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
        !          2211:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
        !          2212:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
        !          2213:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
        !          2214:     out=matprod2(newm, oldm ,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate)); /* Bug Valgrind */
        !          2215:     
        !          2216:     savm=oldm;
        !          2217:     oldm=newm;
        !          2218: 
        !          2219:     for(j=1; j<=nlstate; j++){
        !          2220:       max[j]=0.;
        !          2221:       min[j]=1.;
        !          2222:     }
        !          2223:       /* sumnew=0; */
        !          2224:       /* for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k]; */
        !          2225:     for(j=1; j<=nlstate; j++){ 
        !          2226:       for(i=1;i<=nlstate;i++){
        !          2227:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
        !          2228:        bprlim[i][j]= newm[i][j];
        !          2229:        max[i]=FMAX(max[i],bprlim[i][j]);
        !          2230:        min[i]=FMIN(min[i],bprlim[i][j]);
        !          2231:       }
        !          2232:     }
        !          2233: 
        !          2234:     maxmax=0.;
        !          2235:     for(i=1; i<=nlstate; i++){
        !          2236:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
        !          2237:       maxmax=FMAX(maxmax,meandiff[i]);
        !          2238:       /* 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); */
        !          2239:     } /* j loop */
        !          2240:     *ncvyear= -( (int)age- (int)agefin);
        !          2241:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
        !          2242:     if(maxmax < ftolpl){
        !          2243:       printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);
        !          2244:       free_vector(min,1,nlstate);
        !          2245:       free_vector(max,1,nlstate);
        !          2246:       free_vector(meandiff,1,nlstate);
        !          2247:       return bprlim;
        !          2248:     }
        !          2249:   } /* age loop */
        !          2250:     /* After some age loop it doesn't converge */
        !          2251:   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\
        !          2252: 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);
        !          2253:   /* 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); */
        !          2254:   free_vector(min,1,nlstate);
        !          2255:   free_vector(max,1,nlstate);
        !          2256:   free_vector(meandiff,1,nlstate);
        !          2257:   
        !          2258:   return bprlim; /* should not reach here */
        !          2259: }
        !          2260: 
1.126     brouard  2261: /*************** transition probabilities ***************/ 
                   2262: 
                   2263: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2264: {
1.138     brouard  2265:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2266:      computes the probability to be observed in state j being in state i by appying the
                   2267:      model to the ncovmodel covariates (including constant and age).
                   2268:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2269:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2270:      ncth covariate in the global vector x is given by the formula:
                   2271:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2272:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2273:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2274:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2275:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2276:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2277:   */
                   2278:   double s1, lnpijopii;
1.126     brouard  2279:   /*double t34;*/
1.164     brouard  2280:   int i,j, nc, ii, jj;
1.126     brouard  2281: 
                   2282:     for(i=1; i<= nlstate; i++){
                   2283:       for(j=1; j<i;j++){
1.138     brouard  2284:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2285:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2286:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2287: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2288:        }
1.138     brouard  2289:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2290: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2291:       }
                   2292:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2293:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2294:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2295:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2296: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2297:        }
1.138     brouard  2298:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2299:       }
                   2300:     }
                   2301:     
                   2302:     for(i=1; i<= nlstate; i++){
                   2303:       s1=0;
1.131     brouard  2304:       for(j=1; j<i; j++){
1.138     brouard  2305:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2306:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2307:       }
                   2308:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2309:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2310:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2311:       }
1.138     brouard  2312:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2313:       ps[i][i]=1./(s1+1.);
1.138     brouard  2314:       /* Computing other pijs */
1.126     brouard  2315:       for(j=1; j<i; j++)
                   2316:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2317:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2318:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2319:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2320:     } /* end i */
                   2321:     
                   2322:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2323:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2324:        ps[ii][jj]=0;
                   2325:        ps[ii][ii]=1;
                   2326:       }
                   2327:     }
                   2328:     
1.145     brouard  2329:     
                   2330:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2331:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2332:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2333:     /*   } */
                   2334:     /*   printf("\n "); */
                   2335:     /* } */
                   2336:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2337:     /*
1.126     brouard  2338:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2339:       goto end;*/
                   2340:     return ps;
                   2341: }
                   2342: 
1.217   ! brouard  2343: /*************** transition probabilities ***************/ 
        !          2344: 
        !          2345: double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
        !          2346: {
        !          2347:   /* According to parameters values stored in x and the covariate's values stored in cov,
        !          2348:      computes the probability to be observed in state j being in state i by appying the
        !          2349:      model to the ncovmodel covariates (including constant and age).
        !          2350:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
        !          2351:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
        !          2352:      ncth covariate in the global vector x is given by the formula:
        !          2353:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
        !          2354:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
        !          2355:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
        !          2356:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
        !          2357:      Outputs ps[i][j] the probability to be observed in j being in j according to
        !          2358:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
        !          2359:   */
        !          2360:   double s1, lnpijopii;
        !          2361:   /*double t34;*/
        !          2362:   int i,j, nc, ii, jj;
        !          2363: 
        !          2364:     for(i=1; i<= nlstate; i++){
        !          2365:       for(j=1; j<i;j++){
        !          2366:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          2367:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
        !          2368:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
        !          2369: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          2370:        }
        !          2371:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          2372: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          2373:       }
        !          2374:       for(j=i+1; j<=nlstate+ndeath;j++){
        !          2375:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          2376:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
        !          2377:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
        !          2378: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
        !          2379:        }
        !          2380:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          2381:       }
        !          2382:     }
        !          2383:     
        !          2384:     for(i=1; i<= nlstate; i++){
        !          2385:       s1=0;
        !          2386:       for(j=1; j<i; j++){
        !          2387:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          2388:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          2389:       }
        !          2390:       for(j=i+1; j<=nlstate+ndeath; j++){
        !          2391:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          2392:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          2393:       }
        !          2394:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
        !          2395:       ps[i][i]=1./(s1+1.);
        !          2396:       /* Computing other pijs */
        !          2397:       for(j=1; j<i; j++)
        !          2398:        ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          2399:       for(j=i+1; j<=nlstate+ndeath; j++)
        !          2400:        ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          2401:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
        !          2402:     } /* end i */
        !          2403:     
        !          2404:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
        !          2405:       for(jj=1; jj<= nlstate+ndeath; jj++){
        !          2406:        ps[ii][jj]=0;
        !          2407:        ps[ii][ii]=1;
        !          2408:       }
        !          2409:     }
        !          2410:     /* Added for backcast */
        !          2411:     for(jj=1; jj<= nlstate; jj++){
        !          2412:       s1=0.;
        !          2413:       for(ii=1; ii<= nlstate; ii++){
        !          2414:        s1+=ps[ii][jj];
        !          2415:       }
        !          2416:       for(ii=1; ii<= nlstate; ii++){
        !          2417:        ps[ii][jj]=ps[ii][jj]/s1;
        !          2418:       }
        !          2419:     }
        !          2420:      
        !          2421:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
        !          2422:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
        !          2423:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
        !          2424:     /*   } */
        !          2425:     /*   printf("\n "); */
        !          2426:     /* } */
        !          2427:     /* printf("\n ");printf("%lf ",cov[2]);*/
        !          2428:     /*
        !          2429:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
        !          2430:       goto end;*/
        !          2431:     return ps;
        !          2432: }
        !          2433: 
        !          2434: 
1.126     brouard  2435: /**************** Product of 2 matrices ******************/
                   2436: 
1.145     brouard  2437: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2438: {
                   2439:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2440:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2441:   /* in, b, out are matrice of pointers which should have been initialized 
                   2442:      before: only the contents of out is modified. The function returns
                   2443:      a pointer to pointers identical to out */
1.145     brouard  2444:   int i, j, k;
1.126     brouard  2445:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2446:     for(k=ncolol; k<=ncoloh; k++){
                   2447:       out[i][k]=0.;
                   2448:       for(j=ncl; j<=nch; j++)
                   2449:        out[i][k] +=in[i][j]*b[j][k];
                   2450:     }
1.126     brouard  2451:   return out;
                   2452: }
                   2453: 
                   2454: 
                   2455: /************* Higher Matrix Product ***************/
                   2456: 
                   2457: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2458: {
                   2459:   /* Computes the transition matrix starting at age 'age' over 
                   2460:      'nhstepm*hstepm*stepm' months (i.e. until
                   2461:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2462:      nhstepm*hstepm matrices. 
                   2463:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2464:      (typically every 2 years instead of every month which is too big 
                   2465:      for the memory).
                   2466:      Model is determined by parameters x and covariates have to be 
                   2467:      included manually here. 
                   2468: 
                   2469:      */
                   2470: 
                   2471:   int i, j, d, h, k;
1.131     brouard  2472:   double **out, cov[NCOVMAX+1];
1.126     brouard  2473:   double **newm;
1.187     brouard  2474:   double agexact;
1.214     brouard  2475:   double agebegin, ageend;
1.126     brouard  2476: 
                   2477:   /* Hstepm could be zero and should return the unit matrix */
                   2478:   for (i=1;i<=nlstate+ndeath;i++)
                   2479:     for (j=1;j<=nlstate+ndeath;j++){
                   2480:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2481:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2482:     }
                   2483:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2484:   for(h=1; h <=nhstepm; h++){
                   2485:     for(d=1; d <=hstepm; d++){
                   2486:       newm=savm;
                   2487:       /* Covariates have to be included here again */
                   2488:       cov[1]=1.;
1.214     brouard  2489:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2490:       cov[2]=agexact;
                   2491:       if(nagesqr==1)
                   2492:        cov[3]= agexact*agexact;
1.131     brouard  2493:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2494:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2495:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2496:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2497:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2498:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2499:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2500:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2501:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2502:        /* 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  2503: 
                   2504: 
                   2505:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2506:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2507:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2508:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217   ! brouard  2509:       /* if((int)age == 70){ */
        !          2510:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
        !          2511:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
        !          2512:       /*         printf("%d pmmij ",i); */
        !          2513:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
        !          2514:       /*           printf("%f ",pmmij[i][j]); */
        !          2515:       /*         } */
        !          2516:       /*         printf(" oldm "); */
        !          2517:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
        !          2518:       /*           printf("%f ",oldm[i][j]); */
        !          2519:       /*         } */
        !          2520:       /*         printf("\n"); */
        !          2521:       /*       } */
        !          2522:       /* } */
1.126     brouard  2523:       savm=oldm;
                   2524:       oldm=newm;
                   2525:     }
                   2526:     for(i=1; i<=nlstate+ndeath; i++)
                   2527:       for(j=1;j<=nlstate+ndeath;j++) {
                   2528:        po[i][j][h]=newm[i][j];
1.128     brouard  2529:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2530:       }
1.128     brouard  2531:     /*printf("h=%d ",h);*/
1.126     brouard  2532:   } /* end h */
1.128     brouard  2533: /*     printf("\n H=%d \n",h); */
1.126     brouard  2534:   return po;
                   2535: }
                   2536: 
1.217   ! brouard  2537: /************* Higher Back Matrix Product ***************/
        !          2538: 
        !          2539: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
        !          2540: {
        !          2541:   /* Computes the transition matrix starting at age 'age' over 
        !          2542:      'nhstepm*hstepm*stepm' months (i.e. until
        !          2543:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
        !          2544:      nhstepm*hstepm matrices. 
        !          2545:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
        !          2546:      (typically every 2 years instead of every month which is too big 
        !          2547:      for the memory).
        !          2548:      Model is determined by parameters x and covariates have to be 
        !          2549:      included manually here. 
        !          2550: 
        !          2551:      */
        !          2552: 
        !          2553:   int i, j, d, h, k;
        !          2554:   double **out, cov[NCOVMAX+1];
        !          2555:   double **newm;
        !          2556:   double agexact;
        !          2557:   double agebegin, ageend;
        !          2558: 
        !          2559:   /* Hstepm could be zero and should return the unit matrix */
        !          2560:   for (i=1;i<=nlstate+ndeath;i++)
        !          2561:     for (j=1;j<=nlstate+ndeath;j++){
        !          2562:       oldm[i][j]=(i==j ? 1.0 : 0.0);
        !          2563:       po[i][j][0]=(i==j ? 1.0 : 0.0);
        !          2564:     }
        !          2565:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
        !          2566:   for(h=1; h <=nhstepm; h++){
        !          2567:     for(d=1; d <=hstepm; d++){
        !          2568:       newm=savm;
        !          2569:       /* Covariates have to be included here again */
        !          2570:       cov[1]=1.;
        !          2571:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
        !          2572:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
        !          2573:       cov[2]=agexact;
        !          2574:       if(nagesqr==1)
        !          2575:        cov[3]= agexact*agexact;
        !          2576:       for (k=1; k<=cptcovn;k++) 
        !          2577:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
        !          2578:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
        !          2579:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
        !          2580:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          2581:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
        !          2582:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
        !          2583:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
        !          2584:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
        !          2585:        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
        !          2586: 
        !          2587: 
        !          2588:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
        !          2589:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
        !          2590:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
        !          2591:                  oldm);
        !          2592:       /* if((int)age == 70){ */
        !          2593:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
        !          2594:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
        !          2595:       /*         printf("%d pmmij ",i); */
        !          2596:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
        !          2597:       /*           printf("%f ",pmmij[i][j]); */
        !          2598:       /*         } */
        !          2599:       /*         printf(" oldm "); */
        !          2600:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
        !          2601:       /*           printf("%f ",oldm[i][j]); */
        !          2602:       /*         } */
        !          2603:       /*         printf("\n"); */
        !          2604:       /*       } */
        !          2605:       /* } */
        !          2606:       savm=oldm;
        !          2607:       oldm=newm;
        !          2608:     }
        !          2609:     for(i=1; i<=nlstate+ndeath; i++)
        !          2610:       for(j=1;j<=nlstate+ndeath;j++) {
        !          2611:        po[i][j][h]=newm[i][j];
        !          2612:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
        !          2613:       }
        !          2614:     /*printf("h=%d ",h);*/
        !          2615:   } /* end h */
        !          2616: /*     printf("\n H=%d \n",h); */
        !          2617:   return po;
        !          2618: }
        !          2619: 
        !          2620: 
1.162     brouard  2621: #ifdef NLOPT
                   2622:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2623:   double fret;
                   2624:   double *xt;
                   2625:   int j;
                   2626:   myfunc_data *d2 = (myfunc_data *) pd;
                   2627: /* xt = (p1-1); */
                   2628:   xt=vector(1,n); 
                   2629:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2630: 
                   2631:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2632:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2633:   printf("Function = %.12lf ",fret);
                   2634:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2635:   printf("\n");
                   2636:  free_vector(xt,1,n);
                   2637:   return fret;
                   2638: }
                   2639: #endif
1.126     brouard  2640: 
                   2641: /*************** log-likelihood *************/
                   2642: double func( double *x)
                   2643: {
                   2644:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2645:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2646:   double **out;
                   2647:   double sw; /* Sum of weights */
                   2648:   double lli; /* Individual log likelihood */
                   2649:   int s1, s2;
                   2650:   double bbh, survp;
                   2651:   long ipmx;
1.187     brouard  2652:   double agexact;
1.126     brouard  2653:   /*extern weight */
                   2654:   /* We are differentiating ll according to initial status */
                   2655:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2656:   /*for(i=1;i<imx;i++) 
                   2657:     printf(" %d\n",s[4][i]);
                   2658:   */
1.162     brouard  2659: 
                   2660:   ++countcallfunc;
                   2661: 
1.126     brouard  2662:   cov[1]=1.;
                   2663: 
                   2664:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2665: 
                   2666:   if(mle==1){
                   2667:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2668:       /* Computes the values of the ncovmodel covariates of the model
                   2669:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2670:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2671:         to be observed in j being in i according to the model.
                   2672:        */
1.145     brouard  2673:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2674:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2675:       }
1.137     brouard  2676:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2677:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2678:         has been calculated etc */
1.126     brouard  2679:       for(mi=1; mi<= wav[i]-1; mi++){
                   2680:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2681:          for (j=1;j<=nlstate+ndeath;j++){
                   2682:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2683:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2684:          }
                   2685:        for(d=0; d<dh[mi][i]; d++){
                   2686:          newm=savm;
1.187     brouard  2687:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2688:          cov[2]=agexact;
                   2689:          if(nagesqr==1)
                   2690:            cov[3]= agexact*agexact;
1.126     brouard  2691:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2692:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2693:          }
                   2694:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2695:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2696:          savm=oldm;
                   2697:          oldm=newm;
                   2698:        } /* end mult */
                   2699:       
                   2700:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2701:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2702:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2703:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2704:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2705:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2706:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2707:         * probability in order to take into account the bias as a fraction of the way
                   2708:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2709:         * -stepm/2 to stepm/2 .
                   2710:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2711:         * For stepm > 1 the results are less biased than in previous versions. 
                   2712:         */
                   2713:        s1=s[mw[mi][i]][i];
                   2714:        s2=s[mw[mi+1][i]][i];
                   2715:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2716:        /* bias bh is positive if real duration
                   2717:         * is higher than the multiple of stepm and negative otherwise.
                   2718:         */
                   2719:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2720:        if( s2 > nlstate){ 
                   2721:          /* i.e. if s2 is a death state and if the date of death is known 
                   2722:             then the contribution to the likelihood is the probability to 
                   2723:             die between last step unit time and current  step unit time, 
                   2724:             which is also equal to probability to die before dh 
                   2725:             minus probability to die before dh-stepm . 
                   2726:             In version up to 0.92 likelihood was computed
                   2727:        as if date of death was unknown. Death was treated as any other
                   2728:        health state: the date of the interview describes the actual state
                   2729:        and not the date of a change in health state. The former idea was
                   2730:        to consider that at each interview the state was recorded
                   2731:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2732:        introduced the exact date of death then we should have modified
                   2733:        the contribution of an exact death to the likelihood. This new
                   2734:        contribution is smaller and very dependent of the step unit
                   2735:        stepm. It is no more the probability to die between last interview
                   2736:        and month of death but the probability to survive from last
                   2737:        interview up to one month before death multiplied by the
                   2738:        probability to die within a month. Thanks to Chris
                   2739:        Jackson for correcting this bug.  Former versions increased
                   2740:        mortality artificially. The bad side is that we add another loop
                   2741:        which slows down the processing. The difference can be up to 10%
                   2742:        lower mortality.
                   2743:          */
1.183     brouard  2744:        /* If, at the beginning of the maximization mostly, the
                   2745:           cumulative probability or probability to be dead is
                   2746:           constant (ie = 1) over time d, the difference is equal to
                   2747:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2748:           s1 at precedent wave, to be dead a month before current
                   2749:           wave is equal to probability, being at state s1 at
                   2750:           precedent wave, to be dead at mont of the current
                   2751:           wave. Then the observed probability (that this person died)
                   2752:           is null according to current estimated parameter. In fact,
                   2753:           it should be very low but not zero otherwise the log go to
                   2754:           infinity.
                   2755:        */
                   2756: /* #ifdef INFINITYORIGINAL */
                   2757: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2758: /* #else */
                   2759: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2760: /*         lli=log(mytinydouble); */
                   2761: /*       else */
                   2762: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2763: /* #endif */
1.216     brouard  2764:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2765:          
                   2766:        } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2767:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2768:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2769:          /*survp += out[s1][j]; */
                   2770:          lli= log(survp);
                   2771:        }
                   2772:        else if  (s2==-4) { 
                   2773:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2774:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2775:          lli= log(survp); 
                   2776:        } 
                   2777:        else if  (s2==-5) { 
                   2778:          for (j=1,survp=0. ; j<=2; j++)  
                   2779:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2780:          lli= log(survp); 
                   2781:        } 
                   2782:        else{
                   2783:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2784:          /*  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 */
                   2785:        } 
                   2786:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2787:        /*if(lli ==000.0)*/
                   2788:        /*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); */
                   2789:        ipmx +=1;
                   2790:        sw += weight[i];
                   2791:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2792:        /* if (lli < log(mytinydouble)){ */
                   2793:        /*   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); */
                   2794:        /*   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]); */
                   2795:        /* } */
1.126     brouard  2796:       } /* end of wave */
                   2797:     } /* end of individual */
                   2798:   }  else if(mle==2){
                   2799:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2800:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2801:       for(mi=1; mi<= wav[i]-1; mi++){
                   2802:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2803:          for (j=1;j<=nlstate+ndeath;j++){
                   2804:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2805:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2806:          }
                   2807:        for(d=0; d<=dh[mi][i]; d++){
                   2808:          newm=savm;
1.187     brouard  2809:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2810:          cov[2]=agexact;
                   2811:          if(nagesqr==1)
                   2812:            cov[3]= agexact*agexact;
1.126     brouard  2813:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2814:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2815:          }
                   2816:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2817:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2818:          savm=oldm;
                   2819:          oldm=newm;
                   2820:        } /* end mult */
                   2821:       
                   2822:        s1=s[mw[mi][i]][i];
                   2823:        s2=s[mw[mi+1][i]][i];
                   2824:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2825:        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 */
                   2826:        ipmx +=1;
                   2827:        sw += weight[i];
                   2828:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2829:       } /* end of wave */
                   2830:     } /* end of individual */
                   2831:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2832:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2833:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2834:       for(mi=1; mi<= wav[i]-1; mi++){
                   2835:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2836:          for (j=1;j<=nlstate+ndeath;j++){
                   2837:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2838:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2839:          }
                   2840:        for(d=0; d<dh[mi][i]; d++){
                   2841:          newm=savm;
1.187     brouard  2842:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2843:          cov[2]=agexact;
                   2844:          if(nagesqr==1)
                   2845:            cov[3]= agexact*agexact;
1.126     brouard  2846:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2847:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2848:          }
                   2849:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2850:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2851:          savm=oldm;
                   2852:          oldm=newm;
                   2853:        } /* end mult */
                   2854:       
                   2855:        s1=s[mw[mi][i]][i];
                   2856:        s2=s[mw[mi+1][i]][i];
                   2857:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2858:        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 */
                   2859:        ipmx +=1;
                   2860:        sw += weight[i];
                   2861:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2862:       } /* end of wave */
                   2863:     } /* end of individual */
                   2864:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2865:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2866:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2867:       for(mi=1; mi<= wav[i]-1; mi++){
                   2868:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2869:          for (j=1;j<=nlstate+ndeath;j++){
                   2870:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2871:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2872:          }
                   2873:        for(d=0; d<dh[mi][i]; d++){
                   2874:          newm=savm;
1.187     brouard  2875:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2876:          cov[2]=agexact;
                   2877:          if(nagesqr==1)
                   2878:            cov[3]= agexact*agexact;
1.126     brouard  2879:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2880:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2881:          }
                   2882:        
                   2883:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2884:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2885:          savm=oldm;
                   2886:          oldm=newm;
                   2887:        } /* end mult */
                   2888:       
                   2889:        s1=s[mw[mi][i]][i];
                   2890:        s2=s[mw[mi+1][i]][i];
                   2891:        if( s2 > nlstate){ 
                   2892:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  2893:        } else if  ( s2==-1 ) { /* alive */
                   2894:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2895:            survp += out[s1][j];
                   2896:          lli= log(survp);
1.126     brouard  2897:        }else{
                   2898:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2899:        }
                   2900:        ipmx +=1;
                   2901:        sw += weight[i];
                   2902:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2903: /*     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]); */
                   2904:       } /* end of wave */
                   2905:     } /* end of individual */
                   2906:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2907:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2908:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2909:       for(mi=1; mi<= wav[i]-1; mi++){
                   2910:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2911:          for (j=1;j<=nlstate+ndeath;j++){
                   2912:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2913:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2914:          }
                   2915:        for(d=0; d<dh[mi][i]; d++){
                   2916:          newm=savm;
1.187     brouard  2917:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2918:          cov[2]=agexact;
                   2919:          if(nagesqr==1)
                   2920:            cov[3]= agexact*agexact;
1.126     brouard  2921:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2922:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2923:          }
                   2924:        
                   2925:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2926:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2927:          savm=oldm;
                   2928:          oldm=newm;
                   2929:        } /* end mult */
                   2930:       
                   2931:        s1=s[mw[mi][i]][i];
                   2932:        s2=s[mw[mi+1][i]][i];
                   2933:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2934:        ipmx +=1;
                   2935:        sw += weight[i];
                   2936:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2937:        /*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]);*/
                   2938:       } /* end of wave */
                   2939:     } /* end of individual */
                   2940:   } /* End of if */
                   2941:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2942:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2943:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2944:   return -l;
                   2945: }
                   2946: 
                   2947: /*************** log-likelihood *************/
                   2948: double funcone( double *x)
                   2949: {
                   2950:   /* Same as likeli but slower because of a lot of printf and if */
                   2951:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2952:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2953:   double **out;
                   2954:   double lli; /* Individual log likelihood */
                   2955:   double llt;
                   2956:   int s1, s2;
                   2957:   double bbh, survp;
1.187     brouard  2958:   double agexact;
1.214     brouard  2959:   double agebegin, ageend;
1.126     brouard  2960:   /*extern weight */
                   2961:   /* We are differentiating ll according to initial status */
                   2962:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2963:   /*for(i=1;i<imx;i++) 
                   2964:     printf(" %d\n",s[4][i]);
                   2965:   */
                   2966:   cov[1]=1.;
                   2967: 
                   2968:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2969: 
                   2970:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2971:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2972:     for(mi=1; mi<= wav[i]-1; mi++){
                   2973:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2974:        for (j=1;j<=nlstate+ndeath;j++){
                   2975:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2976:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2977:        }
1.214     brouard  2978:       
                   2979:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   2980:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   2981:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   2982:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2983:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  2984:        newm=savm;
1.187     brouard  2985:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2986:        cov[2]=agexact;
                   2987:        if(nagesqr==1)
                   2988:          cov[3]= agexact*agexact;
1.126     brouard  2989:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2990:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2991:        }
1.187     brouard  2992: 
1.145     brouard  2993:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2994:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2995:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2996:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2997:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2998:        savm=oldm;
                   2999:        oldm=newm;
                   3000:       } /* end mult */
                   3001:       
                   3002:       s1=s[mw[mi][i]][i];
                   3003:       s2=s[mw[mi+1][i]][i];
1.217   ! brouard  3004:       /* if(s2==-1){ */
        !          3005:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
        !          3006:       /*       /\* exit(1); *\/ */
        !          3007:       /* } */
1.126     brouard  3008:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3009:       /* bias is positive if real duration
                   3010:        * is higher than the multiple of stepm and negative otherwise.
                   3011:        */
                   3012:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   3013:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3014:       } else if  ( s2==-1 ) { /* alive */
1.126     brouard  3015:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3016:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3017:        lli= log(survp);
                   3018:       }else if (mle==1){
                   3019:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3020:       } else if(mle==2){
                   3021:        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 */
                   3022:       } else if(mle==3){  /* exponential inter-extrapolation */
                   3023:        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 */
                   3024:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   3025:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3026:       } else{  /* mle=0 back to 1 */
                   3027:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3028:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3029:       } /* End of if */
                   3030:       ipmx +=1;
                   3031:       sw += weight[i];
                   3032:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3033:       /*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  3034:       if(globpr){
1.214     brouard  3035:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  3036:  %11.6f %11.6f %11.6f ", \
1.214     brouard  3037:                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  3038:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3039:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3040:          llt +=ll[k]*gipmx/gsw;
                   3041:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3042:        }
                   3043:        fprintf(ficresilk," %10.6f\n", -llt);
                   3044:       }
                   3045:     } /* end of wave */
                   3046:   } /* end of individual */
                   3047:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3048:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3049:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3050:   if(globpr==0){ /* First time we count the contributions and weights */
                   3051:     gipmx=ipmx;
                   3052:     gsw=sw;
                   3053:   }
                   3054:   return -l;
                   3055: }
                   3056: 
                   3057: 
                   3058: /*************** function likelione ***********/
                   3059: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3060: {
                   3061:   /* This routine should help understanding what is done with 
                   3062:      the selection of individuals/waves and
                   3063:      to check the exact contribution to the likelihood.
                   3064:      Plotting could be done.
                   3065:    */
                   3066:   int k;
                   3067: 
                   3068:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3069:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3070:     strcat(fileresilk,fileresu);
1.126     brouard  3071:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3072:       printf("Problem with resultfile: %s\n", fileresilk);
                   3073:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3074:     }
1.214     brouard  3075:     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");
                   3076:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3077:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3078:     for(k=1; k<=nlstate; k++) 
                   3079:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3080:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3081:   }
                   3082: 
                   3083:   *fretone=(*funcone)(p);
                   3084:   if(*globpri !=0){
                   3085:     fclose(ficresilk);
1.205     brouard  3086:     if (mle ==0)
                   3087:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3088:     else if(mle >=1)
                   3089:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3090:     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  3091:     
1.208     brouard  3092:       
                   3093:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3094:       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  3095: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3096:     }
1.207     brouard  3097:     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  3098: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3099:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3100: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3101:     fflush(fichtm);
1.205     brouard  3102:   }
1.126     brouard  3103:   return;
                   3104: }
                   3105: 
                   3106: 
                   3107: /*********** Maximum Likelihood Estimation ***************/
                   3108: 
                   3109: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3110: {
1.165     brouard  3111:   int i,j, iter=0;
1.126     brouard  3112:   double **xi;
                   3113:   double fret;
                   3114:   double fretone; /* Only one call to likelihood */
                   3115:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3116: 
                   3117: #ifdef NLOPT
                   3118:   int creturn;
                   3119:   nlopt_opt opt;
                   3120:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3121:   double *lb;
                   3122:   double minf; /* the minimum objective value, upon return */
                   3123:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3124:   myfunc_data dinst, *d = &dinst;
                   3125: #endif
                   3126: 
                   3127: 
1.126     brouard  3128:   xi=matrix(1,npar,1,npar);
                   3129:   for (i=1;i<=npar;i++)
                   3130:     for (j=1;j<=npar;j++)
                   3131:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3132:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3133:   strcpy(filerespow,"POW_"); 
1.126     brouard  3134:   strcat(filerespow,fileres);
                   3135:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3136:     printf("Problem with resultfile: %s\n", filerespow);
                   3137:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3138:   }
                   3139:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3140:   for (i=1;i<=nlstate;i++)
                   3141:     for(j=1;j<=nlstate+ndeath;j++)
                   3142:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3143:   fprintf(ficrespow,"\n");
1.162     brouard  3144: #ifdef POWELL
1.126     brouard  3145:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3146: #endif
1.126     brouard  3147: 
1.162     brouard  3148: #ifdef NLOPT
                   3149: #ifdef NEWUOA
                   3150:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3151: #else
                   3152:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3153: #endif
                   3154:   lb=vector(0,npar-1);
                   3155:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3156:   nlopt_set_lower_bounds(opt, lb);
                   3157:   nlopt_set_initial_step1(opt, 0.1);
                   3158:   
                   3159:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3160:   d->function = func;
                   3161:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3162:   nlopt_set_min_objective(opt, myfunc, d);
                   3163:   nlopt_set_xtol_rel(opt, ftol);
                   3164:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3165:     printf("nlopt failed! %d\n",creturn); 
                   3166:   }
                   3167:   else {
                   3168:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3169:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3170:     iter=1; /* not equal */
                   3171:   }
                   3172:   nlopt_destroy(opt);
                   3173: #endif
1.126     brouard  3174:   free_matrix(xi,1,npar,1,npar);
                   3175:   fclose(ficrespow);
1.203     brouard  3176:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3177:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3178:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3179: 
                   3180: }
                   3181: 
                   3182: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3183: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3184: {
                   3185:   double  **a,**y,*x,pd;
1.203     brouard  3186:   /* double **hess; */
1.164     brouard  3187:   int i, j;
1.126     brouard  3188:   int *indx;
                   3189: 
                   3190:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3191:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3192:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3193:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3194:   double gompertz(double p[]);
1.203     brouard  3195:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3196: 
                   3197:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3198:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3199:   for (i=1;i<=npar;i++){
1.203     brouard  3200:     printf("%d-",i);fflush(stdout);
                   3201:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3202:    
                   3203:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3204:     
                   3205:     /*  printf(" %f ",p[i]);
                   3206:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3207:   }
                   3208:   
                   3209:   for (i=1;i<=npar;i++) {
                   3210:     for (j=1;j<=npar;j++)  {
                   3211:       if (j>i) { 
1.203     brouard  3212:        printf(".%d-%d",i,j);fflush(stdout);
                   3213:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3214:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3215:        
                   3216:        hess[j][i]=hess[i][j];    
                   3217:        /*printf(" %lf ",hess[i][j]);*/
                   3218:       }
                   3219:     }
                   3220:   }
                   3221:   printf("\n");
                   3222:   fprintf(ficlog,"\n");
                   3223: 
                   3224:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3225:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3226:   
                   3227:   a=matrix(1,npar,1,npar);
                   3228:   y=matrix(1,npar,1,npar);
                   3229:   x=vector(1,npar);
                   3230:   indx=ivector(1,npar);
                   3231:   for (i=1;i<=npar;i++)
                   3232:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3233:   ludcmp(a,npar,indx,&pd);
                   3234: 
                   3235:   for (j=1;j<=npar;j++) {
                   3236:     for (i=1;i<=npar;i++) x[i]=0;
                   3237:     x[j]=1;
                   3238:     lubksb(a,npar,indx,x);
                   3239:     for (i=1;i<=npar;i++){ 
                   3240:       matcov[i][j]=x[i];
                   3241:     }
                   3242:   }
                   3243: 
                   3244:   printf("\n#Hessian matrix#\n");
                   3245:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3246:   for (i=1;i<=npar;i++) { 
                   3247:     for (j=1;j<=npar;j++) { 
1.203     brouard  3248:       printf("%.6e ",hess[i][j]);
                   3249:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3250:     }
                   3251:     printf("\n");
                   3252:     fprintf(ficlog,"\n");
                   3253:   }
                   3254: 
1.203     brouard  3255:   /* printf("\n#Covariance matrix#\n"); */
                   3256:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3257:   /* for (i=1;i<=npar;i++) {  */
                   3258:   /*   for (j=1;j<=npar;j++) {  */
                   3259:   /*     printf("%.6e ",matcov[i][j]); */
                   3260:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3261:   /*   } */
                   3262:   /*   printf("\n"); */
                   3263:   /*   fprintf(ficlog,"\n"); */
                   3264:   /* } */
                   3265: 
1.126     brouard  3266:   /* Recompute Inverse */
1.203     brouard  3267:   /* for (i=1;i<=npar;i++) */
                   3268:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3269:   /* ludcmp(a,npar,indx,&pd); */
                   3270: 
                   3271:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3272: 
                   3273:   /* for (j=1;j<=npar;j++) { */
                   3274:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3275:   /*   x[j]=1; */
                   3276:   /*   lubksb(a,npar,indx,x); */
                   3277:   /*   for (i=1;i<=npar;i++){  */
                   3278:   /*     y[i][j]=x[i]; */
                   3279:   /*     printf("%.3e ",y[i][j]); */
                   3280:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3281:   /*   } */
                   3282:   /*   printf("\n"); */
                   3283:   /*   fprintf(ficlog,"\n"); */
                   3284:   /* } */
                   3285: 
                   3286:   /* Verifying the inverse matrix */
                   3287: #ifdef DEBUGHESS
                   3288:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3289: 
1.203     brouard  3290:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3291:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3292: 
                   3293:   for (j=1;j<=npar;j++) {
                   3294:     for (i=1;i<=npar;i++){ 
1.203     brouard  3295:       printf("%.2f ",y[i][j]);
                   3296:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3297:     }
                   3298:     printf("\n");
                   3299:     fprintf(ficlog,"\n");
                   3300:   }
1.203     brouard  3301: #endif
1.126     brouard  3302: 
                   3303:   free_matrix(a,1,npar,1,npar);
                   3304:   free_matrix(y,1,npar,1,npar);
                   3305:   free_vector(x,1,npar);
                   3306:   free_ivector(indx,1,npar);
1.203     brouard  3307:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3308: 
                   3309: 
                   3310: }
                   3311: 
                   3312: /*************** hessian matrix ****************/
                   3313: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3314: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3315:   int i;
                   3316:   int l=1, lmax=20;
1.203     brouard  3317:   double k1,k2, res, fx;
1.132     brouard  3318:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3319:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3320:   int k=0,kmax=10;
                   3321:   double l1;
                   3322: 
                   3323:   fx=func(x);
                   3324:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3325:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3326:     l1=pow(10,l);
                   3327:     delts=delt;
                   3328:     for(k=1 ; k <kmax; k=k+1){
                   3329:       delt = delta*(l1*k);
                   3330:       p2[theta]=x[theta] +delt;
1.145     brouard  3331:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3332:       p2[theta]=x[theta]-delt;
                   3333:       k2=func(p2)-fx;
                   3334:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3335:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3336:       
1.203     brouard  3337: #ifdef DEBUGHESSII
1.126     brouard  3338:       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);
                   3339:       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);
                   3340: #endif
                   3341:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3342:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3343:        k=kmax;
                   3344:       }
                   3345:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3346:        k=kmax; l=lmax*10;
1.126     brouard  3347:       }
                   3348:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3349:        delts=delt;
                   3350:       }
1.203     brouard  3351:     } /* End loop k */
1.126     brouard  3352:   }
                   3353:   delti[theta]=delts;
                   3354:   return res; 
                   3355:   
                   3356: }
                   3357: 
1.203     brouard  3358: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3359: {
                   3360:   int i;
1.164     brouard  3361:   int l=1, lmax=20;
1.126     brouard  3362:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3363:   double p2[MAXPARM+1];
1.203     brouard  3364:   int k, kmax=1;
                   3365:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3366: 
                   3367:   int firstime=0;
1.203     brouard  3368:   
1.126     brouard  3369:   fx=func(x);
1.203     brouard  3370:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3371:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3372:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3373:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3374:     k1=func(p2)-fx;
                   3375:   
1.203     brouard  3376:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3377:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3378:     k2=func(p2)-fx;
                   3379:   
1.203     brouard  3380:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3381:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3382:     k3=func(p2)-fx;
                   3383:   
1.203     brouard  3384:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3385:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3386:     k4=func(p2)-fx;
1.203     brouard  3387:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3388:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3389:       firstime=1;
1.203     brouard  3390:       kmax=kmax+10;
1.208     brouard  3391:     }
                   3392:     if(kmax >=10 || firstime ==1){
1.203     brouard  3393:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3394:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3395:       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);
                   3396:       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);
                   3397:     }
                   3398: #ifdef DEBUGHESSIJ
                   3399:     v1=hess[thetai][thetai];
                   3400:     v2=hess[thetaj][thetaj];
                   3401:     cv12=res;
                   3402:     /* Computing eigen value of Hessian matrix */
                   3403:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3404:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3405:     if ((lc2 <0) || (lc1 <0) ){
                   3406:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3407:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3408:       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);
                   3409:       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);
                   3410:     }
1.126     brouard  3411: #endif
                   3412:   }
                   3413:   return res;
                   3414: }
                   3415: 
1.203     brouard  3416:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3417: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3418: /* { */
                   3419: /*   int i; */
                   3420: /*   int l=1, lmax=20; */
                   3421: /*   double k1,k2,k3,k4,res,fx; */
                   3422: /*   double p2[MAXPARM+1]; */
                   3423: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3424: /*   int k=0,kmax=10; */
                   3425: /*   double l1; */
                   3426:   
                   3427: /*   fx=func(x); */
                   3428: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3429: /*     l1=pow(10,l); */
                   3430: /*     delts=delt; */
                   3431: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3432: /*       delt = delti*(l1*k); */
                   3433: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3434: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3435: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3436: /*       k1=func(p2)-fx; */
                   3437:       
                   3438: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3439: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3440: /*       k2=func(p2)-fx; */
                   3441:       
                   3442: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3443: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3444: /*       k3=func(p2)-fx; */
                   3445:       
                   3446: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3447: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3448: /*       k4=func(p2)-fx; */
                   3449: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3450: /* #ifdef DEBUGHESSIJ */
                   3451: /*       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); */
                   3452: /*       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); */
                   3453: /* #endif */
                   3454: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3455: /*     k=kmax; */
                   3456: /*       } */
                   3457: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3458: /*     k=kmax; l=lmax*10; */
                   3459: /*       } */
                   3460: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3461: /*     delts=delt; */
                   3462: /*       } */
                   3463: /*     } /\* End loop k *\/ */
                   3464: /*   } */
                   3465: /*   delti[theta]=delts; */
                   3466: /*   return res;  */
                   3467: /* } */
                   3468: 
                   3469: 
1.126     brouard  3470: /************** Inverse of matrix **************/
                   3471: void ludcmp(double **a, int n, int *indx, double *d) 
                   3472: { 
                   3473:   int i,imax,j,k; 
                   3474:   double big,dum,sum,temp; 
                   3475:   double *vv; 
                   3476:  
                   3477:   vv=vector(1,n); 
                   3478:   *d=1.0; 
                   3479:   for (i=1;i<=n;i++) { 
                   3480:     big=0.0; 
                   3481:     for (j=1;j<=n;j++) 
                   3482:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3483:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3484:     vv[i]=1.0/big; 
                   3485:   } 
                   3486:   for (j=1;j<=n;j++) { 
                   3487:     for (i=1;i<j;i++) { 
                   3488:       sum=a[i][j]; 
                   3489:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3490:       a[i][j]=sum; 
                   3491:     } 
                   3492:     big=0.0; 
                   3493:     for (i=j;i<=n;i++) { 
                   3494:       sum=a[i][j]; 
                   3495:       for (k=1;k<j;k++) 
                   3496:        sum -= a[i][k]*a[k][j]; 
                   3497:       a[i][j]=sum; 
                   3498:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3499:        big=dum; 
                   3500:        imax=i; 
                   3501:       } 
                   3502:     } 
                   3503:     if (j != imax) { 
                   3504:       for (k=1;k<=n;k++) { 
                   3505:        dum=a[imax][k]; 
                   3506:        a[imax][k]=a[j][k]; 
                   3507:        a[j][k]=dum; 
                   3508:       } 
                   3509:       *d = -(*d); 
                   3510:       vv[imax]=vv[j]; 
                   3511:     } 
                   3512:     indx[j]=imax; 
                   3513:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3514:     if (j != n) { 
                   3515:       dum=1.0/(a[j][j]); 
                   3516:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3517:     } 
                   3518:   } 
                   3519:   free_vector(vv,1,n);  /* Doesn't work */
                   3520: ;
                   3521: } 
                   3522: 
                   3523: void lubksb(double **a, int n, int *indx, double b[]) 
                   3524: { 
                   3525:   int i,ii=0,ip,j; 
                   3526:   double sum; 
                   3527:  
                   3528:   for (i=1;i<=n;i++) { 
                   3529:     ip=indx[i]; 
                   3530:     sum=b[ip]; 
                   3531:     b[ip]=b[i]; 
                   3532:     if (ii) 
                   3533:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3534:     else if (sum) ii=i; 
                   3535:     b[i]=sum; 
                   3536:   } 
                   3537:   for (i=n;i>=1;i--) { 
                   3538:     sum=b[i]; 
                   3539:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3540:     b[i]=sum/a[i][i]; 
                   3541:   } 
                   3542: } 
                   3543: 
                   3544: void pstamp(FILE *fichier)
                   3545: {
1.196     brouard  3546:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3547: }
                   3548: 
                   3549: /************ Frequencies ********************/
1.214     brouard  3550: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3551:                  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
                   3552:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.126     brouard  3553: {  /* Some frequencies */
                   3554:   
1.164     brouard  3555:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3556:   int mi; /* Effective wave */
1.126     brouard  3557:   int first;
                   3558:   double ***freq; /* Frequencies */
                   3559:   double *pp, **prop;
                   3560:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
1.214     brouard  3561:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3562:   double agebegin, ageend;
                   3563:     
1.126     brouard  3564:   pp=vector(1,nlstate);
                   3565:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3566:   strcpy(fileresp,"P_");
                   3567:   strcat(fileresp,fileresu);
1.213     brouard  3568:   /*strcat(fileresphtm,fileresu);*/
1.126     brouard  3569:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3570:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3571:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3572:     exit(0);
                   3573:   }
1.214     brouard  3574: 
1.213     brouard  3575:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3576:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3577:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3578:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3579:     fflush(ficlog);
                   3580:     exit(70); 
                   3581:   }
1.214     brouard  3582:   else{
                   3583:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3584: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3585: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3586:          fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3587:   }
                   3588:     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);
                   3589:     
                   3590:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3591:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3592:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3593:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3594:     fflush(ficlog);
                   3595:     exit(70); 
                   3596:   }
                   3597:   else{
                   3598:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3599: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3600: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3601:          fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3602:   }
                   3603:   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);
                   3604: 
1.126     brouard  3605:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3606:   j1=0;
                   3607:   
                   3608:   j=cptcoveff;
                   3609:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3610: 
                   3611:   first=1;
                   3612: 
1.214     brouard  3613:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
1.126     brouard  3614:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3615:        scanf("%d", i);*/
                   3616:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3617:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3618:          for(m=iagemin; m <= iagemax+3; m++)
                   3619:            freq[i][jk][m]=0;
1.143     brouard  3620:       
                   3621:       for (i=1; i<=nlstate; i++)  
                   3622:        for(m=iagemin; m <= iagemax+3; m++)
                   3623:          prop[i][m]=0;
1.126     brouard  3624:       
                   3625:       dateintsum=0;
                   3626:       k2cpt=0;
1.214     brouard  3627:       for (i=1; i<=imx; i++) { /* For each individual i */
1.126     brouard  3628:        bool=1;
1.210     brouard  3629:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3630:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3631:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3632:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3633:               bool=0;
1.198     brouard  3634:               /* 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", 
                   3635:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3636:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3637:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3638:             } 
1.210     brouard  3639:        } /* cptcovn > 0 */
1.214     brouard  3640: 
1.126     brouard  3641:        if (bool==1){
1.214     brouard  3642:          /* for(m=firstpass; m<=lastpass; m++){ */
                   3643:          for(mi=1; mi<wav[i];mi++){
                   3644:            m=mw[mi][i];
                   3645:            /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
                   3646:               and mw[mi+1][i]. dh depends on stepm. */
                   3647:            agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3648:            ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
                   3649:            if(m >=firstpass && m <=lastpass){
                   3650:              k2=anint[m][i]+(mint[m][i]/12.);
                   3651:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3652:              if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3653:              if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3654:              if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
                   3655:                prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
1.126     brouard  3656:              if (m<lastpass) {
1.214     brouard  3657:                /* if(s[m][i]==4 && s[m+1][i]==4) */
                   3658:                /*   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]); */
                   3659:                if(s[m][i]==-1)
                   3660:                  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.));
                   3661:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
                   3662:                /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
                   3663:                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  3664:              }
1.214     brouard  3665:            }  
                   3666:            if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
                   3667:              dateintsum=dateintsum+k2;
                   3668:              k2cpt++;
                   3669:              /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3670:            }
                   3671:            /*}*/
1.210     brouard  3672:          } /* end m */
                   3673:        } /* end bool */
                   3674:       } /* end i = 1 to imx */
1.126     brouard  3675:        
                   3676:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3677:       pstamp(ficresp);
                   3678:       if  (cptcovn>0) {
                   3679:        fprintf(ficresp, "\n#********** Variable "); 
1.214     brouard  3680:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3681:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.213     brouard  3682:        for (z1=1; z1<=cptcoveff; z1++){
                   3683:          fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3684:          fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3685:          fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.213     brouard  3686:        }
                   3687:          fprintf(ficresp, "**********\n#");
1.214     brouard  3688:        fprintf(ficresphtm, "**********</h3>\n");
                   3689:        fprintf(ficresphtmfr, "**********</h3>\n");
1.143     brouard  3690:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3691:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3692:        fprintf(ficlog, "**********\n");
1.126     brouard  3693:       }
1.214     brouard  3694:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.213     brouard  3695:       for(i=1; i<=nlstate;i++) {
1.126     brouard  3696:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
1.213     brouard  3697:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3698:       }
1.126     brouard  3699:       fprintf(ficresp, "\n");
1.213     brouard  3700:       fprintf(ficresphtm, "\n");
1.126     brouard  3701:       
1.214     brouard  3702:       /* Header of frequency table by age */
                   3703:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3704:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   3705:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3706:        for(m=-1; m <=nlstate+ndeath; m++){
                   3707:          if(jk!=0 && m!=0)
                   3708:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3709:        }
                   3710:       }
                   3711:       fprintf(ficresphtmfr, "\n");
                   3712:       
                   3713:       /* For each age */
1.126     brouard  3714:       for(i=iagemin; i <= iagemax+3; i++){
1.213     brouard  3715:        fprintf(ficresphtm,"<tr>");
1.214     brouard  3716:        if(i==iagemax+1){
                   3717:          fprintf(ficlog,"1");
                   3718:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3719:        }else if(i==iagemax+2){
                   3720:          fprintf(ficlog,"0");
                   3721:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3722:        }else if(i==iagemax+3){
1.126     brouard  3723:          fprintf(ficlog,"Total");
1.214     brouard  3724:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.126     brouard  3725:        }else{
                   3726:          if(first==1){
                   3727:            first=0;
                   3728:            printf("See log file for details...\n");
                   3729:          }
1.214     brouard  3730:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
1.126     brouard  3731:          fprintf(ficlog,"Age %d", i);
                   3732:        }
                   3733:        for(jk=1; jk <=nlstate ; jk++){
                   3734:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3735:            pp[jk] += freq[jk][m][i]; 
                   3736:        }
                   3737:        for(jk=1; jk <=nlstate ; jk++){
                   3738:          for(m=-1, pos=0; m <=0 ; m++)
                   3739:            pos += freq[jk][m][i];
                   3740:          if(pp[jk]>=1.e-10){
                   3741:            if(first==1){
1.132     brouard  3742:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3743:            }
                   3744:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3745:          }else{
                   3746:            if(first==1)
                   3747:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3748:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3749:          }
                   3750:        }
                   3751: 
                   3752:        for(jk=1; jk <=nlstate ; jk++){
                   3753:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3754:            pp[jk] += freq[jk][m][i];
                   3755:        }       
                   3756:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3757:          pos += pp[jk];
                   3758:          posprop += prop[jk][i];
                   3759:        }
                   3760:        for(jk=1; jk <=nlstate ; jk++){
                   3761:          if(pos>=1.e-5){
                   3762:            if(first==1)
                   3763:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3764:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3765:          }else{
                   3766:            if(first==1)
                   3767:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3768:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3769:          }
                   3770:          if( i <= iagemax){
                   3771:            if(pos>=1.e-5){
                   3772:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.213     brouard  3773:              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  3774:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3775:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3776:            }
1.213     brouard  3777:            else{
1.126     brouard  3778:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
1.213     brouard  3779:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
                   3780:            }
1.126     brouard  3781:          }
                   3782:        }
                   3783:        
1.214     brouard  3784:        for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3785:          for(m=-1; m <=nlstate+ndeath; m++){
                   3786:            if(freq[jk][m][i] !=0 ) { /* minimizing output */
                   3787:              if(first==1){
                   3788:                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3789:              }
1.126     brouard  3790:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3791:            }
1.214     brouard  3792:            if(jk!=0 && m!=0)
                   3793:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
                   3794:          }
                   3795:        }
                   3796:        fprintf(ficresphtmfr,"</tr>\n ");
1.213     brouard  3797:        if(i <= iagemax){
1.126     brouard  3798:          fprintf(ficresp,"\n");
1.213     brouard  3799:          fprintf(ficresphtm,"</tr>\n");
                   3800:        }
1.126     brouard  3801:        if(first==1)
                   3802:          printf("Others in log...\n");
                   3803:        fprintf(ficlog,"\n");
1.210     brouard  3804:       } /* end loop i */
1.213     brouard  3805:       fprintf(ficresphtm,"</table>\n");
1.214     brouard  3806:       fprintf(ficresphtmfr,"</table>\n");
1.145     brouard  3807:       /*}*/
1.210     brouard  3808:   } /* end j1 */
1.126     brouard  3809:   dateintmean=dateintsum/k2cpt; 
                   3810:  
                   3811:   fclose(ficresp);
1.213     brouard  3812:   fclose(ficresphtm);
1.214     brouard  3813:   fclose(ficresphtmfr);
1.126     brouard  3814:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3815:   free_vector(pp,1,nlstate);
                   3816:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3817:   /* End of Freq */
                   3818: }
                   3819: 
                   3820: /************ Prevalence ********************/
                   3821: 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)
                   3822: {  
                   3823:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3824:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3825:      We still use firstpass and lastpass as another selection.
                   3826:   */
                   3827:  
1.164     brouard  3828:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3829:   int mi; /* Effective wave */
                   3830:   int iage;
                   3831:   double agebegin, ageend;
1.164     brouard  3832: 
                   3833:   double **prop;
                   3834:   double posprop; 
1.126     brouard  3835:   double  y2; /* in fractional years */
                   3836:   int iagemin, iagemax;
1.145     brouard  3837:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3838: 
                   3839:   iagemin= (int) agemin;
                   3840:   iagemax= (int) agemax;
                   3841:   /*pp=vector(1,nlstate);*/
                   3842:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3843:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3844:   j1=0;
                   3845:   
1.145     brouard  3846:   /*j=cptcoveff;*/
1.126     brouard  3847:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3848:   
1.145     brouard  3849:   first=1;
                   3850:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
1.214     brouard  3851:     for (i=1; i<=nlstate; i++)  
                   3852:       for(iage=iagemin; iage <= iagemax+3; iage++)
                   3853:        prop[i][iage]=0.0;
                   3854:     
                   3855:     for (i=1; i<=imx; i++) { /* Each individual */
                   3856:       bool=1;
                   3857:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3858:        for (z1=1; z1<=cptcoveff; z1++) 
                   3859:          if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   3860:            bool=0;
                   3861:       } 
                   3862:       if (bool==1) { 
                   3863:        /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   3864:        for(mi=1; mi<wav[i];mi++){
                   3865:          m=mw[mi][i];
                   3866:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3867:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   3868:          if(m >=firstpass && m <=lastpass){
1.126     brouard  3869:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3870:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3871:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3872:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3873:              if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
1.214     brouard  3874:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
1.126     brouard  3875:                /*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]]);*/
1.214     brouard  3876:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   3877:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3878:              } /* end valid statuses */ 
                   3879:            } /* end selection of dates */
1.126     brouard  3880:          } /* end selection of waves */
1.214     brouard  3881:        } /* end effective waves */
                   3882:       } /* end bool */
                   3883:     }
                   3884:     for(i=iagemin; i <= iagemax+3; i++){  
                   3885:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3886:        posprop += prop[jk][i]; 
                   3887:       } 
                   3888:       
                   3889:       for(jk=1; jk <=nlstate ; jk++){      
                   3890:        if( i <=  iagemax){ 
                   3891:          if(posprop>=1.e-5){ 
                   3892:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   3893:          } else{
                   3894:            if(first==1){
                   3895:              first=0;
                   3896:              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]);
1.145     brouard  3897:            }
1.214     brouard  3898:          }
                   3899:        } 
                   3900:       }/* end jk */ 
                   3901:     }/* end i */ 
1.145     brouard  3902:     /*} *//* end i1 */
                   3903:   } /* end j1 */
1.126     brouard  3904:   
                   3905:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3906:   /*free_vector(pp,1,nlstate);*/
                   3907:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3908: }  /* End of prevalence */
                   3909: 
                   3910: /************* Waves Concatenation ***************/
                   3911: 
                   3912: 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)
                   3913: {
                   3914:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3915:      Death is a valid wave (if date is known).
                   3916:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3917:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3918:      and mw[mi+1][i]. dh depends on stepm.
                   3919:      */
                   3920: 
                   3921:   int i, mi, m;
                   3922:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3923:      double sum=0., jmean=0.;*/
1.217   ! brouard  3924:   int first, firstwo, firsthree;
1.126     brouard  3925:   int j, k=0,jk, ju, jl;
                   3926:   double sum=0.;
                   3927:   first=0;
1.214     brouard  3928:   firstwo=0;
1.217   ! brouard  3929:   firsthree=0;
1.164     brouard  3930:   jmin=100000;
1.126     brouard  3931:   jmax=-1;
                   3932:   jmean=0.;
1.214     brouard  3933:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  3934:     mi=0;
                   3935:     m=firstpass;
1.214     brouard  3936:     while(s[m][i] <= nlstate){  /* a live state */
1.216     brouard  3937:       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  3938:        mw[++mi][i]=m;
1.216     brouard  3939:       }
                   3940:       if(m >=lastpass){
                   3941:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
1.217   ! brouard  3942:          if(firsthree == 0){
        !          3943:            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);
        !          3944:            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.\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);
        !          3945:            firsthree=1;
        !          3946:          }else{
        !          3947:            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.\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);
        !          3948:          }
1.216     brouard  3949:          mw[++mi][i]=m;
                   3950:        }
                   3951:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   3952:          nbwarn++;
                   3953:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   3954:            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);
                   3955:            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);
                   3956:          }
                   3957:          break;
                   3958:        }
1.126     brouard  3959:        break;
1.216     brouard  3960:       }
1.126     brouard  3961:       else
                   3962:        m++;
                   3963:     }/* end while */
1.216     brouard  3964:     
                   3965:     /* After last pass */
1.214     brouard  3966:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  3967:       mi++;    /* Death is another wave */
                   3968:       /* if(mi==0)  never been interviewed correctly before death */
                   3969:         /* Only death is a correct wave */
                   3970:       mw[mi][i]=m;
1.216     brouard  3971:     }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 */
                   3972:       /* m++; */
                   3973:       /* mi++; */
                   3974:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   3975:       /* mw[mi][i]=m; */
                   3976:       nberr++;
1.214     brouard  3977:       if(firstwo==0){
1.216     brouard  3978:        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 );
                   3979:        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.\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 );
1.214     brouard  3980:        firstwo=1;
1.216     brouard  3981:       }else if(firstwo==1){
                   3982:        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.\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 );
1.214     brouard  3983:       }
1.126     brouard  3984:     }
                   3985:     wav[i]=mi;
                   3986:     if(mi==0){
                   3987:       nbwarn++;
                   3988:       if(first==0){
                   3989:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3990:        first=1;
                   3991:       }
                   3992:       if(first==1){
                   3993:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3994:       }
                   3995:     } /* end mi==0 */
                   3996:   } /* End individuals */
1.214     brouard  3997:   /* wav and mw are no more changed */
1.126     brouard  3998: 
1.214     brouard  3999:   
1.126     brouard  4000:   for(i=1; i<=imx; i++){
                   4001:     for(mi=1; mi<wav[i];mi++){
                   4002:       if (stepm <=0)
                   4003:        dh[mi][i]=1;
                   4004:       else{
                   4005:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4006:          if (agedc[i] < 2*AGESUP) {
                   4007:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4008:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4009:            else if(j<0){
                   4010:              nberr++;
                   4011:              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]);
                   4012:              j=1; /* Temporary Dangerous patch */
                   4013:              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);
                   4014:              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]);
                   4015:              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);
                   4016:            }
                   4017:            k=k+1;
                   4018:            if (j >= jmax){
                   4019:              jmax=j;
                   4020:              ijmax=i;
                   4021:            }
                   4022:            if (j <= jmin){
                   4023:              jmin=j;
                   4024:              ijmin=i;
                   4025:            }
                   4026:            sum=sum+j;
                   4027:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4028:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4029:          }
                   4030:        }
                   4031:        else{
                   4032:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   4033: /*       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]); */
                   4034: 
                   4035:          k=k+1;
                   4036:          if (j >= jmax) {
                   4037:            jmax=j;
                   4038:            ijmax=i;
                   4039:          }
                   4040:          else if (j <= jmin){
                   4041:            jmin=j;
                   4042:            ijmin=i;
                   4043:          }
                   4044:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4045:          /*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]);*/
                   4046:          if(j<0){
                   4047:            nberr++;
                   4048:            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]);
                   4049:            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]);
                   4050:          }
                   4051:          sum=sum+j;
                   4052:        }
                   4053:        jk= j/stepm;
                   4054:        jl= j -jk*stepm;
                   4055:        ju= j -(jk+1)*stepm;
                   4056:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4057:          if(jl==0){
                   4058:            dh[mi][i]=jk;
                   4059:            bh[mi][i]=0;
                   4060:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  4061:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  4062:            dh[mi][i]=jk+1;
                   4063:            bh[mi][i]=ju;
                   4064:          }
                   4065:        }else{
                   4066:          if(jl <= -ju){
                   4067:            dh[mi][i]=jk;
                   4068:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4069:                                 * is higher than the multiple of stepm and negative otherwise.
                   4070:                                 */
                   4071:          }
                   4072:          else{
                   4073:            dh[mi][i]=jk+1;
                   4074:            bh[mi][i]=ju;
                   4075:          }
                   4076:          if(dh[mi][i]==0){
                   4077:            dh[mi][i]=1; /* At least one step */
                   4078:            bh[mi][i]=ju; /* At least one step */
                   4079:            /*  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);*/
                   4080:          }
                   4081:        } /* end if mle */
                   4082:       }
                   4083:     } /* end wave */
                   4084:   }
                   4085:   jmean=sum/k;
                   4086:   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  4087:   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  4088:  }
                   4089: 
                   4090: /*********** Tricode ****************************/
1.145     brouard  4091: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4092: {
1.144     brouard  4093:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4094:   /*     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  4095:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  4096:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  4097:    * nbcode[Tvar[j]][1]= 
1.144     brouard  4098:   */
1.130     brouard  4099: 
1.145     brouard  4100:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4101:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4102:   int cptcode=0; /* Modality max of covariates j */
                   4103:   int modmincovj=0; /* Modality min of covariates j */
                   4104: 
                   4105: 
1.126     brouard  4106:   cptcoveff=0; 
                   4107:  
1.144     brouard  4108:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4109: 
1.145     brouard  4110:   /* Loop on covariates without age and products */
1.186     brouard  4111:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  4112:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  4113:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  4114:                               modality of this covariate Vj*/ 
1.145     brouard  4115:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4116:                                    * If product of Vn*Vm, still boolean *:
                   4117:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4118:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4119:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  4120:                                      modality of the nth covariate of individual i. */
1.145     brouard  4121:       if (ij > modmaxcovj)
                   4122:         modmaxcovj=ij; 
                   4123:       else if (ij < modmincovj) 
                   4124:        modmincovj=ij; 
                   4125:       if ((ij < -1) && (ij > NCOVMAX)){
                   4126:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4127:        exit(1);
                   4128:       }else
1.136     brouard  4129:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  4130:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  4131:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  4132:       /* getting the maximum value of the modality of the covariate
                   4133:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4134:         female is 1, then modmaxcovj=1.*/
1.192     brouard  4135:     } /* end for loop on individuals i */
1.145     brouard  4136:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  4137:     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  4138:     cptcode=modmaxcovj;
1.137     brouard  4139:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  4140:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  4141:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4142:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4143:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4144:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   4145:        if( k != -1){
                   4146:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   4147:                             covariate for which somebody answered excluding 
                   4148:                             undefined. Usually 2: 0 and 1. */
                   4149:        }
                   4150:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   4151:                             covariate for which somebody answered including 
                   4152:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  4153:       }
                   4154:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   4155:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  4156:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  4157: 
1.136     brouard  4158:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  4159:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4160:        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  4161:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  4162:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4163:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4164:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  4165:        nbcode[Tvar[j]][ij]=k;
                   4166:        nbcode[Tvar[j]][1]=0;
                   4167:        nbcode[Tvar[j]][2]=1;
                   4168:        nbcode[Tvar[j]][3]=2;
1.197     brouard  4169:        To be continued (not working yet).
1.145     brouard  4170:     */
1.197     brouard  4171:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4172:     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*/
                   4173:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  4174:          break;
                   4175:        }
                   4176:        ij++;
1.197     brouard  4177:        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  4178:        cptcode = ij; /* New max modality for covar j */
                   4179:     } /* end of loop on modality i=-1 to 1 or more */
                   4180:       
                   4181:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4182:     /*         /\*recode from 0 *\/ */
                   4183:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4184:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4185:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4186:     /*         } */
                   4187:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4188:     /*         if (ij > ncodemax[j]) { */
                   4189:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4190:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4191:     /*           break; */
                   4192:     /*         } */
                   4193:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4194:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4195:   
1.145     brouard  4196:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  4197:   
1.187     brouard  4198:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  4199:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4200:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  4201:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  4202:  } 
1.126     brouard  4203: 
1.192     brouard  4204:  ij=0;
1.145     brouard  4205:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4206:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  4207:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  4208:      ij++;
1.145     brouard  4209:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4210:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  4211:    }else{
                   4212:        /* Tvaraff[ij]=0; */
                   4213:    }
1.126     brouard  4214:  }
1.192     brouard  4215:  /* ij--; */
1.144     brouard  4216:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  4217: 
1.126     brouard  4218: }
                   4219: 
1.145     brouard  4220: 
1.126     brouard  4221: /*********** Health Expectancies ****************/
                   4222: 
1.127     brouard  4223: 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  4224: 
                   4225: {
                   4226:   /* Health expectancies, no variances */
1.164     brouard  4227:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4228:   int nhstepma, nstepma; /* Decreasing with age */
                   4229:   double age, agelim, hf;
                   4230:   double ***p3mat;
                   4231:   double eip;
                   4232: 
                   4233:   pstamp(ficreseij);
                   4234:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4235:   fprintf(ficreseij,"# Age");
                   4236:   for(i=1; i<=nlstate;i++){
                   4237:     for(j=1; j<=nlstate;j++){
                   4238:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4239:     }
                   4240:     fprintf(ficreseij," e%1d. ",i);
                   4241:   }
                   4242:   fprintf(ficreseij,"\n");
                   4243: 
                   4244:   
                   4245:   if(estepm < stepm){
                   4246:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4247:   }
                   4248:   else  hstepm=estepm;   
                   4249:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4250:    * This is mainly to measure the difference between two models: for example
                   4251:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4252:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4253:    * progression in between and thus overestimating or underestimating according
                   4254:    * to the curvature of the survival function. If, for the same date, we 
                   4255:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4256:    * to compare the new estimate of Life expectancy with the same linear 
                   4257:    * hypothesis. A more precise result, taking into account a more precise
                   4258:    * curvature will be obtained if estepm is as small as stepm. */
                   4259: 
                   4260:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4261:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4262:      nhstepm is the number of hstepm from age to agelim 
                   4263:      nstepm is the number of stepm from age to agelin. 
                   4264:      Look at hpijx to understand the reason of that which relies in memory size
                   4265:      and note for a fixed period like estepm months */
                   4266:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4267:      survival function given by stepm (the optimization length). Unfortunately it
                   4268:      means that if the survival funtion is printed only each two years of age and if
                   4269:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4270:      results. So we changed our mind and took the option of the best precision.
                   4271:   */
                   4272:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4273: 
                   4274:   agelim=AGESUP;
                   4275:   /* If stepm=6 months */
                   4276:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4277:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4278:     
                   4279: /* nhstepm age range expressed in number of stepm */
                   4280:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4281:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4282:   /* if (stepm >= YEARM) hstepm=1;*/
                   4283:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4284:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4285: 
                   4286:   for (age=bage; age<=fage; age ++){ 
                   4287:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4288:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4289:     /* if (stepm >= YEARM) hstepm=1;*/
                   4290:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4291: 
                   4292:     /* If stepm=6 months */
                   4293:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4294:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4295:     
                   4296:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4297:     
                   4298:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4299:     
                   4300:     printf("%d|",(int)age);fflush(stdout);
                   4301:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4302:     
                   4303:     /* Computing expectancies */
                   4304:     for(i=1; i<=nlstate;i++)
                   4305:       for(j=1; j<=nlstate;j++)
                   4306:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4307:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4308:          
                   4309:          /* 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]);*/
                   4310: 
                   4311:        }
                   4312: 
                   4313:     fprintf(ficreseij,"%3.0f",age );
                   4314:     for(i=1; i<=nlstate;i++){
                   4315:       eip=0;
                   4316:       for(j=1; j<=nlstate;j++){
                   4317:        eip +=eij[i][j][(int)age];
                   4318:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4319:       }
                   4320:       fprintf(ficreseij,"%9.4f", eip );
                   4321:     }
                   4322:     fprintf(ficreseij,"\n");
                   4323:     
                   4324:   }
                   4325:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4326:   printf("\n");
                   4327:   fprintf(ficlog,"\n");
                   4328:   
                   4329: }
                   4330: 
1.127     brouard  4331: 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  4332: 
                   4333: {
                   4334:   /* Covariances of health expectancies eij and of total life expectancies according
                   4335:    to initial status i, ei. .
                   4336:   */
                   4337:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4338:   int nhstepma, nstepma; /* Decreasing with age */
                   4339:   double age, agelim, hf;
                   4340:   double ***p3matp, ***p3matm, ***varhe;
                   4341:   double **dnewm,**doldm;
                   4342:   double *xp, *xm;
                   4343:   double **gp, **gm;
                   4344:   double ***gradg, ***trgradg;
                   4345:   int theta;
                   4346: 
                   4347:   double eip, vip;
                   4348: 
                   4349:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4350:   xp=vector(1,npar);
                   4351:   xm=vector(1,npar);
                   4352:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4353:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4354:   
                   4355:   pstamp(ficresstdeij);
                   4356:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4357:   fprintf(ficresstdeij,"# Age");
                   4358:   for(i=1; i<=nlstate;i++){
                   4359:     for(j=1; j<=nlstate;j++)
                   4360:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4361:     fprintf(ficresstdeij," e%1d. ",i);
                   4362:   }
                   4363:   fprintf(ficresstdeij,"\n");
                   4364: 
                   4365:   pstamp(ficrescveij);
                   4366:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4367:   fprintf(ficrescveij,"# Age");
                   4368:   for(i=1; i<=nlstate;i++)
                   4369:     for(j=1; j<=nlstate;j++){
                   4370:       cptj= (j-1)*nlstate+i;
                   4371:       for(i2=1; i2<=nlstate;i2++)
                   4372:        for(j2=1; j2<=nlstate;j2++){
                   4373:          cptj2= (j2-1)*nlstate+i2;
                   4374:          if(cptj2 <= cptj)
                   4375:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4376:        }
                   4377:     }
                   4378:   fprintf(ficrescveij,"\n");
                   4379:   
                   4380:   if(estepm < stepm){
                   4381:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4382:   }
                   4383:   else  hstepm=estepm;   
                   4384:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4385:    * This is mainly to measure the difference between two models: for example
                   4386:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4387:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4388:    * progression in between and thus overestimating or underestimating according
                   4389:    * to the curvature of the survival function. If, for the same date, we 
                   4390:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4391:    * to compare the new estimate of Life expectancy with the same linear 
                   4392:    * hypothesis. A more precise result, taking into account a more precise
                   4393:    * curvature will be obtained if estepm is as small as stepm. */
                   4394: 
                   4395:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4396:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4397:      nhstepm is the number of hstepm from age to agelim 
                   4398:      nstepm is the number of stepm from age to agelin. 
                   4399:      Look at hpijx to understand the reason of that which relies in memory size
                   4400:      and note for a fixed period like estepm months */
                   4401:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4402:      survival function given by stepm (the optimization length). Unfortunately it
                   4403:      means that if the survival funtion is printed only each two years of age and if
                   4404:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4405:      results. So we changed our mind and took the option of the best precision.
                   4406:   */
                   4407:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4408: 
                   4409:   /* If stepm=6 months */
                   4410:   /* nhstepm age range expressed in number of stepm */
                   4411:   agelim=AGESUP;
                   4412:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4413:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4414:   /* if (stepm >= YEARM) hstepm=1;*/
                   4415:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4416:   
                   4417:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4418:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4419:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4420:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4421:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4422:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4423: 
                   4424:   for (age=bage; age<=fage; age ++){ 
                   4425:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4426:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4427:     /* if (stepm >= YEARM) hstepm=1;*/
                   4428:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4429: 
                   4430:     /* If stepm=6 months */
                   4431:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4432:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4433:     
                   4434:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4435: 
                   4436:     /* Computing  Variances of health expectancies */
                   4437:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4438:        decrease memory allocation */
                   4439:     for(theta=1; theta <=npar; theta++){
                   4440:       for(i=1; i<=npar; i++){ 
                   4441:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4442:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   4443:       }
                   4444:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4445:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   4446:   
                   4447:       for(j=1; j<= nlstate; j++){
                   4448:        for(i=1; i<=nlstate; i++){
                   4449:          for(h=0; h<=nhstepm-1; h++){
                   4450:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4451:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4452:          }
                   4453:        }
                   4454:       }
                   4455:      
                   4456:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   4457:        for(h=0; h<=nhstepm-1; h++){
                   4458:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4459:        }
                   4460:     }/* End theta */
                   4461:     
                   4462:     
                   4463:     for(h=0; h<=nhstepm-1; h++)
                   4464:       for(j=1; j<=nlstate*nlstate;j++)
                   4465:        for(theta=1; theta <=npar; theta++)
                   4466:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4467:     
                   4468: 
                   4469:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   4470:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   4471:        varhe[ij][ji][(int)age] =0.;
                   4472: 
                   4473:      printf("%d|",(int)age);fflush(stdout);
                   4474:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4475:      for(h=0;h<=nhstepm-1;h++){
                   4476:       for(k=0;k<=nhstepm-1;k++){
                   4477:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4478:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4479:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4480:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4481:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   4482:       }
                   4483:     }
                   4484: 
                   4485:     /* Computing expectancies */
                   4486:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4487:     for(i=1; i<=nlstate;i++)
                   4488:       for(j=1; j<=nlstate;j++)
                   4489:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4490:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4491:          
                   4492:          /* 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]);*/
                   4493: 
                   4494:        }
                   4495: 
                   4496:     fprintf(ficresstdeij,"%3.0f",age );
                   4497:     for(i=1; i<=nlstate;i++){
                   4498:       eip=0.;
                   4499:       vip=0.;
                   4500:       for(j=1; j<=nlstate;j++){
                   4501:        eip += eij[i][j][(int)age];
                   4502:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4503:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4504:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   4505:       }
                   4506:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4507:     }
                   4508:     fprintf(ficresstdeij,"\n");
                   4509: 
                   4510:     fprintf(ficrescveij,"%3.0f",age );
                   4511:     for(i=1; i<=nlstate;i++)
                   4512:       for(j=1; j<=nlstate;j++){
                   4513:        cptj= (j-1)*nlstate+i;
                   4514:        for(i2=1; i2<=nlstate;i2++)
                   4515:          for(j2=1; j2<=nlstate;j2++){
                   4516:            cptj2= (j2-1)*nlstate+i2;
                   4517:            if(cptj2 <= cptj)
                   4518:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4519:          }
                   4520:       }
                   4521:     fprintf(ficrescveij,"\n");
                   4522:    
                   4523:   }
                   4524:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4525:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4526:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4527:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4528:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4529:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4530:   printf("\n");
                   4531:   fprintf(ficlog,"\n");
                   4532: 
                   4533:   free_vector(xm,1,npar);
                   4534:   free_vector(xp,1,npar);
                   4535:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4536:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4537:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4538: }
                   4539: 
                   4540: /************ Variance ******************/
1.209     brouard  4541:  void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126     brouard  4542: {
                   4543:   /* Variance of health expectancies */
                   4544:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4545:   /* double **newm;*/
1.169     brouard  4546:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4547:   
                   4548:   int movingaverage();
1.126     brouard  4549:   double **dnewm,**doldm;
                   4550:   double **dnewmp,**doldmp;
                   4551:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4552:   int k;
1.126     brouard  4553:   double *xp;
                   4554:   double **gp, **gm;  /* for var eij */
                   4555:   double ***gradg, ***trgradg; /*for var eij */
                   4556:   double **gradgp, **trgradgp; /* for var p point j */
                   4557:   double *gpp, *gmp; /* for var p point j */
                   4558:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4559:   double ***p3mat;
                   4560:   double age,agelim, hf;
                   4561:   double ***mobaverage;
                   4562:   int theta;
                   4563:   char digit[4];
                   4564:   char digitp[25];
                   4565: 
                   4566:   char fileresprobmorprev[FILENAMELENGTH];
                   4567: 
                   4568:   if(popbased==1){
                   4569:     if(mobilav!=0)
1.201     brouard  4570:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4571:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4572:   }
                   4573:   else 
1.201     brouard  4574:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4575: 
                   4576:   if (mobilav!=0) {
                   4577:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4578:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4579:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4580:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4581:     }
                   4582:   }
                   4583: 
1.201     brouard  4584:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4585:   sprintf(digit,"%-d",ij);
                   4586:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4587:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4588:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4589:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4590:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4591:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4592:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4593:   }
                   4594:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4595:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4596:   pstamp(ficresprobmorprev);
                   4597:   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);
                   4598:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4599:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4600:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4601:     for(i=1; i<=nlstate;i++)
                   4602:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4603:   }  
                   4604:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4605:   
1.126     brouard  4606:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4607:   fprintf(ficgp,"\nunset title \n");
                   4608: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4609:   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");
                   4610:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4611: /*   } */
                   4612:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4613:   pstamp(ficresvij);
                   4614:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4615:   if(popbased==1)
1.128     brouard  4616:     fprintf(ficresvij,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d\n",mobilav);
1.126     brouard  4617:   else
                   4618:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4619:   fprintf(ficresvij,"# Age");
                   4620:   for(i=1; i<=nlstate;i++)
                   4621:     for(j=1; j<=nlstate;j++)
                   4622:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4623:   fprintf(ficresvij,"\n");
                   4624: 
                   4625:   xp=vector(1,npar);
                   4626:   dnewm=matrix(1,nlstate,1,npar);
                   4627:   doldm=matrix(1,nlstate,1,nlstate);
                   4628:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4629:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4630: 
                   4631:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4632:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4633:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4634:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4635:   
                   4636:   if(estepm < stepm){
                   4637:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4638:   }
                   4639:   else  hstepm=estepm;   
                   4640:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4641:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4642:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4643:      nstepm is the number of stepm from age to agelim. 
1.209     brouard  4644:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4645:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4646:      survival function given by stepm (the optimization length). Unfortunately it
                   4647:      means that if the survival funtion is printed every two years of age and if
                   4648:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4649:      results. So we changed our mind and took the option of the best precision.
                   4650:   */
                   4651:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4652:   agelim = AGESUP;
                   4653:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4654:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4655:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4656:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4657:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4658:     gp=matrix(0,nhstepm,1,nlstate);
                   4659:     gm=matrix(0,nhstepm,1,nlstate);
                   4660: 
                   4661: 
                   4662:     for(theta=1; theta <=npar; theta++){
                   4663:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4664:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4665:       }
1.209     brouard  4666: 
                   4667:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4668: 
                   4669:       if (popbased==1) {
                   4670:        if(mobilav ==0){
                   4671:          for(i=1; i<=nlstate;i++)
                   4672:            prlim[i][i]=probs[(int)age][i][ij];
                   4673:        }else{ /* mobilav */ 
                   4674:          for(i=1; i<=nlstate;i++)
                   4675:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4676:        }
                   4677:       }
                   4678:   
1.209     brouard  4679:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4680:       for(j=1; j<= nlstate; j++){
                   4681:        for(h=0; h<=nhstepm; h++){
                   4682:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4683:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4684:        }
                   4685:       }
1.209     brouard  4686:       /* Next for computing probability of death (h=1 means
1.126     brouard  4687:          computed over hstepm matrices product = hstepm*stepm months) 
                   4688:          as a weighted average of prlim.
                   4689:       */
                   4690:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4691:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4692:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4693:       }    
                   4694:       /* end probability of death */
                   4695: 
                   4696:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4697:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4698: 
                   4699:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4700:  
                   4701:       if (popbased==1) {
                   4702:        if(mobilav ==0){
                   4703:          for(i=1; i<=nlstate;i++)
                   4704:            prlim[i][i]=probs[(int)age][i][ij];
                   4705:        }else{ /* mobilav */ 
                   4706:          for(i=1; i<=nlstate;i++)
                   4707:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4708:        }
                   4709:       }
                   4710: 
1.209     brouard  4711:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4712: 
1.128     brouard  4713:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4714:        for(h=0; h<=nhstepm; h++){
                   4715:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4716:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4717:        }
                   4718:       }
                   4719:       /* This for computing probability of death (h=1 means
                   4720:          computed over hstepm matrices product = hstepm*stepm months) 
                   4721:          as a weighted average of prlim.
                   4722:       */
                   4723:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4724:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4725:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4726:       }    
                   4727:       /* end probability of death */
                   4728: 
                   4729:       for(j=1; j<= nlstate; j++) /* vareij */
                   4730:        for(h=0; h<=nhstepm; h++){
                   4731:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4732:        }
                   4733: 
                   4734:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4735:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4736:       }
                   4737: 
                   4738:     } /* End theta */
                   4739: 
                   4740:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4741: 
                   4742:     for(h=0; h<=nhstepm; h++) /* veij */
                   4743:       for(j=1; j<=nlstate;j++)
                   4744:        for(theta=1; theta <=npar; theta++)
                   4745:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4746: 
                   4747:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4748:       for(theta=1; theta <=npar; theta++)
                   4749:        trgradgp[j][theta]=gradgp[theta][j];
                   4750:   
                   4751: 
                   4752:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4753:     for(i=1;i<=nlstate;i++)
                   4754:       for(j=1;j<=nlstate;j++)
                   4755:        vareij[i][j][(int)age] =0.;
                   4756: 
                   4757:     for(h=0;h<=nhstepm;h++){
                   4758:       for(k=0;k<=nhstepm;k++){
                   4759:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4760:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4761:        for(i=1;i<=nlstate;i++)
                   4762:          for(j=1;j<=nlstate;j++)
                   4763:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4764:       }
                   4765:     }
                   4766:   
                   4767:     /* pptj */
                   4768:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4769:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4770:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4771:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4772:        varppt[j][i]=doldmp[j][i];
                   4773:     /* end ppptj */
                   4774:     /*  x centered again */
1.209     brouard  4775: 
                   4776:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4777:  
                   4778:     if (popbased==1) {
                   4779:       if(mobilav ==0){
                   4780:        for(i=1; i<=nlstate;i++)
                   4781:          prlim[i][i]=probs[(int)age][i][ij];
                   4782:       }else{ /* mobilav */ 
                   4783:        for(i=1; i<=nlstate;i++)
                   4784:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4785:       }
                   4786:     }
                   4787:              
                   4788:     /* This for computing probability of death (h=1 means
                   4789:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4790:        as a weighted average of prlim.
                   4791:     */
1.209     brouard  4792:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4793:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4794:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4795:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4796:     }    
                   4797:     /* end probability of death */
                   4798: 
                   4799:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4800:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4801:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4802:       for(i=1; i<=nlstate;i++){
                   4803:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4804:       }
                   4805:     } 
                   4806:     fprintf(ficresprobmorprev,"\n");
                   4807: 
                   4808:     fprintf(ficresvij,"%.0f ",age );
                   4809:     for(i=1; i<=nlstate;i++)
                   4810:       for(j=1; j<=nlstate;j++){
                   4811:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4812:       }
                   4813:     fprintf(ficresvij,"\n");
                   4814:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4815:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4816:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4817:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4818:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4819:   } /* End age */
                   4820:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4821:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4822:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4823:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4824:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4825:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4826:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4827:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4828:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4829: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4830: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4831: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4832:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4833:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4834:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4835:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201     brouard  4836:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.199     brouard  4837:   /*  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  4838: */
1.199     brouard  4839: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4840:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4841: 
                   4842:   free_vector(xp,1,npar);
                   4843:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4844:   free_matrix(dnewm,1,nlstate,1,npar);
                   4845:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4846:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4847:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4848:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4849:   fclose(ficresprobmorprev);
                   4850:   fflush(ficgp);
                   4851:   fflush(fichtm); 
                   4852: }  /* end varevsij */
                   4853: 
                   4854: /************ Variance of prevlim ******************/
1.209     brouard  4855:  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  4856: {
1.205     brouard  4857:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4858:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4859: 
1.126     brouard  4860:   double **dnewm,**doldm;
                   4861:   int i, j, nhstepm, hstepm;
                   4862:   double *xp;
                   4863:   double *gp, *gm;
                   4864:   double **gradg, **trgradg;
1.208     brouard  4865:   double **mgm, **mgp;
1.126     brouard  4866:   double age,agelim;
                   4867:   int theta;
                   4868:   
                   4869:   pstamp(ficresvpl);
                   4870:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4871:   fprintf(ficresvpl,"# Age");
                   4872:   for(i=1; i<=nlstate;i++)
                   4873:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4874:   fprintf(ficresvpl,"\n");
                   4875: 
                   4876:   xp=vector(1,npar);
                   4877:   dnewm=matrix(1,nlstate,1,npar);
                   4878:   doldm=matrix(1,nlstate,1,nlstate);
                   4879:   
                   4880:   hstepm=1*YEARM; /* Every year of age */
                   4881:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4882:   agelim = AGESUP;
                   4883:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4884:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4885:     if (stepm >= YEARM) hstepm=1;
                   4886:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4887:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4888:     mgp=matrix(1,npar,1,nlstate);
                   4889:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4890:     gp=vector(1,nlstate);
                   4891:     gm=vector(1,nlstate);
                   4892: 
                   4893:     for(theta=1; theta <=npar; theta++){
                   4894:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4895:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4896:       }
1.209     brouard  4897:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4898:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4899:       else
                   4900:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4901:       for(i=1;i<=nlstate;i++){
1.126     brouard  4902:        gp[i] = prlim[i][i];
1.208     brouard  4903:        mgp[theta][i] = prlim[i][i];
                   4904:       }
1.126     brouard  4905:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4906:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4907:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4908:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4909:       else
                   4910:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4911:       for(i=1;i<=nlstate;i++){
1.126     brouard  4912:        gm[i] = prlim[i][i];
1.208     brouard  4913:        mgm[theta][i] = prlim[i][i];
                   4914:       }
1.126     brouard  4915:       for(i=1;i<=nlstate;i++)
                   4916:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  4917:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4918:     } /* End theta */
                   4919: 
                   4920:     trgradg =matrix(1,nlstate,1,npar);
                   4921: 
                   4922:     for(j=1; j<=nlstate;j++)
                   4923:       for(theta=1; theta <=npar; theta++)
                   4924:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  4925:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4926:     /*   printf("\nmgm mgp %d ",(int)age); */
                   4927:     /*   for(j=1; j<=nlstate;j++){ */
                   4928:     /*         printf(" %d ",j); */
                   4929:     /*         for(theta=1; theta <=npar; theta++) */
                   4930:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   4931:     /*         printf("\n "); */
                   4932:     /*   } */
                   4933:     /* } */
                   4934:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4935:     /*   printf("\n gradg %d ",(int)age); */
                   4936:     /*   for(j=1; j<=nlstate;j++){ */
                   4937:     /*         printf("%d ",j); */
                   4938:     /*         for(theta=1; theta <=npar; theta++) */
                   4939:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   4940:     /*         printf("\n "); */
                   4941:     /*   } */
                   4942:     /* } */
1.126     brouard  4943: 
                   4944:     for(i=1;i<=nlstate;i++)
                   4945:       varpl[i][(int)age] =0.;
1.209     brouard  4946:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4947:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4948:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4949:     }else{
1.126     brouard  4950:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4951:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4952:     }
1.126     brouard  4953:     for(i=1;i<=nlstate;i++)
                   4954:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4955: 
                   4956:     fprintf(ficresvpl,"%.0f ",age );
                   4957:     for(i=1; i<=nlstate;i++)
                   4958:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4959:     fprintf(ficresvpl,"\n");
                   4960:     free_vector(gp,1,nlstate);
                   4961:     free_vector(gm,1,nlstate);
1.208     brouard  4962:     free_matrix(mgm,1,npar,1,nlstate);
                   4963:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4964:     free_matrix(gradg,1,npar,1,nlstate);
                   4965:     free_matrix(trgradg,1,nlstate,1,npar);
                   4966:   } /* End age */
                   4967: 
                   4968:   free_vector(xp,1,npar);
                   4969:   free_matrix(doldm,1,nlstate,1,npar);
                   4970:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4971: 
                   4972: }
                   4973: 
                   4974: /************ Variance of one-step probabilities  ******************/
                   4975: 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[])
                   4976: {
1.164     brouard  4977:   int i, j=0,  k1, l1, tj;
1.126     brouard  4978:   int k2, l2, j1,  z1;
1.164     brouard  4979:   int k=0, l;
1.145     brouard  4980:   int first=1, first1, first2;
1.126     brouard  4981:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4982:   double **dnewm,**doldm;
                   4983:   double *xp;
                   4984:   double *gp, *gm;
                   4985:   double **gradg, **trgradg;
                   4986:   double **mu;
1.164     brouard  4987:   double age, cov[NCOVMAX+1];
1.126     brouard  4988:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4989:   int theta;
                   4990:   char fileresprob[FILENAMELENGTH];
                   4991:   char fileresprobcov[FILENAMELENGTH];
                   4992:   char fileresprobcor[FILENAMELENGTH];
                   4993:   double ***varpij;
                   4994: 
1.201     brouard  4995:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4996:   strcat(fileresprob,fileres);
                   4997:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4998:     printf("Problem with resultfile: %s\n", fileresprob);
                   4999:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5000:   }
1.201     brouard  5001:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  5002:   strcat(fileresprobcov,fileresu);
1.126     brouard  5003:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5004:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   5005:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5006:   }
1.201     brouard  5007:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  5008:   strcat(fileresprobcor,fileresu);
1.126     brouard  5009:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5010:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   5011:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5012:   }
                   5013:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5014:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5015:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5016:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5017:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5018:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5019:   pstamp(ficresprob);
                   5020:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5021:   fprintf(ficresprob,"# Age");
                   5022:   pstamp(ficresprobcov);
                   5023:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5024:   fprintf(ficresprobcov,"# Age");
                   5025:   pstamp(ficresprobcor);
                   5026:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5027:   fprintf(ficresprobcor,"# Age");
                   5028: 
                   5029: 
                   5030:   for(i=1; i<=nlstate;i++)
                   5031:     for(j=1; j<=(nlstate+ndeath);j++){
                   5032:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5033:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5034:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5035:     }  
                   5036:  /* fprintf(ficresprob,"\n");
                   5037:   fprintf(ficresprobcov,"\n");
                   5038:   fprintf(ficresprobcor,"\n");
                   5039:  */
1.131     brouard  5040:   xp=vector(1,npar);
1.126     brouard  5041:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5042:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5043:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5044:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5045:   first=1;
                   5046:   fprintf(ficgp,"\n# Routine varprob");
                   5047:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5048:   fprintf(fichtm,"\n");
                   5049: 
1.200     brouard  5050:   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  5051:   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);
                   5052:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5053: and drawn. It helps understanding how is the covariance between two incidences.\
                   5054:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   5055:   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. \
                   5056: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5057: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5058: standard deviations wide on each axis. <br>\
                   5059:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5060:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5061: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5062: 
                   5063:   cov[1]=1;
1.145     brouard  5064:   /* tj=cptcoveff; */
                   5065:   tj = (int) pow(2,cptcoveff);
1.126     brouard  5066:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5067:   j1=0;
1.145     brouard  5068:   for(j1=1; j1<=tj;j1++){
                   5069:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   5070:     /*j1++;*/
1.126     brouard  5071:       if  (cptcovn>0) {
                   5072:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  5073:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5074:        fprintf(ficresprob, "**********\n#\n");
                   5075:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  5076:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5077:        fprintf(ficresprobcov, "**********\n#\n");
                   5078:        
                   5079:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  5080:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5081:        fprintf(ficgp, "**********\n#\n");
                   5082:        
                   5083:        
                   5084:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  5085:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5086:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5087:        
                   5088:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  5089:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  5090:        fprintf(ficresprobcor, "**********\n#");    
                   5091:       }
                   5092:       
1.145     brouard  5093:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5094:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5095:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5096:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  5097:       for (age=bage; age<=fage; age ++){ 
                   5098:        cov[2]=age;
1.187     brouard  5099:        if(nagesqr==1)
                   5100:          cov[3]= age*age;
1.126     brouard  5101:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  5102:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5103:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  5104:                                                         * 1  1 1 1 1
                   5105:                                                         * 2  2 1 1 1
                   5106:                                                         * 3  1 2 1 1
                   5107:                                                         */
                   5108:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  5109:        }
1.186     brouard  5110:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  5111:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  5112:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  5113:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  5114:        
                   5115:     
                   5116:        for(theta=1; theta <=npar; theta++){
                   5117:          for(i=1; i<=npar; i++)
                   5118:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   5119:          
                   5120:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5121:          
                   5122:          k=0;
                   5123:          for(i=1; i<= (nlstate); i++){
                   5124:            for(j=1; j<=(nlstate+ndeath);j++){
                   5125:              k=k+1;
                   5126:              gp[k]=pmmij[i][j];
                   5127:            }
                   5128:          }
                   5129:          
                   5130:          for(i=1; i<=npar; i++)
                   5131:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   5132:     
                   5133:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5134:          k=0;
                   5135:          for(i=1; i<=(nlstate); i++){
                   5136:            for(j=1; j<=(nlstate+ndeath);j++){
                   5137:              k=k+1;
                   5138:              gm[k]=pmmij[i][j];
                   5139:            }
                   5140:          }
                   5141:      
                   5142:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5143:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5144:        }
                   5145: 
                   5146:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5147:          for(theta=1; theta <=npar; theta++)
                   5148:            trgradg[j][theta]=gradg[theta][j];
                   5149:        
                   5150:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5151:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   5152: 
                   5153:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   5154:        
                   5155:        k=0;
                   5156:        for(i=1; i<=(nlstate); i++){
                   5157:          for(j=1; j<=(nlstate+ndeath);j++){
                   5158:            k=k+1;
                   5159:            mu[k][(int) age]=pmmij[i][j];
                   5160:          }
                   5161:        }
                   5162:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5163:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5164:            varpij[i][j][(int)age] = doldm[i][j];
                   5165: 
                   5166:        /*printf("\n%d ",(int)age);
                   5167:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5168:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5169:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5170:          }*/
                   5171: 
                   5172:        fprintf(ficresprob,"\n%d ",(int)age);
                   5173:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5174:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   5175: 
                   5176:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5177:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5178:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5179:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5180:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5181:        }
                   5182:        i=0;
                   5183:        for (k=1; k<=(nlstate);k++){
                   5184:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  5185:            i++;
1.126     brouard  5186:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5187:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5188:            for (j=1; j<=i;j++){
1.145     brouard  5189:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  5190:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5191:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5192:            }
                   5193:          }
                   5194:        }/* end of loop for state */
                   5195:       } /* end of loop for age */
1.145     brouard  5196:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5197:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5198:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5199:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5200:       
1.126     brouard  5201:       /* Confidence intervalle of pij  */
                   5202:       /*
1.131     brouard  5203:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  5204:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5205:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5206:        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);
                   5207:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5208:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5209:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5210:       */
                   5211: 
                   5212:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  5213:       first1=1;first2=2;
1.126     brouard  5214:       for (k2=1; k2<=(nlstate);k2++){
                   5215:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5216:          if(l2==k2) continue;
                   5217:          j=(k2-1)*(nlstate+ndeath)+l2;
                   5218:          for (k1=1; k1<=(nlstate);k1++){
                   5219:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5220:              if(l1==k1) continue;
                   5221:              i=(k1-1)*(nlstate+ndeath)+l1;
                   5222:              if(i<=j) continue;
                   5223:              for (age=bage; age<=fage; age ++){ 
                   5224:                if ((int)age %5==0){
                   5225:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5226:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5227:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5228:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   5229:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   5230:                  c12=cv12/sqrt(v1*v2);
                   5231:                  /* Computing eigen value of matrix of covariance */
                   5232:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5233:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  5234:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  5235:                    if(first2==1){
                   5236:                      first1=0;
                   5237:                    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);
                   5238:                    }
                   5239:                    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);
                   5240:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5241:                    /* lc2=fabs(lc2); */
1.135     brouard  5242:                  }
                   5243: 
1.126     brouard  5244:                  /* Eigen vectors */
                   5245:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5246:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   5247:                  v21=(lc1-v1)/cv12*v11;
                   5248:                  v12=-v21;
                   5249:                  v22=v11;
                   5250:                  tnalp=v21/v11;
                   5251:                  if(first1==1){
                   5252:                    first1=0;
                   5253:                    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);
                   5254:                  }
                   5255:                  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);
                   5256:                  /*printf(fignu*/
                   5257:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5258:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5259:                  if(first==1){
                   5260:                    first=0;
1.200     brouard  5261:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  5262:                    fprintf(ficgp,"\nset parametric;unset label");
                   5263:                    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  5264:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  5265:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  5266:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   5267: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   5268:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   5269:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5270:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  5271:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  5272:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  5273:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5274:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5275:                    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",\
                   5276:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   5277:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5278:                  }else{
                   5279:                    first=0;
                   5280:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5281:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5282:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5283:                    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",\
                   5284:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   5285:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5286:                  }/* if first */
                   5287:                } /* age mod 5 */
                   5288:              } /* end loop age */
1.201     brouard  5289:              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  5290:              first=1;
                   5291:            } /*l12 */
                   5292:          } /* k12 */
                   5293:        } /*l1 */
                   5294:       }/* k1 */
1.169     brouard  5295:       /* } */ /* loop covariates */
1.126     brouard  5296:   }
                   5297:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5298:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5299:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5300:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5301:   free_vector(xp,1,npar);
                   5302:   fclose(ficresprob);
                   5303:   fclose(ficresprobcov);
                   5304:   fclose(ficresprobcor);
                   5305:   fflush(ficgp);
                   5306:   fflush(fichtmcov);
                   5307: }
                   5308: 
                   5309: 
                   5310: /******************* Printing html file ***********/
1.201     brouard  5311: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5312:                  int lastpass, int stepm, int weightopt, char model[],\
                   5313:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217   ! brouard  5314:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5315:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5316:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5317:   int jj1, k1, i1, cpt;
                   5318: 
                   5319:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5320:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5321: </ul>");
1.214     brouard  5322:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5323:    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",
                   5324:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5325:    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  5326:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5327:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5328:    fprintf(fichtm,"\
                   5329:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5330:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5331:    fprintf(fichtm,"\
1.217   ! brouard  5332:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
        !          5333:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
        !          5334:    fprintf(fichtm,"\
1.126     brouard  5335:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5336:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5337:    fprintf(fichtm,"\
1.217   ! brouard  5338:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
        !          5339:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
        !          5340:    fprintf(fichtm,"\
1.211     brouard  5341:  - (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  5342:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5343:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5344:    if(prevfcast==1){
                   5345:      fprintf(fichtm,"\
                   5346:  - Prevalence projections by age and states:                           \
1.201     brouard  5347:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5348:    }
1.126     brouard  5349: 
                   5350: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   5351: 
1.145     brouard  5352:  m=pow(2,cptcoveff);
1.126     brouard  5353:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5354: 
                   5355:  jj1=0;
                   5356:  for(k1=1; k1<=m;k1++){
1.192     brouard  5357:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5358:      jj1++;
                   5359:      if (cptcovn > 0) {
                   5360:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  5361:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  5362:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5363:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  5364:        }
1.126     brouard  5365:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5366:      }
1.201     brouard  5367:      /* aij, bij */
1.211     brouard  5368:      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> \
                   5369: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  5370:      /* Pij */
1.211     brouard  5371:      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  5372: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  5373:      /* Quasi-incidences */
1.211     brouard  5374:      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  5375:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211     brouard  5376:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5377: 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  5378: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   5379:      /* Survival functions (period) in state j */
                   5380:      for(cpt=1; cpt<=nlstate;cpt++){
                   5381:        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> \
                   5382: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   5383:      }
                   5384:      /* State specific survival functions (period) */
                   5385:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  5386:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  5387:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   5388:  <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);
                   5389:      }
                   5390:      /* Period (stable) prevalence in each health state */
                   5391:      for(cpt=1; cpt<=nlstate;cpt++){
1.217   ! brouard  5392:        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  5393: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   5394:      }
1.217   ! brouard  5395:     if(backcast==1){
        !          5396:      /* Period (stable) back prevalence in each health state */
        !          5397:      for(cpt=1; cpt<=nlstate;cpt++){
        !          5398:        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> \
        !          5399: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
        !          5400:      }
        !          5401:     }
1.211     brouard  5402:     if(prevfcast==1){
                   5403:       /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5404:       for(cpt=1; cpt<=nlstate;cpt++){
1.214     brouard  5405:        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  5406: <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  5407:       }
                   5408:     }
                   5409: 
1.126     brouard  5410:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  5411:        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  5412: <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  5413:      }
1.192     brouard  5414:    /* } /\* end i1 *\/ */
1.126     brouard  5415:  }/* End k1 */
                   5416:  fprintf(fichtm,"</ul>");
                   5417: 
                   5418:  fprintf(fichtm,"\
                   5419: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5420:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5421:  - 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  5422: But because parameters are usually highly correlated (a higher incidence of disability \
                   5423: and a higher incidence of recovery can give very close observed transition) it might \
                   5424: be very useful to look not only at linear confidence intervals estimated from the \
                   5425: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5426: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5427: covariance matrix of the one-step probabilities. \
                   5428: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5429: 
1.193     brouard  5430:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5431:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  5432:  fprintf(fichtm,"\
                   5433:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5434:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5435: 
                   5436:  fprintf(fichtm,"\
                   5437:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5438:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  5439:  fprintf(fichtm,"\
                   5440:  - 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): \
                   5441:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5442:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  5443:  fprintf(fichtm,"\
                   5444:  - (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): \
                   5445:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5446:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  5447:  fprintf(fichtm,"\
1.128     brouard  5448:  - 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  5449:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  5450:  fprintf(fichtm,"\
1.128     brouard  5451:  - 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  5452:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  5453:  fprintf(fichtm,"\
                   5454:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  5455:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5456: 
                   5457: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5458: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5459: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5460: /*     <br>",fileres,fileres,fileres,fileres); */
                   5461: /*  else  */
                   5462: /*    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); */
                   5463:  fflush(fichtm);
                   5464:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5465: 
1.145     brouard  5466:  m=pow(2,cptcoveff);
1.126     brouard  5467:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5468: 
                   5469:  jj1=0;
                   5470:  for(k1=1; k1<=m;k1++){
1.192     brouard  5471:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5472:      jj1++;
                   5473:      if (cptcovn > 0) {
                   5474:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5475:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  5476:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5477:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5478:      }
                   5479:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5480:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  5481: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   5482: <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  5483:      }
                   5484:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5485: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5486: true period expectancies (those weighted with period prevalences are also\
                   5487:  drawn in addition to the population based expectancies computed using\
1.205     brouard  5488:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   5489: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  5490:    /* } /\* end i1 *\/ */
1.126     brouard  5491:  }/* End k1 */
                   5492:  fprintf(fichtm,"</ul>");
                   5493:  fflush(fichtm);
                   5494: }
                   5495: 
                   5496: /******************* Gnuplot file **************/
1.211     brouard  5497:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126     brouard  5498: 
                   5499:   char dirfileres[132],optfileres[132];
1.164     brouard  5500:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5501:   int lv=0, vlv=0, kl=0;
1.130     brouard  5502:   int ng=0;
1.201     brouard  5503:   int vpopbased;
1.126     brouard  5504: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5505: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5506: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5507: /*   } */
                   5508: 
                   5509:   /*#ifdef windows */
                   5510:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5511:     /*#endif */
                   5512:   m=pow(2,cptcoveff);
                   5513: 
1.202     brouard  5514:   /* Contribution to likelihood */
                   5515:   /* Plot the probability implied in the likelihood */
                   5516:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5517:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5518:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5519:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5520: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5521:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5522: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5523:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5524:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5525:     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  5526:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5527:     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  5528:     for (i=1; i<= nlstate ; i ++) {
                   5529:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5530:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214     brouard  5531:       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  5532:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.214     brouard  5533:        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  5534:       }
                   5535:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5536:     }
                   5537:     /* 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 */             
                   5538:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5539:     /* 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  5540:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5541:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5542: 
1.126     brouard  5543:   strcpy(dirfileres,optionfilefiname);
                   5544:   strcpy(optfileres,"vpl");
                   5545:  /* 1eme*/
1.211     brouard  5546:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
                   5547:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
                   5548:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5549:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
                   5550:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5551:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5552:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5553:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5554:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5555:        vlv= nbcode[Tvaraff[lv]][lv];
                   5556:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5557:       }
                   5558:       fprintf(ficgp,"\n#\n");
                   5559: 
1.201     brouard  5560:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5561:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5562:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5563: set ylabel \"Probability\" \n\
1.199     brouard  5564: set ter svg size 640, 480\n\
1.201     brouard  5565: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5566: 
                   5567:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5568:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5569:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5570:      }
1.201     brouard  5571:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5572:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5573:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5574:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5575:      } 
1.201     brouard  5576:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
1.126     brouard  5577:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5578:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5579:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5580:      }  
1.201     brouard  5581:      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));
                   5582:      fprintf(ficgp,"\nset out \n");
                   5583:     } /* k1 */
                   5584:   } /* cpt */
1.126     brouard  5585:   /*2 eme*/
                   5586:   for (k1=1; k1<= m ; k1 ++) { 
1.211     brouard  5587:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5588:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5589:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5590:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5591:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5592:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5593:        vlv= nbcode[Tvaraff[lv]][lv];
                   5594:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5595:       }
                   5596:       fprintf(ficgp,"\n#\n");
                   5597: 
1.201     brouard  5598:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5599:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5600:       if(vpopbased==0)
                   5601:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5602:       else
                   5603:        fprintf(ficgp,"\nreplot ");
                   5604:       for (i=1; i<= nlstate+1 ; i ++) {
                   5605:        k=2*i;
                   5606:        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);
                   5607:        for (j=1; j<= nlstate+1 ; j ++) {
                   5608:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5609:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5610:        }   
                   5611:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5612:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5613:        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);
                   5614:        for (j=1; j<= nlstate+1 ; j ++) {
                   5615:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5616:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5617:        }   
                   5618:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5619:        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);
                   5620:        for (j=1; j<= nlstate+1 ; j ++) {
                   5621:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5622:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5623:        }   
                   5624:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5625:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5626:       } /* state */
                   5627:     } /* vpopbased */
                   5628:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5629:   } /* k1 */
1.211     brouard  5630: 
                   5631: 
1.126     brouard  5632:   /*3eme*/
                   5633:   for (k1=1; k1<= m ; k1 ++) { 
                   5634:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5635:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5636:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5637:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5638:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5639:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5640:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5641:        vlv= nbcode[Tvaraff[lv]][lv];
                   5642:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5643:       }
                   5644:       fprintf(ficgp,"\n#\n");
                   5645: 
1.126     brouard  5646:       /*       k=2+nlstate*(2*cpt-2); */
                   5647:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5648:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5649:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5650: 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  5651:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5652:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5653:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5654:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5655:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5656:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5657:        
                   5658:       */
                   5659:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5660:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
1.126     brouard  5661:        /*      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);*/
                   5662:        
                   5663:       } 
1.201     brouard  5664:       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  5665:     }
                   5666:   }
                   5667:   
1.201     brouard  5668:   /* Survival functions (period) from state i in state j by initial state i */
                   5669:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5670:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5671:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5672:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5673:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5674:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5675:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5676:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5677:        vlv= nbcode[Tvaraff[lv]][lv];
                   5678:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5679:       }
                   5680:       fprintf(ficgp,"\n#\n");
                   5681: 
1.201     brouard  5682:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5683:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5684: set ter svg size 640, 480\n\
                   5685: unset log y\n\
                   5686: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5687:       k=3;
1.201     brouard  5688:       for (i=1; i<= nlstate ; i ++){
1.217   ! brouard  5689:        if(i==1){
1.201     brouard  5690:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.217   ! brouard  5691:        }else{
1.201     brouard  5692:          fprintf(ficgp,", '' ");
1.217   ! brouard  5693:        }
1.201     brouard  5694:        l=(nlstate+ndeath)*(i-1)+1;
                   5695:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5696:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5697:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5698:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5699:       } /* nlstate */
                   5700:       fprintf(ficgp,"\nset out\n");
                   5701:     } /* end cpt state*/ 
                   5702:   } /* end covariate */  
                   5703: 
                   5704:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5705:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5706:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5707:       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  5708:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5709:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5710:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5711:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5712:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5713:        vlv= nbcode[Tvaraff[lv]][lv];
                   5714:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5715:       }
                   5716:       fprintf(ficgp,"\n#\n");
                   5717: 
1.201     brouard  5718:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5719:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5720: set ter svg size 640, 480\n\
                   5721: unset log y\n\
                   5722: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5723:       k=3;
1.201     brouard  5724:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5725:        if(j==1)
                   5726:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5727:        else
                   5728:          fprintf(ficgp,", '' ");
                   5729:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5730:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5731:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5732:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5733:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5734:       } /* nlstate */
                   5735:       fprintf(ficgp,", '' ");
                   5736:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5737:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5738:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5739:        if(j < nlstate)
                   5740:          fprintf(ficgp,"$%d +",k+l);
                   5741:        else
                   5742:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5743:       }
                   5744:       fprintf(ficgp,"\nset out\n");
                   5745:     } /* end cpt state*/ 
                   5746:   } /* end covariate */  
                   5747: 
1.202     brouard  5748:   /* CV preval stable (period) for each covariate */
1.211     brouard  5749:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  5750:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5751:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   5752:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5753:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5754:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5755:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5756:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5757:        vlv= nbcode[Tvaraff[lv]][lv];
                   5758:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5759:       }
                   5760:       fprintf(ficgp,"\n#\n");
                   5761: 
1.201     brouard  5762:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5763:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5764: set ter svg size 640, 480\n\
1.126     brouard  5765: unset log y\n\
1.153     brouard  5766: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5767:       k=3; /* Offset */
1.153     brouard  5768:       for (i=1; i<= nlstate ; i ++){
                   5769:        if(i==1)
1.201     brouard  5770:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5771:        else
                   5772:          fprintf(ficgp,", '' ");
1.154     brouard  5773:        l=(nlstate+ndeath)*(i-1)+1;
                   5774:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5775:        for (j=2; j<= nlstate ; j ++)
                   5776:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5777:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5778:       } /* nlstate */
1.201     brouard  5779:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5780:     } /* end cpt state*/ 
                   5781:   } /* end covariate */  
1.201     brouard  5782: 
1.217   ! brouard  5783:     /* CV back preval stable (period) for each covariate */
        !          5784:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
        !          5785:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
        !          5786:       fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
        !          5787:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5788:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5789:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5790:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5791:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5792:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5793:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5794:       }
        !          5795:       fprintf(ficgp,"\n#\n");
        !          5796: 
        !          5797:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
        !          5798:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
        !          5799: set ter svg size 640, 480\n\
        !          5800: unset log y\n\
        !          5801: plot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          5802:       k=3; /* Offset */
        !          5803:       for (i=1; i<= nlstate ; i ++){
        !          5804:        if(i==1)
        !          5805:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
        !          5806:        else
        !          5807:          fprintf(ficgp,", '' ");
        !          5808:        l=(nlstate+ndeath)*(i-1)+1;
        !          5809:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /* a vérifier */
        !          5810:        for (j=2; j<= nlstate ; j ++)
        !          5811:          fprintf(ficgp,"+$%d",k+l+j-1);
        !          5812:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
        !          5813:       } /* nlstate */
        !          5814:       fprintf(ficgp,"\nset out\n");
        !          5815:     } /* end cpt state*/ 
        !          5816:   } /* end covariate */  
        !          5817: 
1.211     brouard  5818:   if(prevfcast==1){
                   5819:   /* Projection from cross-sectional to stable (period) for each covariate */
                   5820: 
                   5821:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   5822:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5823:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   5824:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   5825:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5826:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5827:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5828:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5829:          vlv= nbcode[Tvaraff[lv]][lv];
                   5830:          fprintf(ficgp," V%d=%d ",k,vlv);
                   5831:        }
                   5832:        fprintf(ficgp,"\n#\n");
                   5833:        
                   5834:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   5835:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   5836:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   5837: set ter svg size 640, 480\n\
                   5838: unset log y\n\
                   5839: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5840:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   5841:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5842:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5843:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5844:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5845:          if(i==1){
                   5846:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   5847:          }else{
                   5848:            fprintf(ficgp,",\\\n '' ");
                   5849:          }
                   5850:          if(cptcoveff ==0){ /* No covariate */
                   5851:            fprintf(ficgp," u 2:("); /* Age is in 2 */
                   5852:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   5853:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   5854:            if(i==nlstate+1)
                   5855:              fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
                   5856:                        2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5857:            else
                   5858:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
                   5859:                      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5860:          }else{
                   5861:            fprintf(ficgp,"u 6:(("); /* Age is in 6 */
                   5862:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5863:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5864:            kl=0;
                   5865:            for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
                   5866:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5867:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5868:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5869:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5870:              vlv= nbcode[Tvaraff[lv]][lv];
                   5871:              kl++;
                   5872:              /* 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 *\/ */
                   5873:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5874:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5875:              /* ''  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*/
                   5876:              if(k==cptcoveff)
                   5877:                if(i==nlstate+1)
                   5878:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5879:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5880:                else
                   5881:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5882:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5883:              else{
                   5884:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
                   5885:                kl++;
                   5886:              }
                   5887:            } /* end covariate */
                   5888:          } /* end if covariate */
                   5889:        } /* nlstate */
                   5890:        fprintf(ficgp,"\nset out\n");
                   5891:       } /* end cpt state*/
                   5892:     } /* end covariate */
                   5893:   } /* End if prevfcast */
                   5894: 
                   5895: 
1.126     brouard  5896:   /* proba elementaires */
1.187     brouard  5897:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5898:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5899:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5900:     for(k=1; k <=(nlstate+ndeath); k++){
                   5901:       if (k != i) {
1.187     brouard  5902:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5903:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5904:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5905:          jk++; 
                   5906:        }
1.187     brouard  5907:        fprintf(ficgp,"\n");
1.126     brouard  5908:       }
                   5909:     }
                   5910:    }
1.187     brouard  5911:   fprintf(ficgp,"##############\n#\n");
                   5912: 
1.145     brouard  5913:   /*goto avoid;*/
1.200     brouard  5914:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5915:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5916:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5917:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5918:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5919:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5920:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5921:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5922:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5923:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5924:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5925:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5926:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5927:   fprintf(ficgp,"#\n");
1.201     brouard  5928:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5929:      fprintf(ficgp,"# ng=%d\n",ng);
                   5930:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5931:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5932:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5933:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5934:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5935:        if (ng==1){
                   5936:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5937:         fprintf(ficgp,"\nunset log y");
                   5938:        }else if (ng==2){
                   5939:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5940:         fprintf(ficgp,"\nset log y");
                   5941:        }else if (ng==3){
1.126     brouard  5942:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5943:         fprintf(ficgp,"\nset log y");
                   5944:        }else
                   5945:         fprintf(ficgp,"\nunset title ");
                   5946:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5947:        i=1;
                   5948:        for(k2=1; k2<=nlstate; k2++) {
                   5949:         k3=i;
                   5950:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5951:           if (k != k2){
1.201     brouard  5952:             switch( ng) {
                   5953:             case 1:
1.187     brouard  5954:               if(nagesqr==0)
1.201     brouard  5955:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5956:               else /* nagesqr =1 */
1.201     brouard  5957:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5958:               break;
                   5959:             case 2: /* ng=2 */
1.187     brouard  5960:               if(nagesqr==0)
                   5961:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5962:               else /* nagesqr =1 */
1.201     brouard  5963:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5964:               break;
                   5965:             case 3:
                   5966:               if(nagesqr==0)
                   5967:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5968:               else /* nagesqr =1 */
                   5969:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5970:               break;
                   5971:             }
1.141     brouard  5972:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5973:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5974:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5975:               if(ij <=cptcovage) { /* Bug valgrind */
                   5976:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5977:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5978:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5979:                   ij++;
                   5980:                 }
1.186     brouard  5981:               }
                   5982:               else
1.198     brouard  5983:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5984:             }
1.217   ! brouard  5985:           }else{
        !          5986:             i=i-ncovmodel;
        !          5987:             if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
        !          5988:               fprintf(ficgp," (1.");
        !          5989:           }
        !          5990:           
        !          5991:           if(ng != 1){
        !          5992:             fprintf(ficgp,")/(1");
1.126     brouard  5993:             
1.217   ! brouard  5994:             for(k1=1; k1 <=nlstate; k1++){ 
        !          5995:               if(nagesqr==0)
        !          5996:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
        !          5997:               else /* nagesqr =1 */
        !          5998:                 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);
        !          5999:               
        !          6000:               ij=1;
        !          6001:               for(j=3; j <=ncovmodel-nagesqr; j++){
        !          6002:                 if(ij <=cptcovage) { /* Bug valgrind */
        !          6003:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
        !          6004:                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
        !          6005:                     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
        !          6006:                     ij++;
1.197     brouard  6007:                   }
1.186     brouard  6008:                 }
1.217   ! brouard  6009:                 else
        !          6010:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6011:               }
                   6012:               fprintf(ficgp,")");
1.217   ! brouard  6013:             }
        !          6014:             fprintf(ficgp,")");
        !          6015:             if(ng ==2)
        !          6016:               fprintf(ficgp," t \"p%d%d\" ", k2,k);
        !          6017:             else /* ng= 3 */
        !          6018:               fprintf(ficgp," t \"i%d%d\" ", k2,k);
        !          6019:           }else{ /* end ng <> 1 */
        !          6020:             if( k !=k2) /* logit p11 is hard to draw */
1.201     brouard  6021:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  6022:           }
1.217   ! brouard  6023:           if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
        !          6024:             fprintf(ficgp,",");
        !          6025:           if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
        !          6026:             fprintf(ficgp,",");
        !          6027:           i=i+ncovmodel;
1.126     brouard  6028:         } /* end k */
                   6029:        } /* end k2 */
1.201     brouard  6030:        fprintf(ficgp,"\n set out\n");
1.126     brouard  6031:      } /* end jk */
                   6032:    } /* end ng */
1.164     brouard  6033:  /* avoid: */
1.126     brouard  6034:    fflush(ficgp); 
                   6035: }  /* end gnuplot */
                   6036: 
                   6037: 
                   6038: /*************** Moving average **************/
                   6039: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   6040: 
                   6041:   int i, cpt, cptcod;
                   6042:   int modcovmax =1;
                   6043:   int mobilavrange, mob;
                   6044:   double age;
                   6045: 
                   6046:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   6047:                           a covariate has 2 modalities */
                   6048:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   6049: 
                   6050:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6051:     if(mobilav==1) mobilavrange=5; /* default */
                   6052:     else mobilavrange=mobilav;
                   6053:     for (age=bage; age<=fage; age++)
                   6054:       for (i=1; i<=nlstate;i++)
                   6055:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   6056:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6057:     /* We keep the original values on the extreme ages bage, fage and for 
                   6058:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6059:        we use a 5 terms etc. until the borders are no more concerned. 
                   6060:     */ 
                   6061:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6062:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6063:        for (i=1; i<=nlstate;i++){
                   6064:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   6065:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6066:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6067:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6068:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6069:              }
                   6070:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6071:          }
                   6072:        }
                   6073:       }/* end age */
                   6074:     }/* end mob */
                   6075:   }else return -1;
                   6076:   return 0;
                   6077: }/* End movingaverage */
                   6078: 
                   6079: 
                   6080: /************** Forecasting ******************/
1.169     brouard  6081: 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  6082:   /* proj1, year, month, day of starting projection 
                   6083:      agemin, agemax range of age
                   6084:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6085:      anproj2 year of en of projection (same day and month as proj1).
                   6086:   */
1.164     brouard  6087:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6088:   double agec; /* generic age */
                   6089:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6090:   double *popeffectif,*popcount;
                   6091:   double ***p3mat;
                   6092:   double ***mobaverage;
                   6093:   char fileresf[FILENAMELENGTH];
                   6094: 
                   6095:   agelim=AGESUP;
1.211     brouard  6096:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6097:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6098:      We still use firstpass and lastpass as another selection.
                   6099:   */
1.214     brouard  6100:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6101:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6102:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6103:  
1.201     brouard  6104:   strcpy(fileresf,"F_"); 
                   6105:   strcat(fileresf,fileresu);
1.126     brouard  6106:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6107:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6108:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6109:   }
1.215     brouard  6110:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6111:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6112: 
                   6113:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6114: 
                   6115:   if (mobilav!=0) {
                   6116:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6117:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   6118:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6119:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6120:     }
                   6121:   }
                   6122: 
                   6123:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6124:   if (stepm<=12) stepsize=1;
                   6125:   if(estepm < stepm){
                   6126:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6127:   }
                   6128:   else  hstepm=estepm;   
                   6129: 
                   6130:   hstepm=hstepm/stepm; 
                   6131:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6132:                                fractional in yp1 */
                   6133:   anprojmean=yp;
                   6134:   yp2=modf((yp1*12),&yp);
                   6135:   mprojmean=yp;
                   6136:   yp1=modf((yp2*30.5),&yp);
                   6137:   jprojmean=yp;
                   6138:   if(jprojmean==0) jprojmean=1;
                   6139:   if(mprojmean==0) jprojmean=1;
                   6140: 
                   6141:   i1=cptcoveff;
                   6142:   if (cptcovn < 1){i1=1;}
                   6143:   
                   6144:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6145:   
                   6146:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6147: 
                   6148: /*           if (h==(int)(YEARM*yearp)){ */
                   6149:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   6150:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6151:       k=k+1;
1.211     brouard  6152:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  6153:       for(j=1;j<=cptcoveff;j++) {
1.211     brouard  6154:        fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6155:       }
1.211     brouard  6156:       fprintf(ficresf," yearproj age");
1.126     brouard  6157:       for(j=1; j<=nlstate+ndeath;j++){ 
                   6158:        for(i=1; i<=nlstate;i++)              
                   6159:           fprintf(ficresf," p%d%d",i,j);
                   6160:        fprintf(ficresf," p.%d",j);
                   6161:       }
1.217   ! brouard  6162:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
1.126     brouard  6163:        fprintf(ficresf,"\n");
                   6164:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6165:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6166:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6167:          nhstepm = nhstepm/hstepm; 
                   6168:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6169:          oldm=oldms;savm=savms;
1.217   ! brouard  6170:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
1.126     brouard  6171:        
                   6172:          for (h=0; h<=nhstepm; h++){
                   6173:            if (h*hstepm/YEARM*stepm ==yearp) {
                   6174:               fprintf(ficresf,"\n");
                   6175:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6176:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6177:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6178:            } 
                   6179:            for(j=1; j<=nlstate+ndeath;j++) {
                   6180:              ppij=0.;
                   6181:              for(i=1; i<=nlstate;i++) {
                   6182:                if (mobilav==1) 
                   6183:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   6184:                else {
                   6185:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   6186:                }
                   6187:                if (h*hstepm/YEARM*stepm== yearp) {
                   6188:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   6189:                }
                   6190:              } /* end i */
                   6191:              if (h*hstepm/YEARM*stepm==yearp) {
                   6192:                fprintf(ficresf," %.3f", ppij);
                   6193:              }
                   6194:            }/* end j */
                   6195:          } /* end h */
                   6196:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6197:        } /* end agec */
                   6198:       } /* end yearp */
                   6199:     } /* end cptcod */
                   6200:   } /* end  cptcov */
                   6201:        
                   6202:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6203: 
                   6204:   fclose(ficresf);
1.215     brouard  6205:   printf("End of Computing forecasting \n");
                   6206:   fprintf(ficlog,"End of Computing forecasting\n");
                   6207: 
1.126     brouard  6208: }
                   6209: 
1.217   ! brouard  6210: /************** Back Forecasting ******************/
        !          6211: 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){
        !          6212:   /* back1, year, month, day of starting backection 
        !          6213:      agemin, agemax range of age
        !          6214:      dateprev1 dateprev2 range of dates during which prevalence is computed
        !          6215:      anback2 year of en of backection (same day and month as back1).
        !          6216:   */
        !          6217:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
        !          6218:   double agec; /* generic age */
        !          6219:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
        !          6220:   double *popeffectif,*popcount;
        !          6221:   double ***p3mat;
        !          6222:   double ***mobaverage;
        !          6223:   char fileresfb[FILENAMELENGTH];
        !          6224: 
        !          6225:   agelim=AGESUP;
        !          6226:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
        !          6227:      in each health status at the date of interview (if between dateprev1 and dateprev2).
        !          6228:      We still use firstpass and lastpass as another selection.
        !          6229:   */
        !          6230:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
        !          6231:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
        !          6232:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
        !          6233:  
        !          6234:   strcpy(fileresfb,"FB_"); 
        !          6235:   strcat(fileresfb,fileresu);
        !          6236:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
        !          6237:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
        !          6238:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
        !          6239:   }
        !          6240:   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb);
        !          6241:   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb);
        !          6242: 
        !          6243:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
        !          6244: 
        !          6245:   if (mobilav!=0) {
        !          6246:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          6247:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
        !          6248:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
        !          6249:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
        !          6250:     }
        !          6251:   }
        !          6252: 
        !          6253:   stepsize=(int) (stepm+YEARM-1)/YEARM;
        !          6254:   if (stepm<=12) stepsize=1;
        !          6255:   if(estepm < stepm){
        !          6256:     printf ("Problem %d lower than %d\n",estepm, stepm);
        !          6257:   }
        !          6258:   else  hstepm=estepm;   
        !          6259: 
        !          6260:   hstepm=hstepm/stepm; 
        !          6261:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
        !          6262:                                fractional in yp1 */
        !          6263:   anprojmean=yp;
        !          6264:   yp2=modf((yp1*12),&yp);
        !          6265:   mprojmean=yp;
        !          6266:   yp1=modf((yp2*30.5),&yp);
        !          6267:   jprojmean=yp;
        !          6268:   if(jprojmean==0) jprojmean=1;
        !          6269:   if(mprojmean==0) jprojmean=1;
        !          6270: 
        !          6271:   i1=cptcoveff;
        !          6272:   if (cptcovn < 1){i1=1;}
        !          6273:   
        !          6274:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
        !          6275:   
        !          6276:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
        !          6277: 
        !          6278: /*           if (h==(int)(YEARM*yearp)){ */
        !          6279:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
        !          6280:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
        !          6281:       k=k+1;
        !          6282:       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#");
        !          6283:       for(j=1;j<=cptcoveff;j++) {
        !          6284:        fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          6285:       }
        !          6286:       fprintf(ficresfb," yearbproj age");
        !          6287:       for(j=1; j<=nlstate+ndeath;j++){ 
        !          6288:        for(i=1; i<=nlstate;i++)              
        !          6289:           fprintf(ficresfb," p%d%d",i,j);
        !          6290:        fprintf(ficresfb," p.%d",j);
        !          6291:       }
        !          6292:       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) { 
        !          6293:      /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
        !          6294:        fprintf(ficresfb,"\n");
        !          6295:        fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);   
        !          6296:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
        !          6297:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
        !          6298:          nhstepm = nhstepm/hstepm; 
        !          6299:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          6300:          oldm=oldms;savm=savms;
        !          6301:          hbxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
        !          6302:        
        !          6303:          for (h=0; h<=nhstepm; h++){
        !          6304:            if (h*hstepm/YEARM*stepm ==yearp) {
        !          6305:               fprintf(ficresfb,"\n");
        !          6306:               for(j=1;j<=cptcoveff;j++) 
        !          6307:                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          6308:              fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm);
        !          6309:            } 
        !          6310:            for(j=1; j<=nlstate+ndeath;j++) {
        !          6311:              ppij=0.;
        !          6312:              for(i=1; i<=nlstate;i++) {
        !          6313:                if (mobilav==1) 
        !          6314:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
        !          6315:                else {
        !          6316:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
        !          6317:                }
        !          6318:                if (h*hstepm/YEARM*stepm== yearp) {
        !          6319:                  fprintf(ficresfb," %.3f", p3mat[i][j][h]);
        !          6320:                }
        !          6321:              } /* end i */
        !          6322:              if (h*hstepm/YEARM*stepm==yearp) {
        !          6323:                fprintf(ficresfb," %.3f", ppij);
        !          6324:              }
        !          6325:            }/* end j */
        !          6326:          } /* end h */
        !          6327:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          6328:        } /* end agec */
        !          6329:       } /* end yearp */
        !          6330:     } /* end cptcod */
        !          6331:   } /* end  cptcov */
        !          6332:        
        !          6333:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          6334: 
        !          6335:   fclose(ficresfb);
        !          6336:   printf("End of Computing Back forecasting \n");
        !          6337:   fprintf(ficlog,"End of Computing Back forecasting\n");
        !          6338: 
        !          6339: }
        !          6340: 
1.126     brouard  6341: /************** Forecasting *****not tested NB*************/
1.169     brouard  6342: 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  6343:   
                   6344:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6345:   int *popage;
                   6346:   double calagedatem, agelim, kk1, kk2;
                   6347:   double *popeffectif,*popcount;
                   6348:   double ***p3mat,***tabpop,***tabpopprev;
                   6349:   double ***mobaverage;
                   6350:   char filerespop[FILENAMELENGTH];
                   6351: 
                   6352:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6353:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6354:   agelim=AGESUP;
                   6355:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6356:   
                   6357:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6358:   
                   6359:   
1.201     brouard  6360:   strcpy(filerespop,"POP_"); 
                   6361:   strcat(filerespop,fileresu);
1.126     brouard  6362:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6363:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6364:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6365:   }
                   6366:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6367:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6368: 
                   6369:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6370: 
                   6371:   if (mobilav!=0) {
                   6372:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6373:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   6374:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6375:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6376:     }
                   6377:   }
                   6378: 
                   6379:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6380:   if (stepm<=12) stepsize=1;
                   6381:   
                   6382:   agelim=AGESUP;
                   6383:   
                   6384:   hstepm=1;
                   6385:   hstepm=hstepm/stepm; 
                   6386:   
                   6387:   if (popforecast==1) {
                   6388:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6389:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6390:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6391:     } 
                   6392:     popage=ivector(0,AGESUP);
                   6393:     popeffectif=vector(0,AGESUP);
                   6394:     popcount=vector(0,AGESUP);
                   6395:     
                   6396:     i=1;   
                   6397:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   6398:    
                   6399:     imx=i;
                   6400:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6401:   }
                   6402: 
                   6403:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   6404:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6405:       k=k+1;
                   6406:       fprintf(ficrespop,"\n#******");
                   6407:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6408:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6409:       }
                   6410:       fprintf(ficrespop,"******\n");
                   6411:       fprintf(ficrespop,"# Age");
                   6412:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   6413:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   6414:       
                   6415:       for (cpt=0; cpt<=0;cpt++) { 
                   6416:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6417:        
                   6418:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6419:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6420:          nhstepm = nhstepm/hstepm; 
                   6421:          
                   6422:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6423:          oldm=oldms;savm=savms;
                   6424:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6425:        
                   6426:          for (h=0; h<=nhstepm; h++){
                   6427:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6428:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6429:            } 
                   6430:            for(j=1; j<=nlstate+ndeath;j++) {
                   6431:              kk1=0.;kk2=0;
                   6432:              for(i=1; i<=nlstate;i++) {              
                   6433:                if (mobilav==1) 
                   6434:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   6435:                else {
                   6436:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   6437:                }
                   6438:              }
                   6439:              if (h==(int)(calagedatem+12*cpt)){
                   6440:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   6441:                  /*fprintf(ficrespop," %.3f", kk1);
                   6442:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   6443:              }
                   6444:            }
                   6445:            for(i=1; i<=nlstate;i++){
                   6446:              kk1=0.;
                   6447:                for(j=1; j<=nlstate;j++){
                   6448:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   6449:                }
                   6450:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   6451:            }
                   6452: 
                   6453:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   6454:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   6455:          }
                   6456:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6457:        }
                   6458:       }
                   6459:  
                   6460:   /******/
                   6461: 
                   6462:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   6463:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6464:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6465:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6466:          nhstepm = nhstepm/hstepm; 
                   6467:          
                   6468:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6469:          oldm=oldms;savm=savms;
                   6470:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6471:          for (h=0; h<=nhstepm; h++){
                   6472:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6473:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6474:            } 
                   6475:            for(j=1; j<=nlstate+ndeath;j++) {
                   6476:              kk1=0.;kk2=0;
                   6477:              for(i=1; i<=nlstate;i++) {              
                   6478:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   6479:              }
                   6480:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   6481:            }
                   6482:          }
                   6483:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6484:        }
                   6485:       }
                   6486:    } 
                   6487:   }
                   6488:  
                   6489:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6490: 
                   6491:   if (popforecast==1) {
                   6492:     free_ivector(popage,0,AGESUP);
                   6493:     free_vector(popeffectif,0,AGESUP);
                   6494:     free_vector(popcount,0,AGESUP);
                   6495:   }
                   6496:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6497:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6498:   fclose(ficrespop);
                   6499: } /* End of popforecast */
                   6500: 
                   6501: int fileappend(FILE *fichier, char *optionfich)
                   6502: {
                   6503:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   6504:     printf("Problem with file: %s\n", optionfich);
                   6505:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   6506:     return (0);
                   6507:   }
                   6508:   fflush(fichier);
                   6509:   return (1);
                   6510: }
                   6511: 
                   6512: 
                   6513: /**************** function prwizard **********************/
                   6514: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   6515: {
                   6516: 
                   6517:   /* Wizard to print covariance matrix template */
                   6518: 
1.164     brouard  6519:   char ca[32], cb[32];
                   6520:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  6521:   int numlinepar;
                   6522: 
                   6523:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6524:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6525:   for(i=1; i <=nlstate; i++){
                   6526:     jj=0;
                   6527:     for(j=1; j <=nlstate+ndeath; j++){
                   6528:       if(j==i) continue;
                   6529:       jj++;
                   6530:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6531:       printf("%1d%1d",i,j);
                   6532:       fprintf(ficparo,"%1d%1d",i,j);
                   6533:       for(k=1; k<=ncovmodel;k++){
                   6534:        /*        printf(" %lf",param[i][j][k]); */
                   6535:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6536:        printf(" 0.");
                   6537:        fprintf(ficparo," 0.");
                   6538:       }
                   6539:       printf("\n");
                   6540:       fprintf(ficparo,"\n");
                   6541:     }
                   6542:   }
                   6543:   printf("# Scales (for hessian or gradient estimation)\n");
                   6544:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6545:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6546:   for(i=1; i <=nlstate; i++){
                   6547:     jj=0;
                   6548:     for(j=1; j <=nlstate+ndeath; j++){
                   6549:       if(j==i) continue;
                   6550:       jj++;
                   6551:       fprintf(ficparo,"%1d%1d",i,j);
                   6552:       printf("%1d%1d",i,j);
                   6553:       fflush(stdout);
                   6554:       for(k=1; k<=ncovmodel;k++){
                   6555:        /*      printf(" %le",delti3[i][j][k]); */
                   6556:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6557:        printf(" 0.");
                   6558:        fprintf(ficparo," 0.");
                   6559:       }
                   6560:       numlinepar++;
                   6561:       printf("\n");
                   6562:       fprintf(ficparo,"\n");
                   6563:     }
                   6564:   }
                   6565:   printf("# Covariance matrix\n");
                   6566: /* # 121 Var(a12)\n\ */
                   6567: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6568: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6569: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6570: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6571: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6572: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6573: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6574:   fflush(stdout);
                   6575:   fprintf(ficparo,"# Covariance matrix\n");
                   6576:   /* # 121 Var(a12)\n\ */
                   6577:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6578:   /* #   ...\n\ */
                   6579:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6580:   
                   6581:   for(itimes=1;itimes<=2;itimes++){
                   6582:     jj=0;
                   6583:     for(i=1; i <=nlstate; i++){
                   6584:       for(j=1; j <=nlstate+ndeath; j++){
                   6585:        if(j==i) continue;
                   6586:        for(k=1; k<=ncovmodel;k++){
                   6587:          jj++;
                   6588:          ca[0]= k+'a'-1;ca[1]='\0';
                   6589:          if(itimes==1){
                   6590:            printf("#%1d%1d%d",i,j,k);
                   6591:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6592:          }else{
                   6593:            printf("%1d%1d%d",i,j,k);
                   6594:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6595:            /*  printf(" %.5le",matcov[i][j]); */
                   6596:          }
                   6597:          ll=0;
                   6598:          for(li=1;li <=nlstate; li++){
                   6599:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6600:              if(lj==li) continue;
                   6601:              for(lk=1;lk<=ncovmodel;lk++){
                   6602:                ll++;
                   6603:                if(ll<=jj){
                   6604:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6605:                  if(ll<jj){
                   6606:                    if(itimes==1){
                   6607:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6608:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6609:                    }else{
                   6610:                      printf(" 0.");
                   6611:                      fprintf(ficparo," 0.");
                   6612:                    }
                   6613:                  }else{
                   6614:                    if(itimes==1){
                   6615:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   6616:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   6617:                    }else{
                   6618:                      printf(" 0.");
                   6619:                      fprintf(ficparo," 0.");
                   6620:                    }
                   6621:                  }
                   6622:                }
                   6623:              } /* end lk */
                   6624:            } /* end lj */
                   6625:          } /* end li */
                   6626:          printf("\n");
                   6627:          fprintf(ficparo,"\n");
                   6628:          numlinepar++;
                   6629:        } /* end k*/
                   6630:       } /*end j */
                   6631:     } /* end i */
                   6632:   } /* end itimes */
                   6633: 
                   6634: } /* end of prwizard */
                   6635: /******************* Gompertz Likelihood ******************************/
                   6636: double gompertz(double x[])
                   6637: { 
                   6638:   double A,B,L=0.0,sump=0.,num=0.;
                   6639:   int i,n=0; /* n is the size of the sample */
                   6640: 
                   6641:   for (i=0;i<=imx-1 ; i++) {
                   6642:     sump=sump+weight[i];
                   6643:     /*    sump=sump+1;*/
                   6644:     num=num+1;
                   6645:   }
                   6646:  
                   6647:  
                   6648:   /* for (i=0; i<=imx; i++) 
                   6649:      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]);*/
                   6650: 
                   6651:   for (i=1;i<=imx ; i++)
                   6652:     {
                   6653:       if (cens[i] == 1 && wav[i]>1)
                   6654:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   6655:       
                   6656:       if (cens[i] == 0 && wav[i]>1)
                   6657:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   6658:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   6659:       
                   6660:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6661:       if (wav[i] > 1 ) { /* ??? */
                   6662:        L=L+A*weight[i];
                   6663:        /*      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]);*/
                   6664:       }
                   6665:     }
                   6666: 
                   6667:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6668:  
                   6669:   return -2*L*num/sump;
                   6670: }
                   6671: 
1.136     brouard  6672: #ifdef GSL
                   6673: /******************* Gompertz_f Likelihood ******************************/
                   6674: double gompertz_f(const gsl_vector *v, void *params)
                   6675: { 
                   6676:   double A,B,LL=0.0,sump=0.,num=0.;
                   6677:   double *x= (double *) v->data;
                   6678:   int i,n=0; /* n is the size of the sample */
                   6679: 
                   6680:   for (i=0;i<=imx-1 ; i++) {
                   6681:     sump=sump+weight[i];
                   6682:     /*    sump=sump+1;*/
                   6683:     num=num+1;
                   6684:   }
                   6685:  
                   6686:  
                   6687:   /* for (i=0; i<=imx; i++) 
                   6688:      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]);*/
                   6689:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   6690:   for (i=1;i<=imx ; i++)
                   6691:     {
                   6692:       if (cens[i] == 1 && wav[i]>1)
                   6693:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   6694:       
                   6695:       if (cens[i] == 0 && wav[i]>1)
                   6696:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   6697:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   6698:       
                   6699:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6700:       if (wav[i] > 1 ) { /* ??? */
                   6701:        LL=LL+A*weight[i];
                   6702:        /*      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]);*/
                   6703:       }
                   6704:     }
                   6705: 
                   6706:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6707:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   6708:  
                   6709:   return -2*LL*num/sump;
                   6710: }
                   6711: #endif
                   6712: 
1.126     brouard  6713: /******************* Printing html file ***********/
1.201     brouard  6714: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6715:                  int lastpass, int stepm, int weightopt, char model[],\
                   6716:                  int imx,  double p[],double **matcov,double agemortsup){
                   6717:   int i,k;
                   6718: 
                   6719:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   6720:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   6721:   for (i=1;i<=2;i++) 
                   6722:     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  6723:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  6724:   fprintf(fichtm,"</ul>");
                   6725: 
                   6726: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   6727: 
                   6728:  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>");
                   6729: 
                   6730:  for (k=agegomp;k<(agemortsup-2);k++) 
                   6731:    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]);
                   6732: 
                   6733:  
                   6734:   fflush(fichtm);
                   6735: }
                   6736: 
                   6737: /******************* Gnuplot file **************/
1.201     brouard  6738: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  6739: 
                   6740:   char dirfileres[132],optfileres[132];
1.164     brouard  6741: 
1.126     brouard  6742:   int ng;
                   6743: 
                   6744: 
                   6745:   /*#ifdef windows */
                   6746:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   6747:     /*#endif */
                   6748: 
                   6749: 
                   6750:   strcpy(dirfileres,optionfilefiname);
                   6751:   strcpy(optfileres,"vpl");
1.199     brouard  6752:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  6753:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  6754:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  6755:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  6756:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   6757: 
                   6758: } 
                   6759: 
1.136     brouard  6760: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   6761: {
1.126     brouard  6762: 
1.136     brouard  6763:   /*-------- data file ----------*/
                   6764:   FILE *fic;
                   6765:   char dummy[]="                         ";
1.164     brouard  6766:   int i=0, j=0, n=0;
1.136     brouard  6767:   int linei, month, year,iout;
                   6768:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  6769:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  6770:   char *stratrunc;
                   6771:   int lstra;
1.126     brouard  6772: 
                   6773: 
1.136     brouard  6774:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  6775:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   6776:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  6777:   }
1.126     brouard  6778: 
1.136     brouard  6779:   i=1;
                   6780:   linei=0;
                   6781:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   6782:     linei=linei+1;
                   6783:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   6784:       if(line[j] == '\t')
                   6785:        line[j] = ' ';
                   6786:     }
                   6787:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   6788:       ;
                   6789:     };
                   6790:     line[j+1]=0;  /* Trims blanks at end of line */
                   6791:     if(line[0]=='#'){
                   6792:       fprintf(ficlog,"Comment line\n%s\n",line);
                   6793:       printf("Comment line\n%s\n",line);
                   6794:       continue;
                   6795:     }
                   6796:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  6797:     strcpy(line, linetmp);
1.136     brouard  6798:   
1.126     brouard  6799: 
1.136     brouard  6800:     for (j=maxwav;j>=1;j--){
1.137     brouard  6801:       cutv(stra, strb, line, ' '); 
1.136     brouard  6802:       if(strb[0]=='.') { /* Missing status */
                   6803:        lval=-1;
                   6804:       }else{
                   6805:        errno=0;
                   6806:        lval=strtol(strb,&endptr,10); 
                   6807:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   6808:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6809:          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);
                   6810:          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  6811:          return 1;
                   6812:        }
                   6813:       }
                   6814:       s[j][i]=lval;
                   6815:       
                   6816:       strcpy(line,stra);
                   6817:       cutv(stra, strb,line,' ');
1.169     brouard  6818:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6819:       }
1.169     brouard  6820:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6821:        month=99;
                   6822:        year=9999;
                   6823:       }else{
1.141     brouard  6824:        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);
                   6825:        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  6826:        return 1;
                   6827:       }
                   6828:       anint[j][i]= (double) year; 
                   6829:       mint[j][i]= (double)month; 
                   6830:       strcpy(line,stra);
                   6831:     } /* ENd Waves */
                   6832:     
                   6833:     cutv(stra, strb,line,' '); 
1.169     brouard  6834:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6835:     }
1.169     brouard  6836:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6837:       month=99;
                   6838:       year=9999;
                   6839:     }else{
1.141     brouard  6840:       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);
                   6841:        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  6842:        return 1;
                   6843:     }
                   6844:     andc[i]=(double) year; 
                   6845:     moisdc[i]=(double) month; 
                   6846:     strcpy(line,stra);
                   6847:     
                   6848:     cutv(stra, strb,line,' '); 
1.169     brouard  6849:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6850:     }
1.169     brouard  6851:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  6852:       month=99;
                   6853:       year=9999;
                   6854:     }else{
1.141     brouard  6855:       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);
                   6856:       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  6857:        return 1;
                   6858:     }
                   6859:     if (year==9999) {
1.141     brouard  6860:       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);
                   6861:       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  6862:        return 1;
1.126     brouard  6863: 
1.136     brouard  6864:     }
                   6865:     annais[i]=(double)(year);
                   6866:     moisnais[i]=(double)(month); 
                   6867:     strcpy(line,stra);
                   6868:     
                   6869:     cutv(stra, strb,line,' '); 
                   6870:     errno=0;
                   6871:     dval=strtod(strb,&endptr); 
                   6872:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6873:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6874:       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  6875:       fflush(ficlog);
                   6876:       return 1;
                   6877:     }
                   6878:     weight[i]=dval; 
                   6879:     strcpy(line,stra);
                   6880:     
                   6881:     for (j=ncovcol;j>=1;j--){
                   6882:       cutv(stra, strb,line,' '); 
                   6883:       if(strb[0]=='.') { /* Missing status */
                   6884:        lval=-1;
                   6885:       }else{
                   6886:        errno=0;
                   6887:        lval=strtol(strb,&endptr,10); 
                   6888:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6889:          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);
                   6890:          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  6891:          return 1;
                   6892:        }
                   6893:       }
                   6894:       if(lval <-1 || lval >1){
1.141     brouard  6895:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6896:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6897:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6898:  For example, for multinomial values like 1, 2 and 3,\n \
                   6899:  build V1=0 V2=0 for the reference value (1),\n \
                   6900:         V1=1 V2=0 for (2) \n \
                   6901:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6902:  output of IMaCh is often meaningless.\n \
                   6903:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6904:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6905:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6906:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6907:  For example, for multinomial values like 1, 2 and 3,\n \
                   6908:  build V1=0 V2=0 for the reference value (1),\n \
                   6909:         V1=1 V2=0 for (2) \n \
                   6910:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6911:  output of IMaCh is often meaningless.\n \
                   6912:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6913:        return 1;
                   6914:       }
                   6915:       covar[j][i]=(double)(lval);
                   6916:       strcpy(line,stra);
                   6917:     }  
                   6918:     lstra=strlen(stra);
                   6919:      
                   6920:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6921:       stratrunc = &(stra[lstra-9]);
                   6922:       num[i]=atol(stratrunc);
                   6923:     }
                   6924:     else
                   6925:       num[i]=atol(stra);
                   6926:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6927:       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;}*/
                   6928:     
                   6929:     i=i+1;
                   6930:   } /* End loop reading  data */
1.126     brouard  6931: 
1.136     brouard  6932:   *imax=i-1; /* Number of individuals */
                   6933:   fclose(fic);
                   6934:  
                   6935:   return (0);
1.164     brouard  6936:   /* endread: */
1.136     brouard  6937:     printf("Exiting readdata: ");
                   6938:     fclose(fic);
                   6939:     return (1);
1.126     brouard  6940: 
                   6941: 
                   6942: 
1.136     brouard  6943: }
1.145     brouard  6944: void removespace(char *str) {
                   6945:   char *p1 = str, *p2 = str;
                   6946:   do
                   6947:     while (*p2 == ' ')
                   6948:       p2++;
1.169     brouard  6949:   while (*p1++ == *p2++);
1.145     brouard  6950: }
                   6951: 
                   6952: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6953:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6954:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6955:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6956:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6957:    * - cptcovage number of covariates with age*products =2
                   6958:    * - cptcovs number of simple covariates
                   6959:    * - 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
                   6960:    *     which is a new column after the 9 (ncovcol) variables. 
                   6961:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6962:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6963:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6964:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6965:  */
1.136     brouard  6966: {
1.145     brouard  6967:   int i, j, k, ks;
1.164     brouard  6968:   int  j1, k1, k2;
1.136     brouard  6969:   char modelsav[80];
1.145     brouard  6970:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6971:   char *strpt;
1.136     brouard  6972: 
1.145     brouard  6973:   /*removespace(model);*/
1.136     brouard  6974:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6975:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6976:     if (strstr(model,"AGE") !=0){
1.192     brouard  6977:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6978:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6979:       return 1;
                   6980:     }
1.141     brouard  6981:     if (strstr(model,"v") !=0){
                   6982:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6983:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6984:       return 1;
                   6985:     }
1.187     brouard  6986:     strcpy(modelsav,model); 
                   6987:     if ((strpt=strstr(model,"age*age")) !=0){
                   6988:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6989:       if(strpt != model){
                   6990:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6991:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6992:  corresponding column of parameters.\n",model);
                   6993:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6994:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6995:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6996:       return 1;
                   6997:     }
                   6998: 
                   6999:       nagesqr=1;
                   7000:       if (strstr(model,"+age*age") !=0)
                   7001:        substrchaine(modelsav, model, "+age*age");
                   7002:       else if (strstr(model,"age*age+") !=0)
                   7003:        substrchaine(modelsav, model, "age*age+");
                   7004:       else 
                   7005:        substrchaine(modelsav, model, "age*age");
                   7006:     }else
                   7007:       nagesqr=0;
                   7008:     if (strlen(modelsav) >1){
                   7009:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7010:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   7011:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   7012:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   7013:                   * cst, age and age*age 
                   7014:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   7015:                   /* including age products which are counted in cptcovage.
                   7016:                  * but the covariates which are products must be treated 
                   7017:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   7018:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7019:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7020: 
                   7021:     
                   7022:       /*   Design
                   7023:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7024:        *  <          ncovcol=8                >
                   7025:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7026:        *   k=  1    2      3       4     5       6      7        8
                   7027:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7028:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   7029:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   7030:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   7031:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7032:        *  Tage[++cptcovage]=k
                   7033:        *       if products, new covar are created after ncovcol with k1
                   7034:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7035:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7036:        *  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
                   7037:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7038:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7039:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7040:        *  <          ncovcol=8                >
                   7041:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7042:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7043:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7044:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7045:        * p Tprod[1]@2={                         6, 5}
                   7046:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7047:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7048:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7049:        *How to reorganize?
                   7050:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7051:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7052:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7053:        * Struct []
                   7054:        */
1.145     brouard  7055: 
1.187     brouard  7056:       /* This loop fills the array Tvar from the string 'model'.*/
                   7057:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7058:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7059:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7060:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7061:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7062:       /*       k=1 Tvar[1]=2 (from V2) */
                   7063:       /*       k=5 Tvar[5] */
                   7064:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  7065:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  7066:       /*       } */
1.198     brouard  7067:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  7068:       /*
                   7069:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7070:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  7071:         Tvar[k]=0;
1.187     brouard  7072:       cptcovage=0;
                   7073:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   7074:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   7075:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   7076:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   7077:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   7078:        /*scanf("%d",i);*/
                   7079:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   7080:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   7081:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   7082:            /* covar is not filled and then is empty */
                   7083:            cptcovprod--;
                   7084:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   7085:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   7086:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   7087:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7088:            /*printf("stre=%s ", stre);*/
                   7089:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   7090:            cptcovprod--;
                   7091:            cutl(stre,strb,strc,'V');
                   7092:            Tvar[k]=atoi(stre);
                   7093:            cptcovage++;
                   7094:            Tage[cptcovage]=k;
                   7095:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   7096:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   7097:            cptcovn++;
                   7098:            cptcovprodnoage++;k1++;
                   7099:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   7100:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   7101:                                   because this model-covariate is a construction we invent a new column
                   7102:                                   ncovcol + k1
                   7103:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   7104:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   7105:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   7106:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   7107:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   7108:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   7109:            k2=k2+2;
                   7110:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   7111:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   7112:            for (i=1; i<=lastobs;i++){
                   7113:              /* Computes the new covariate which is a product of
                   7114:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   7115:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   7116:            }
                   7117:          } /* End age is not in the model */
                   7118:        } /* End if model includes a product */
                   7119:        else { /* no more sum */
                   7120:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   7121:          /*  scanf("%d",i);*/
                   7122:          cutl(strd,strc,strb,'V');
                   7123:          ks++; /**< Number of simple covariates */
1.145     brouard  7124:          cptcovn++;
1.187     brouard  7125:          Tvar[k]=atoi(strd);
                   7126:        }
                   7127:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   7128:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   7129:          scanf("%d",i);*/
                   7130:       } /* end of loop + on total covariates */
                   7131:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7132:   } /* end if strlen(model == 0) */
1.136     brouard  7133:   
                   7134:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7135:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7136: 
                   7137:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   7138:   printf("cptcovprod=%d ", cptcovprod);
                   7139:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   7140: 
                   7141:   scanf("%d ",i);*/
                   7142: 
                   7143: 
1.137     brouard  7144:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  7145:   /*endread:*/
1.136     brouard  7146:     printf("Exiting decodemodel: ");
                   7147:     return (1);
                   7148: }
                   7149: 
1.169     brouard  7150: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  7151: {
                   7152:   int i, m;
                   7153: 
                   7154:   for (i=1; i<=imx; i++) {
                   7155:     for(m=2; (m<= maxwav); m++) {
                   7156:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7157:        anint[m][i]=9999;
1.216     brouard  7158:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7159:          s[m][i]=-1;
1.136     brouard  7160:       }
                   7161:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  7162:        *nberr = *nberr + 1;
                   7163:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
                   7164:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136     brouard  7165:        s[m][i]=-1;
                   7166:       }
                   7167:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  7168:        (*nberr)++;
1.136     brouard  7169:        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]); 
                   7170:        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]); 
                   7171:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7172:       }
                   7173:     }
                   7174:   }
                   7175: 
                   7176:   for (i=1; i<=imx; i++)  {
                   7177:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7178:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  7179:       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  7180:        if (s[m][i] >= nlstate+1) {
1.169     brouard  7181:          if(agedc[i]>0){
                   7182:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  7183:              agev[m][i]=agedc[i];
1.214     brouard  7184:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  7185:            }else {
1.136     brouard  7186:              if ((int)andc[i]!=9999){
                   7187:                nbwarn++;
                   7188:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7189:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7190:                agev[m][i]=-1;
                   7191:              }
                   7192:            }
1.169     brouard  7193:          } /* agedc > 0 */
1.214     brouard  7194:        } /* end if */
1.136     brouard  7195:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7196:                                 years but with the precision of a month */
                   7197:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7198:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7199:            agev[m][i]=1;
                   7200:          else if(agev[m][i] < *agemin){ 
                   7201:            *agemin=agev[m][i];
                   7202:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7203:          }
                   7204:          else if(agev[m][i] >*agemax){
                   7205:            *agemax=agev[m][i];
1.156     brouard  7206:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  7207:          }
                   7208:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7209:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  7210:        } /* en if 9*/
1.136     brouard  7211:        else { /* =9 */
1.214     brouard  7212:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  7213:          agev[m][i]=1;
                   7214:          s[m][i]=-1;
                   7215:        }
                   7216:       }
1.214     brouard  7217:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  7218:        agev[m][i]=1;
1.214     brouard  7219:       else{
                   7220:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7221:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7222:        agev[m][i]=0;
                   7223:       }
                   7224:     } /* End for lastpass */
                   7225:   }
1.136     brouard  7226:     
                   7227:   for (i=1; i<=imx; i++)  {
                   7228:     for(m=firstpass; (m<=lastpass); m++){
                   7229:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  7230:        (*nberr)++;
1.136     brouard  7231:        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);     
                   7232:        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);     
                   7233:        return 1;
                   7234:       }
                   7235:     }
                   7236:   }
                   7237: 
                   7238:   /*for (i=1; i<=imx; i++){
                   7239:   for (m=firstpass; (m<lastpass); m++){
                   7240:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7241: }
                   7242: 
                   7243: }*/
                   7244: 
                   7245: 
1.139     brouard  7246:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7247:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  7248: 
                   7249:   return (0);
1.164     brouard  7250:  /* endread:*/
1.136     brouard  7251:     printf("Exiting calandcheckages: ");
                   7252:     return (1);
                   7253: }
                   7254: 
1.172     brouard  7255: #if defined(_MSC_VER)
                   7256: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7257: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7258: //#include "stdafx.h"
                   7259: //#include <stdio.h>
                   7260: //#include <tchar.h>
                   7261: //#include <windows.h>
                   7262: //#include <iostream>
                   7263: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7264: 
                   7265: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7266: 
                   7267: BOOL IsWow64()
                   7268: {
                   7269:        BOOL bIsWow64 = FALSE;
                   7270: 
                   7271:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7272:        //  (HANDLE, PBOOL);
                   7273: 
                   7274:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7275: 
                   7276:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7277:        const char funcName[] = "IsWow64Process";
                   7278:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7279:                GetProcAddress(module, funcName);
                   7280: 
                   7281:        if (NULL != fnIsWow64Process)
                   7282:        {
                   7283:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7284:                        &bIsWow64))
                   7285:                        //throw std::exception("Unknown error");
                   7286:                        printf("Unknown error\n");
                   7287:        }
                   7288:        return bIsWow64 != FALSE;
                   7289: }
                   7290: #endif
1.177     brouard  7291: 
1.191     brouard  7292: void syscompilerinfo(int logged)
1.167     brouard  7293:  {
                   7294:    /* #include "syscompilerinfo.h"*/
1.185     brouard  7295:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7296:    /* /GS /W3 /Gy
                   7297:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7298:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7299:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  7300:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   7301:    */ 
                   7302:    /* 64 bits */
1.185     brouard  7303:    /*
                   7304:      /GS /W3 /Gy
                   7305:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   7306:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   7307:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   7308:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   7309:    /* Optimization are useless and O3 is slower than O2 */
                   7310:    /*
                   7311:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   7312:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   7313:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   7314:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   7315:    */
1.186     brouard  7316:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  7317:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   7318:       /PDB:"visual studio
                   7319:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   7320:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   7321:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   7322:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   7323:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   7324:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   7325:       uiAccess='false'"
                   7326:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   7327:       /NOLOGO /TLBID:1
                   7328:    */
1.177     brouard  7329: #if defined __INTEL_COMPILER
1.178     brouard  7330: #if defined(__GNUC__)
                   7331:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   7332: #endif
1.177     brouard  7333: #elif defined(__GNUC__) 
1.179     brouard  7334: #ifndef  __APPLE__
1.174     brouard  7335: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  7336: #endif
1.177     brouard  7337:    struct utsname sysInfo;
1.178     brouard  7338:    int cross = CROSS;
                   7339:    if (cross){
                   7340:           printf("Cross-");
1.191     brouard  7341:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  7342:    }
1.174     brouard  7343: #endif
                   7344: 
1.171     brouard  7345: #include <stdint.h>
1.178     brouard  7346: 
1.191     brouard  7347:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  7348: #if defined(__clang__)
1.191     brouard  7349:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  7350: #endif
                   7351: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  7352:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  7353: #endif
                   7354: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  7355:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  7356: #endif
                   7357: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  7358:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  7359: #endif
                   7360: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  7361:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  7362: #endif
                   7363: #if defined(_MSC_VER)
1.191     brouard  7364:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  7365: #endif
                   7366: #if defined(__PGI)
1.191     brouard  7367:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  7368: #endif
                   7369: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  7370:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  7371: #endif
1.191     brouard  7372:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  7373:    
1.167     brouard  7374: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   7375: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   7376:     // Windows (x64 and x86)
1.191     brouard  7377:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  7378: #elif __unix__ // all unices, not all compilers
                   7379:     // Unix
1.191     brouard  7380:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  7381: #elif __linux__
                   7382:     // linux
1.191     brouard  7383:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  7384: #elif __APPLE__
1.174     brouard  7385:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  7386:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  7387: #endif
                   7388: 
                   7389: /*  __MINGW32__          */
                   7390: /*  __CYGWIN__  */
                   7391: /* __MINGW64__  */
                   7392: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   7393: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   7394: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   7395: /* _WIN64  // Defined for applications for Win64. */
                   7396: /* _M_X64 // Defined for compilations that target x64 processors. */
                   7397: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  7398: 
1.167     brouard  7399: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  7400:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  7401: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  7402:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  7403: #else
1.191     brouard  7404:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  7405: #endif
                   7406: 
1.169     brouard  7407: #if defined(__GNUC__)
                   7408: # if defined(__GNUC_PATCHLEVEL__)
                   7409: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7410:                             + __GNUC_MINOR__ * 100 \
                   7411:                             + __GNUC_PATCHLEVEL__)
                   7412: # else
                   7413: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7414:                             + __GNUC_MINOR__ * 100)
                   7415: # endif
1.174     brouard  7416:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  7417:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  7418: 
                   7419:    if (uname(&sysInfo) != -1) {
                   7420:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  7421:         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  7422:    }
                   7423:    else
                   7424:       perror("uname() error");
1.179     brouard  7425:    //#ifndef __INTEL_COMPILER 
                   7426: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  7427:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  7428:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  7429: #endif
1.169     brouard  7430: #endif
1.172     brouard  7431: 
                   7432:    //   void main()
                   7433:    //   {
1.169     brouard  7434: #if defined(_MSC_VER)
1.174     brouard  7435:    if (IsWow64()){
1.191     brouard  7436:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7437:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  7438:    }
                   7439:    else{
1.191     brouard  7440:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7441:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  7442:    }
1.172     brouard  7443:    //     printf("\nPress Enter to continue...");
                   7444:    //     getchar();
                   7445:    //   }
                   7446: 
1.169     brouard  7447: #endif
                   7448:    
1.167     brouard  7449: 
                   7450:  }
1.136     brouard  7451: 
1.209     brouard  7452:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  7453:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   7454:   int i, j, k, i1 ;
1.202     brouard  7455:   /* double ftolpl = 1.e-10; */
1.180     brouard  7456:   double age, agebase, agelim;
1.203     brouard  7457:   double tot;
1.180     brouard  7458: 
1.202     brouard  7459:   strcpy(filerespl,"PL_");
                   7460:   strcat(filerespl,fileresu);
                   7461:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   7462:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7463:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7464:   }
                   7465:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7466:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7467:   pstamp(ficrespl);
1.203     brouard  7468:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  7469:   fprintf(ficrespl,"#Age ");
                   7470:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   7471:   fprintf(ficrespl,"\n");
1.180     brouard  7472:   
                   7473:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   7474: 
                   7475:     agebase=ageminpar;
                   7476:     agelim=agemaxpar;
                   7477: 
                   7478:     i1=pow(2,cptcoveff);
                   7479:     if (cptcovn < 1){i1=1;}
                   7480: 
                   7481:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7482:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   7483:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   7484:        k=k+1;
                   7485:        /* to clean */
1.198     brouard  7486:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  7487:        fprintf(ficrespl,"#******");
                   7488:        printf("#******");
                   7489:        fprintf(ficlog,"#******");
1.180     brouard  7490:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  7491:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7492:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7493:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  7494:        }
                   7495:        fprintf(ficrespl,"******\n");
                   7496:        printf("******\n");
                   7497:        fprintf(ficlog,"******\n");
                   7498: 
                   7499:        fprintf(ficrespl,"#Age ");
                   7500:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  7501:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  7502:        }
1.203     brouard  7503:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   7504:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  7505:        
                   7506:        for (age=agebase; age<=agelim; age++){
                   7507:        /* for (age=agebase; age<=agebase; age++){ */
1.209     brouard  7508:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  7509:          fprintf(ficrespl,"%.0f ",age );
                   7510:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  7511:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  7512:          tot=0.;
                   7513:          for(i=1; i<=nlstate;i++){
                   7514:            tot +=  prlim[i][i];
1.180     brouard  7515:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  7516:          }
1.209     brouard  7517:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  7518:        } /* Age */
                   7519:        /* was end of cptcod */
                   7520:     } /* cptcov */
1.184     brouard  7521:        return 0;
1.180     brouard  7522: }
                   7523: 
1.217   ! brouard  7524:  int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
        !          7525:   /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
        !          7526:   int i, j, k, i1 ;
        !          7527:   /* double ftolpl = 1.e-10; */
        !          7528:   double age, agebase, agelim;
        !          7529:   double tot;
        !          7530: 
        !          7531:   strcpy(fileresplb,"PLB_");
        !          7532:   strcat(fileresplb,fileresu);
        !          7533:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
        !          7534:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
        !          7535:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
        !          7536:   }
        !          7537:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
        !          7538:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
        !          7539:   pstamp(ficresplb);
        !          7540:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
        !          7541:   fprintf(ficresplb,"#Age ");
        !          7542:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
        !          7543:   fprintf(ficresplb,"\n");
        !          7544:   
        !          7545:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
        !          7546: 
        !          7547:     agebase=ageminpar;
        !          7548:     agelim=agemaxpar;
        !          7549: 
        !          7550:     i1=pow(2,cptcoveff);
        !          7551:     if (cptcovn < 1){i1=1;}
        !          7552: 
        !          7553:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
        !          7554:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
        !          7555:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
        !          7556:        k=k+1;
        !          7557:        /* to clean */
        !          7558:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
        !          7559:        fprintf(ficresplb,"#******");
        !          7560:        printf("#******");
        !          7561:        fprintf(ficlog,"#******");
        !          7562:        for(j=1;j<=cptcoveff;j++) {
        !          7563:          fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7564:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7565:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7566:        }
        !          7567:        fprintf(ficresplb,"******\n");
        !          7568:        printf("******\n");
        !          7569:        fprintf(ficlog,"******\n");
        !          7570: 
        !          7571:        fprintf(ficresplb,"#Age ");
        !          7572:        for(j=1;j<=cptcoveff;j++) {
        !          7573:          fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7574:        }
        !          7575:        for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
        !          7576:        fprintf(ficresplb,"Total Years_to_converge\n");
        !          7577:        
        !          7578:        for (age=agebase; age<=agelim; age++){
        !          7579:        /* for (age=agebase; age<=agebase; age++){ */
        !          7580:          bprevalim(bprlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
        !          7581:          fprintf(ficresplb,"%.0f ",age );
        !          7582:          for(j=1;j<=cptcoveff;j++)
        !          7583:            fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7584:          tot=0.;
        !          7585:          for(i=1; i<=nlstate;i++){
        !          7586:            tot +=  bprlim[i][i];
        !          7587:            fprintf(ficresplb," %.5f", bprlim[i][i]);
        !          7588:          }
        !          7589:          fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
        !          7590:        } /* Age */
        !          7591:        /* was end of cptcod */
        !          7592:     } /* cptcov */
        !          7593:        return 0;
        !          7594: }
        !          7595: 
1.180     brouard  7596: int hPijx(double *p, int bage, int fage){
                   7597:     /*------------- h Pij x at various ages ------------*/
                   7598: 
                   7599:   int stepsize;
                   7600:   int agelim;
                   7601:   int hstepm;
                   7602:   int nhstepm;
                   7603:   int h, i, i1, j, k;
                   7604: 
                   7605:   double agedeb;
                   7606:   double ***p3mat;
                   7607: 
1.201     brouard  7608:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  7609:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   7610:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7611:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7612:     }
                   7613:     printf("Computing pij: result on file '%s' \n", filerespij);
                   7614:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   7615:   
                   7616:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7617:     /*if (stepm<=24) stepsize=2;*/
                   7618: 
                   7619:     agelim=AGESUP;
                   7620:     hstepm=stepsize*YEARM; /* Every year of age */
                   7621:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   7622: 
                   7623:     /* hstepm=1;   aff par mois*/
                   7624:     pstamp(ficrespij);
                   7625:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   7626:     i1= pow(2,cptcoveff);
1.183     brouard  7627:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   7628:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   7629:    /*          k=k+1;  */
                   7630:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7631:       fprintf(ficrespij,"\n#****** ");
                   7632:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  7633:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  7634:       fprintf(ficrespij,"******\n");
                   7635:       
                   7636:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   7637:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7638:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7639:        
                   7640:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  7641:        
1.183     brouard  7642:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7643:        oldm=oldms;savm=savms;
                   7644:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   7645:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   7646:        for(i=1; i<=nlstate;i++)
                   7647:          for(j=1; j<=nlstate+ndeath;j++)
                   7648:            fprintf(ficrespij," %1d-%1d",i,j);
                   7649:        fprintf(ficrespij,"\n");
                   7650:        for (h=0; h<=nhstepm; h++){
                   7651:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   7652:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  7653:          for(i=1; i<=nlstate;i++)
                   7654:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  7655:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  7656:          fprintf(ficrespij,"\n");
                   7657:        }
1.183     brouard  7658:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7659:        fprintf(ficrespij,"\n");
                   7660:       }
1.180     brouard  7661:       /*}*/
                   7662:     }
1.184     brouard  7663:        return 0;
1.180     brouard  7664: }
                   7665: 
1.217   ! brouard  7666:  int hBijx(double *p, int bage, int fage){
        !          7667:     /*------------- h Bij x at various ages ------------*/
        !          7668: 
        !          7669:   int stepsize;
        !          7670:   int agelim;
        !          7671:   int hstepm;
        !          7672:   int nhstepm;
        !          7673:   int h, i, i1, j, k;
        !          7674: 
        !          7675:   double agedeb;
        !          7676:   double ***p3mat;
        !          7677: 
        !          7678:     strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
        !          7679:     if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
        !          7680:       printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
        !          7681:       fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
        !          7682:     }
        !          7683:     printf("Computing pij back: result on file '%s' \n", filerespijb);
        !          7684:     fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
        !          7685:   
        !          7686:     stepsize=(int) (stepm+YEARM-1)/YEARM;
        !          7687:     /*if (stepm<=24) stepsize=2;*/
        !          7688: 
        !          7689:     agelim=AGESUP;
        !          7690:     hstepm=stepsize*YEARM; /* Every year of age */
        !          7691:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
        !          7692: 
        !          7693:     /* hstepm=1;   aff par mois*/
        !          7694:     pstamp(ficrespijb);
        !          7695:     fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
        !          7696:     i1= pow(2,cptcoveff);
        !          7697:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
        !          7698:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
        !          7699:    /*          k=k+1;  */
        !          7700:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
        !          7701:       fprintf(ficrespijb,"\n#****** ");
        !          7702:       for(j=1;j<=cptcoveff;j++) 
        !          7703:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          7704:       fprintf(ficrespijb,"******\n");
        !          7705:       
        !          7706:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
        !          7707:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months */
        !          7708:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
        !          7709:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
        !          7710:        
        !          7711:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
        !          7712:        
        !          7713:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          7714:        oldm=oldms;savm=savms;
        !          7715:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
        !          7716:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
        !          7717:        for(i=1; i<=nlstate;i++)
        !          7718:          for(j=1; j<=nlstate+ndeath;j++)
        !          7719:            fprintf(ficrespijb," %1d-%1d",i,j);
        !          7720:        fprintf(ficrespijb,"\n");
        !          7721:        for (h=0; h<=nhstepm; h++){
        !          7722:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
        !          7723:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
        !          7724:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
        !          7725:          for(i=1; i<=nlstate;i++)
        !          7726:            for(j=1; j<=nlstate+ndeath;j++)
        !          7727:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
        !          7728:          fprintf(ficrespijb,"\n");
        !          7729:        }
        !          7730:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          7731:        fprintf(ficrespijb,"\n");
        !          7732:       }
        !          7733:       /*}*/
        !          7734:     }
        !          7735:        return 0;
        !          7736: }
        !          7737: 
1.180     brouard  7738: 
1.136     brouard  7739: /***********************************************/
                   7740: /**************** Main Program *****************/
                   7741: /***********************************************/
                   7742: 
                   7743: int main(int argc, char *argv[])
                   7744: {
                   7745: #ifdef GSL
                   7746:   const gsl_multimin_fminimizer_type *T;
                   7747:   size_t iteri = 0, it;
                   7748:   int rval = GSL_CONTINUE;
                   7749:   int status = GSL_SUCCESS;
                   7750:   double ssval;
                   7751: #endif
                   7752:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  7753:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  7754:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  7755:   int jj, ll, li, lj, lk;
1.136     brouard  7756:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  7757:   int num_filled;
1.136     brouard  7758:   int itimes;
                   7759:   int NDIM=2;
                   7760:   int vpopbased=0;
                   7761: 
1.164     brouard  7762:   char ca[32], cb[32];
1.136     brouard  7763:   /*  FILE *fichtm; *//* Html File */
                   7764:   /* FILE *ficgp;*/ /*Gnuplot File */
                   7765:   struct stat info;
1.191     brouard  7766:   double agedeb=0.;
1.194     brouard  7767: 
                   7768:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  7769: 
1.165     brouard  7770:   double fret;
1.191     brouard  7771:   double dum=0.; /* Dummy variable */
1.136     brouard  7772:   double ***p3mat;
                   7773:   double ***mobaverage;
1.164     brouard  7774: 
                   7775:   char line[MAXLINE];
1.197     brouard  7776:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   7777: 
                   7778:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  7779:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  7780:   char *tok, *val; /* pathtot */
1.136     brouard  7781:   int firstobs=1, lastobs=10;
1.195     brouard  7782:   int c,  h , cpt, c2;
1.191     brouard  7783:   int jl=0;
                   7784:   int i1, j1, jk, stepsize=0;
1.194     brouard  7785:   int count=0;
                   7786: 
1.164     brouard  7787:   int *tab; 
1.136     brouard  7788:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217   ! brouard  7789:   int backcast=0;
1.136     brouard  7790:   int mobilav=0,popforecast=0;
1.191     brouard  7791:   int hstepm=0, nhstepm=0;
1.136     brouard  7792:   int agemortsup;
                   7793:   float  sumlpop=0.;
                   7794:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   7795:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   7796: 
1.191     brouard  7797:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  7798:   double ftolpl=FTOL;
                   7799:   double **prlim;
1.217   ! brouard  7800:   double **bprlim;
1.136     brouard  7801:   double ***param; /* Matrix of parameters */
                   7802:   double  *p;
                   7803:   double **matcov; /* Matrix of covariance */
1.203     brouard  7804:   double **hess; /* Hessian matrix */
1.136     brouard  7805:   double ***delti3; /* Scale */
                   7806:   double *delti; /* Scale */
                   7807:   double ***eij, ***vareij;
                   7808:   double **varpl; /* Variances of prevalence limits by age */
                   7809:   double *epj, vepp;
1.164     brouard  7810: 
1.136     brouard  7811:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217   ! brouard  7812:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
        !          7813: 
1.136     brouard  7814:   double **ximort;
1.145     brouard  7815:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  7816:   int *dcwave;
                   7817: 
1.164     brouard  7818:   char z[1]="c";
1.136     brouard  7819: 
                   7820:   /*char  *strt;*/
                   7821:   char strtend[80];
1.126     brouard  7822: 
1.164     brouard  7823: 
1.126     brouard  7824: /*   setlocale (LC_ALL, ""); */
                   7825: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   7826: /*   textdomain (PACKAGE); */
                   7827: /*   setlocale (LC_CTYPE, ""); */
                   7828: /*   setlocale (LC_MESSAGES, ""); */
                   7829: 
                   7830:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  7831:   rstart_time = time(NULL);  
                   7832:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   7833:   start_time = *localtime(&rstart_time);
1.126     brouard  7834:   curr_time=start_time;
1.157     brouard  7835:   /*tml = *localtime(&start_time.tm_sec);*/
                   7836:   /* strcpy(strstart,asctime(&tml)); */
                   7837:   strcpy(strstart,asctime(&start_time));
1.126     brouard  7838: 
                   7839: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  7840: /*  tp.tm_sec = tp.tm_sec +86400; */
                   7841: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  7842: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   7843: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   7844: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  7845: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  7846: /*   strt=asctime(&tmg); */
                   7847: /*   printf("Time(after) =%s",strstart);  */
                   7848: /*  (void) time (&time_value);
                   7849: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   7850: *  tm = *localtime(&time_value);
                   7851: *  strstart=asctime(&tm);
                   7852: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   7853: */
                   7854: 
                   7855:   nberr=0; /* Number of errors and warnings */
                   7856:   nbwarn=0;
1.184     brouard  7857: #ifdef WIN32
                   7858:   _getcwd(pathcd, size);
                   7859: #else
1.126     brouard  7860:   getcwd(pathcd, size);
1.184     brouard  7861: #endif
1.191     brouard  7862:   syscompilerinfo(0);
1.196     brouard  7863:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  7864:   if(argc <=1){
                   7865:     printf("\nEnter the parameter file name: ");
1.205     brouard  7866:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   7867:       printf("ERROR Empty parameter file name\n");
                   7868:       goto end;
                   7869:     }
1.126     brouard  7870:     i=strlen(pathr);
                   7871:     if(pathr[i-1]=='\n')
                   7872:       pathr[i-1]='\0';
1.156     brouard  7873:     i=strlen(pathr);
1.205     brouard  7874:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  7875:       pathr[i-1]='\0';
1.205     brouard  7876:     }
                   7877:     i=strlen(pathr);
                   7878:     if( i==0 ){
                   7879:       printf("ERROR Empty parameter file name\n");
                   7880:       goto end;
                   7881:     }
                   7882:     for (tok = pathr; tok != NULL; ){
1.126     brouard  7883:       printf("Pathr |%s|\n",pathr);
                   7884:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   7885:       printf("val= |%s| pathr=%s\n",val,pathr);
                   7886:       strcpy (pathtot, val);
                   7887:       if(pathr[0] == '\0') break; /* Dirty */
                   7888:     }
                   7889:   }
                   7890:   else{
                   7891:     strcpy(pathtot,argv[1]);
                   7892:   }
                   7893:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   7894:   /*cygwin_split_path(pathtot,path,optionfile);
                   7895:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   7896:   /* cutv(path,optionfile,pathtot,'\\');*/
                   7897: 
                   7898:   /* Split argv[0], imach program to get pathimach */
                   7899:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   7900:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7901:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7902:  /*   strcpy(pathimach,argv[0]); */
                   7903:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   7904:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   7905:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  7906: #ifdef WIN32
                   7907:   _chdir(path); /* Can be a relative path */
                   7908:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   7909: #else
1.126     brouard  7910:   chdir(path); /* Can be a relative path */
1.184     brouard  7911:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   7912: #endif
                   7913:   printf("Current directory %s!\n",pathcd);
1.126     brouard  7914:   strcpy(command,"mkdir ");
                   7915:   strcat(command,optionfilefiname);
                   7916:   if((outcmd=system(command)) != 0){
1.169     brouard  7917:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  7918:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   7919:     /* fclose(ficlog); */
                   7920: /*     exit(1); */
                   7921:   }
                   7922: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   7923: /*     perror("mkdir"); */
                   7924: /*   } */
                   7925: 
                   7926:   /*-------- arguments in the command line --------*/
                   7927: 
1.186     brouard  7928:   /* Main Log file */
1.126     brouard  7929:   strcat(filelog, optionfilefiname);
                   7930:   strcat(filelog,".log");    /* */
                   7931:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   7932:     printf("Problem with logfile %s\n",filelog);
                   7933:     goto end;
                   7934:   }
                   7935:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  7936:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  7937:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   7938:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   7939:  path=%s \n\
                   7940:  optionfile=%s\n\
                   7941:  optionfilext=%s\n\
1.156     brouard  7942:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  7943: 
1.197     brouard  7944:   syscompilerinfo(1);
1.167     brouard  7945: 
1.126     brouard  7946:   printf("Local time (at start):%s",strstart);
                   7947:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   7948:   fflush(ficlog);
                   7949: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  7950: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  7951: 
                   7952:   /* */
                   7953:   strcpy(fileres,"r");
                   7954:   strcat(fileres, optionfilefiname);
1.201     brouard  7955:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  7956:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  7957:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  7958: 
1.186     brouard  7959:   /* Main ---------arguments file --------*/
1.126     brouard  7960: 
                   7961:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  7962:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   7963:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  7964:     fflush(ficlog);
1.149     brouard  7965:     /* goto end; */
                   7966:     exit(70); 
1.126     brouard  7967:   }
                   7968: 
                   7969: 
                   7970: 
                   7971:   strcpy(filereso,"o");
1.201     brouard  7972:   strcat(filereso,fileresu);
1.126     brouard  7973:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   7974:     printf("Problem with Output resultfile: %s\n", filereso);
                   7975:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   7976:     fflush(ficlog);
                   7977:     goto end;
                   7978:   }
                   7979: 
                   7980:   /* Reads comments: lines beginning with '#' */
                   7981:   numlinepar=0;
1.197     brouard  7982: 
                   7983:     /* First parameter line */
                   7984:   while(fgets(line, MAXLINE, ficpar)) {
                   7985:     /* If line starts with a # it is a comment */
                   7986:     if (line[0] == '#') {
                   7987:       numlinepar++;
                   7988:       fputs(line,stdout);
                   7989:       fputs(line,ficparo);
                   7990:       fputs(line,ficlog);
                   7991:       continue;
                   7992:     }else
                   7993:       break;
                   7994:   }
                   7995:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   7996:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   7997:     if (num_filled != 5) {
                   7998:       printf("Should be 5 parameters\n");
                   7999:     }
1.126     brouard  8000:     numlinepar++;
1.197     brouard  8001:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8002:   }
                   8003:   /* Second parameter line */
                   8004:   while(fgets(line, MAXLINE, ficpar)) {
                   8005:     /* If line starts with a # it is a comment */
                   8006:     if (line[0] == '#') {
                   8007:       numlinepar++;
                   8008:       fputs(line,stdout);
                   8009:       fputs(line,ficparo);
                   8010:       fputs(line,ficlog);
                   8011:       continue;
                   8012:     }else
                   8013:       break;
                   8014:   }
                   8015:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   8016:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   8017:     if (num_filled != 8) {
1.209     brouard  8018:       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");
                   8019:       printf("but line=%s\n",line);
1.197     brouard  8020:     }
                   8021:     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  8022:   }
1.203     brouard  8023:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  8024:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  8025:   /* Third parameter line */
                   8026:   while(fgets(line, MAXLINE, ficpar)) {
                   8027:     /* If line starts with a # it is a comment */
                   8028:     if (line[0] == '#') {
                   8029:       numlinepar++;
                   8030:       fputs(line,stdout);
                   8031:       fputs(line,ficparo);
                   8032:       fputs(line,ficlog);
                   8033:       continue;
                   8034:     }else
                   8035:       break;
                   8036:   }
1.201     brouard  8037:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8038:     if (num_filled == 0)
                   8039:             model[0]='\0';
                   8040:     else if (num_filled != 1){
1.197     brouard  8041:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8042:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8043:       model[0]='\0';
                   8044:       goto end;
                   8045:     }
                   8046:     else{
                   8047:       if (model[0]=='+'){
                   8048:        for(i=1; i<=strlen(model);i++)
                   8049:          modeltemp[i-1]=model[i];
1.201     brouard  8050:        strcpy(model,modeltemp); 
1.197     brouard  8051:       }
                   8052:     }
1.199     brouard  8053:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  8054:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  8055:   }
                   8056:   /* 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); */
                   8057:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8058:   /* 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  8059:   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);
                   8060:   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  8061:   fflush(ficlog);
1.190     brouard  8062:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8063:   if(model[0]=='#'){
1.187     brouard  8064:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8065:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8066:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8067:     if(mle != -1){
                   8068:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8069:       exit(1);
                   8070:     }
                   8071:   }
1.126     brouard  8072:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8073:     ungetc(c,ficpar);
                   8074:     fgets(line, MAXLINE, ficpar);
                   8075:     numlinepar++;
1.195     brouard  8076:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8077:       z[0]=line[1];
                   8078:     }
                   8079:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  8080:     fputs(line, stdout);
                   8081:     //puts(line);
1.126     brouard  8082:     fputs(line,ficparo);
                   8083:     fputs(line,ficlog);
                   8084:   }
                   8085:   ungetc(c,ficpar);
                   8086: 
                   8087:    
1.145     brouard  8088:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  8089:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8090:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8091:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8092:   */
                   8093:   if (strlen(model)>1) 
1.187     brouard  8094:     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  8095:   else
1.187     brouard  8096:     ncovmodel=2; /* Constant and age */
1.133     brouard  8097:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8098:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  8099:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8100:     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);
                   8101:     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);
                   8102:     fflush(stdout);
                   8103:     fclose (ficlog);
                   8104:     goto end;
                   8105:   }
1.126     brouard  8106:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8107:   delti=delti3[1][1];
                   8108:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8109:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8110:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  8111:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8112:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8113:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8114:     fclose (ficparo);
                   8115:     fclose (ficlog);
                   8116:     goto end;
                   8117:     exit(0);
                   8118:   }
1.186     brouard  8119:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  8120:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  8121:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8122:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8123:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8124:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8125:     hess=matrix(1,npar,1,npar);
1.126     brouard  8126:   }
                   8127:   else{
1.145     brouard  8128:     /* Read guessed parameters */
1.126     brouard  8129:     /* Reads comments: lines beginning with '#' */
                   8130:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8131:       ungetc(c,ficpar);
                   8132:       fgets(line, MAXLINE, ficpar);
                   8133:       numlinepar++;
1.141     brouard  8134:       fputs(line,stdout);
1.126     brouard  8135:       fputs(line,ficparo);
                   8136:       fputs(line,ficlog);
                   8137:     }
                   8138:     ungetc(c,ficpar);
                   8139:     
                   8140:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8141:     for(i=1; i <=nlstate; i++){
                   8142:       j=0;
                   8143:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   8144:        if(jj==i) continue;
                   8145:        j++;
                   8146:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  8147:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  8148:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   8149: It might be a problem of design; if ncovcol and the model are correct\n \
                   8150: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   8151:          exit(1);
                   8152:        }
                   8153:        fprintf(ficparo,"%1d%1d",i1,j1);
                   8154:        if(mle==1)
1.193     brouard  8155:          printf("%1d%1d",i,jj);
                   8156:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  8157:        for(k=1; k<=ncovmodel;k++){
                   8158:          fscanf(ficpar," %lf",&param[i][j][k]);
                   8159:          if(mle==1){
                   8160:            printf(" %lf",param[i][j][k]);
                   8161:            fprintf(ficlog," %lf",param[i][j][k]);
                   8162:          }
                   8163:          else
                   8164:            fprintf(ficlog," %lf",param[i][j][k]);
                   8165:          fprintf(ficparo," %lf",param[i][j][k]);
                   8166:        }
                   8167:        fscanf(ficpar,"\n");
                   8168:        numlinepar++;
                   8169:        if(mle==1)
                   8170:          printf("\n");
                   8171:        fprintf(ficlog,"\n");
                   8172:        fprintf(ficparo,"\n");
                   8173:       }
                   8174:     }  
                   8175:     fflush(ficlog);
                   8176: 
1.145     brouard  8177:     /* Reads scales values */
1.126     brouard  8178:     p=param[1][1];
                   8179:     
                   8180:     /* Reads comments: lines beginning with '#' */
                   8181:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8182:       ungetc(c,ficpar);
                   8183:       fgets(line, MAXLINE, ficpar);
                   8184:       numlinepar++;
1.141     brouard  8185:       fputs(line,stdout);
1.126     brouard  8186:       fputs(line,ficparo);
                   8187:       fputs(line,ficlog);
                   8188:     }
                   8189:     ungetc(c,ficpar);
                   8190: 
                   8191:     for(i=1; i <=nlstate; i++){
                   8192:       for(j=1; j <=nlstate+ndeath-1; j++){
                   8193:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  8194:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  8195:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8196:          exit(1);
                   8197:        }
                   8198:        printf("%1d%1d",i,j);
                   8199:        fprintf(ficparo,"%1d%1d",i1,j1);
                   8200:        fprintf(ficlog,"%1d%1d",i1,j1);
                   8201:        for(k=1; k<=ncovmodel;k++){
                   8202:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8203:          printf(" %le",delti3[i][j][k]);
                   8204:          fprintf(ficparo," %le",delti3[i][j][k]);
                   8205:          fprintf(ficlog," %le",delti3[i][j][k]);
                   8206:        }
                   8207:        fscanf(ficpar,"\n");
                   8208:        numlinepar++;
                   8209:        printf("\n");
                   8210:        fprintf(ficparo,"\n");
                   8211:        fprintf(ficlog,"\n");
                   8212:       }
                   8213:     }
                   8214:     fflush(ficlog);
                   8215: 
1.145     brouard  8216:     /* Reads covariance matrix */
1.126     brouard  8217:     delti=delti3[1][1];
                   8218: 
                   8219: 
                   8220:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   8221:   
                   8222:     /* Reads comments: lines beginning with '#' */
                   8223:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8224:       ungetc(c,ficpar);
                   8225:       fgets(line, MAXLINE, ficpar);
                   8226:       numlinepar++;
1.141     brouard  8227:       fputs(line,stdout);
1.126     brouard  8228:       fputs(line,ficparo);
                   8229:       fputs(line,ficlog);
                   8230:     }
                   8231:     ungetc(c,ficpar);
                   8232:   
                   8233:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8234:     hess=matrix(1,npar,1,npar);
1.131     brouard  8235:     for(i=1; i <=npar; i++)
                   8236:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   8237:       
1.194     brouard  8238:     /* Scans npar lines */
1.126     brouard  8239:     for(i=1; i <=npar; i++){
1.194     brouard  8240:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8241:       if(count != 3){
                   8242:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   8243: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8244: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   8245:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   8246: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8247: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   8248:        exit(1);
                   8249:       }else
1.126     brouard  8250:       if(mle==1)
1.194     brouard  8251:        printf("%1d%1d%1d",i1,j1,jk);
                   8252:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   8253:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  8254:       for(j=1; j <=i; j++){
                   8255:        fscanf(ficpar," %le",&matcov[i][j]);
                   8256:        if(mle==1){
                   8257:          printf(" %.5le",matcov[i][j]);
                   8258:        }
                   8259:        fprintf(ficlog," %.5le",matcov[i][j]);
                   8260:        fprintf(ficparo," %.5le",matcov[i][j]);
                   8261:       }
                   8262:       fscanf(ficpar,"\n");
                   8263:       numlinepar++;
                   8264:       if(mle==1)
                   8265:        printf("\n");
                   8266:       fprintf(ficlog,"\n");
                   8267:       fprintf(ficparo,"\n");
                   8268:     }
1.194     brouard  8269:     /* End of read covariance matrix npar lines */
1.126     brouard  8270:     for(i=1; i <=npar; i++)
                   8271:       for(j=i+1;j<=npar;j++)
                   8272:        matcov[i][j]=matcov[j][i];
                   8273:     
                   8274:     if(mle==1)
                   8275:       printf("\n");
                   8276:     fprintf(ficlog,"\n");
                   8277:     
                   8278:     fflush(ficlog);
                   8279:     
                   8280:     /*-------- Rewriting parameter file ----------*/
                   8281:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   8282:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   8283:     strcat(rfileres,".");    /* */
                   8284:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   8285:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  8286:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   8287:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  8288:     }
                   8289:     fprintf(ficres,"#%s\n",version);
                   8290:   }    /* End of mle != -3 */
                   8291: 
1.186     brouard  8292:   /*  Main data
                   8293:    */
1.126     brouard  8294:   n= lastobs;
                   8295:   num=lvector(1,n);
                   8296:   moisnais=vector(1,n);
                   8297:   annais=vector(1,n);
                   8298:   moisdc=vector(1,n);
                   8299:   andc=vector(1,n);
                   8300:   agedc=vector(1,n);
                   8301:   cod=ivector(1,n);
                   8302:   weight=vector(1,n);
                   8303:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   8304:   mint=matrix(1,maxwav,1,n);
                   8305:   anint=matrix(1,maxwav,1,n);
1.131     brouard  8306:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  8307:   tab=ivector(1,NCOVMAX);
1.144     brouard  8308:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  8309:   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  8310: 
1.136     brouard  8311:   /* Reads data from file datafile */
                   8312:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   8313:     goto end;
                   8314: 
                   8315:   /* Calculation of the number of parameters from char model */
1.137     brouard  8316:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   8317:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   8318:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   8319:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   8320:        k=1 Tvar[1]=2 (from V2)
                   8321:     */
                   8322:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   8323:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   8324:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   8325:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   8326:   */
                   8327:   /* For model-covariate k tells which data-covariate to use but
                   8328:     because this model-covariate is a construction we invent a new column
                   8329:     ncovcol + k1
                   8330:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   8331:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  8332:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  8333:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   8334:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   8335:   */
1.145     brouard  8336:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   8337:   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  8338:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   8339:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  8340:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  8341:                         4 covariates (3 plus signs)
                   8342:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   8343:                      */  
1.136     brouard  8344: 
1.186     brouard  8345: /* Main decodemodel */
                   8346: 
1.187     brouard  8347: 
1.136     brouard  8348:   if(decodemodel(model, lastobs) == 1)
                   8349:     goto end;
                   8350: 
1.137     brouard  8351:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   8352:     nbwarn++;
                   8353:     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); 
                   8354:     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); 
                   8355:   }
1.136     brouard  8356:     /*  if(mle==1){*/
1.137     brouard  8357:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   8358:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  8359:   }
                   8360: 
                   8361:     /*-calculation of age at interview from date of interview and age at death -*/
                   8362:   agev=matrix(1,maxwav,1,imx);
                   8363: 
                   8364:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   8365:     goto end;
                   8366: 
1.126     brouard  8367: 
1.136     brouard  8368:   agegomp=(int)agemin;
                   8369:   free_vector(moisnais,1,n);
                   8370:   free_vector(annais,1,n);
1.126     brouard  8371:   /* free_matrix(mint,1,maxwav,1,n);
                   8372:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  8373:   /* free_vector(moisdc,1,n); */
                   8374:   /* free_vector(andc,1,n); */
1.145     brouard  8375:   /* */
                   8376:   
1.126     brouard  8377:   wav=ivector(1,imx);
1.214     brouard  8378:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8379:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8380:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8381:   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.*/
                   8382:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   8383:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  8384:    
                   8385:   /* Concatenates waves */
1.214     brouard  8386:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   8387:      Death is a valid wave (if date is known).
                   8388:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   8389:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   8390:      and mw[mi+1][i]. dh depends on stepm.
                   8391:   */
                   8392: 
1.126     brouard  8393:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  8394:   /* */
                   8395:  
1.215     brouard  8396:   free_vector(moisdc,1,n);
                   8397:   free_vector(andc,1,n);
                   8398: 
1.126     brouard  8399:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   8400: 
                   8401:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   8402:   ncodemax[1]=1;
1.145     brouard  8403:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  8404:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  8405:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211     brouard  8406:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  8407:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  8408:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  8409: 
1.200     brouard  8410:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  8411:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  8412:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  8413:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   8414:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   8415:    * (currently 0 or 1) in the data.
                   8416:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   8417:    * corresponding modality (h,j).
                   8418:    */
                   8419: 
1.145     brouard  8420:   h=0;
                   8421: 
                   8422: 
                   8423:   /*if (cptcovn > 0) */
1.126     brouard  8424:       
1.145     brouard  8425:  
1.126     brouard  8426:   m=pow(2,cptcoveff);
                   8427:  
1.144     brouard  8428:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  8429:           * For k=4 covariates, h goes from 1 to m=2**k
                   8430:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   8431:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  8432:           *     h\k   1     2     3     4
1.143     brouard  8433:           *______________________________  
                   8434:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   8435:           *     2     2     1     1     1
                   8436:           *     3 i=2 1     2     1     1
                   8437:           *     4     2     2     1     1
                   8438:           *     5 i=3 1 i=2 1     2     1
                   8439:           *     6     2     1     2     1
                   8440:           *     7 i=4 1     2     2     1
                   8441:           *     8     2     2     2     1
1.197     brouard  8442:           *     9 i=5 1 i=3 1 i=2 1     2
                   8443:           *    10     2     1     1     2
                   8444:           *    11 i=6 1     2     1     2
                   8445:           *    12     2     2     1     2
                   8446:           *    13 i=7 1 i=4 1     2     2    
                   8447:           *    14     2     1     2     2
                   8448:           *    15 i=8 1     2     2     2
                   8449:           *    16     2     2     2     2
1.143     brouard  8450:           */
1.212     brouard  8451:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  8452:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   8453:      * and the value of each covariate?
                   8454:      * V1=1, V2=1, V3=2, V4=1 ?
                   8455:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   8456:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   8457:      * In order to get the real value in the data, we use nbcode
                   8458:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   8459:      * We are keeping this crazy system in order to be able (in the future?) 
                   8460:      * to have more than 2 values (0 or 1) for a covariate.
                   8461:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   8462:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   8463:      *              bbbbbbbb
                   8464:      *              76543210     
                   8465:      *   h-1        00000101 (6-1=5)
                   8466:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
                   8467:      *           &
                   8468:      *     1        00000001 (1)
                   8469:      *              00000001        = 1 & ((h-1) >> (k-1))
                   8470:      *          +1= 00000010 =2 
                   8471:      *
                   8472:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   8473:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   8474:      *    >>k'            11
                   8475:      *          &   00000001
                   8476:      *            = 00000001
                   8477:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   8478:      * Reverse h=6 and m=16?
                   8479:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   8480:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   8481:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   8482:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   8483:      * V3=decodtabm(14,3,2**4)=2
                   8484:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   8485:      *(h-1) >> (j-1)    0011 =13 >> 2
                   8486:      *          &1 000000001
                   8487:      *           = 000000001
                   8488:      *         +1= 000000010 =2
                   8489:      *                  2211
                   8490:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   8491:      *                  V3=2
                   8492:      */
                   8493: 
1.202     brouard  8494:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   8495:   /*   /\* printf("h=%2d ", h); *\/ */
                   8496:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   8497:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   8498:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   8499:   /*    /\* } *\/ */
                   8500:   /*    /\* printf("\n"); *\/ */
                   8501:   /* } */
1.197     brouard  8502:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   8503:   /*   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 *\/  */
                   8504:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   8505:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   8506:   /*     h++; */
                   8507:   /*     if (h>m)  */
                   8508:   /*       h=1; */
                   8509:   /*     codtab[h][k]=j; */
                   8510:   /*     /\* codtab[12][3]=1; *\/ */
                   8511:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   8512:   /*     /\* 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]]); *\/ */
                   8513:   /*   }  */
                   8514:   /*     } */
                   8515:   /*   } */
                   8516:   /* }  */
1.126     brouard  8517:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   8518:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  8519:   /* for(i=1; i <=m ;i++){  */
                   8520:   /*    for(k=1; k <=cptcovn; k++){ */
                   8521:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   8522:   /*    } */
                   8523:   /*    printf("\n"); */
                   8524:   /* } */
                   8525:   /*   scanf("%d",i);*/
1.145     brouard  8526: 
                   8527:  free_ivector(Ndum,-1,NCOVMAX);
                   8528: 
                   8529: 
1.126     brouard  8530:     
1.186     brouard  8531:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  8532:   strcpy(optionfilegnuplot,optionfilefiname);
                   8533:   if(mle==-3)
1.201     brouard  8534:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  8535:   strcat(optionfilegnuplot,".gp");
                   8536: 
                   8537:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   8538:     printf("Problem with file %s",optionfilegnuplot);
                   8539:   }
                   8540:   else{
1.204     brouard  8541:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  8542:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  8543:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   8544:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  8545:   }
                   8546:   /*  fclose(ficgp);*/
1.186     brouard  8547: 
                   8548: 
                   8549:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  8550: 
                   8551:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   8552:   if(mle==-3)
1.201     brouard  8553:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  8554:   strcat(optionfilehtm,".htm");
                   8555:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  8556:     printf("Problem with %s \n",optionfilehtm);
                   8557:     exit(0);
1.126     brouard  8558:   }
                   8559: 
                   8560:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   8561:   strcat(optionfilehtmcov,"-cov.htm");
                   8562:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   8563:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   8564:   }
                   8565:   else{
                   8566:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   8567: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8568: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  8569:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   8570:   }
                   8571: 
1.213     brouard  8572:   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  8573: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   8574: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  8575: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8576: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  8577: \n\
                   8578: <hr  size=\"2\" color=\"#EC5E5E\">\
                   8579:  <ul><li><h4>Parameter files</h4>\n\
                   8580:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   8581:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   8582:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   8583:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   8584:  - Date and time at start: %s</ul>\n",\
                   8585:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   8586:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   8587:          fileres,fileres,\
                   8588:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   8589:   fflush(fichtm);
                   8590: 
                   8591:   strcpy(pathr,path);
                   8592:   strcat(pathr,optionfilefiname);
1.184     brouard  8593: #ifdef WIN32
                   8594:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   8595: #else
1.126     brouard  8596:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  8597: #endif
                   8598:          
1.126     brouard  8599:   
                   8600:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   8601:      and prints on file fileres'p'. */
1.214     brouard  8602:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
                   8603:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  8604: 
                   8605:   fprintf(fichtm,"\n");
                   8606:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   8607: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   8608: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   8609:          imx,agemin,agemax,jmin,jmax,jmean);
                   8610:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8611:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8612:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8613:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   8614:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   8615:     
                   8616:    
                   8617:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   8618:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   8619:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   8620: 
                   8621:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  8622:   /* For mortality only */
1.126     brouard  8623:   if (mle==-3){
1.136     brouard  8624:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  8625:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  8626:     cens=ivector(1,n);
                   8627:     ageexmed=vector(1,n);
                   8628:     agecens=vector(1,n);
                   8629:     dcwave=ivector(1,n);
                   8630:  
                   8631:     for (i=1; i<=imx; i++){
                   8632:       dcwave[i]=-1;
                   8633:       for (m=firstpass; m<=lastpass; m++)
                   8634:        if (s[m][i]>nlstate) {
                   8635:          dcwave[i]=m;
                   8636:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   8637:          break;
                   8638:        }
                   8639:     }
                   8640: 
                   8641:     for (i=1; i<=imx; i++) {
                   8642:       if (wav[i]>0){
                   8643:        ageexmed[i]=agev[mw[1][i]][i];
                   8644:        j=wav[i];
                   8645:        agecens[i]=1.; 
                   8646: 
                   8647:        if (ageexmed[i]> 1 && wav[i] > 0){
                   8648:          agecens[i]=agev[mw[j][i]][i];
                   8649:          cens[i]= 1;
                   8650:        }else if (ageexmed[i]< 1) 
                   8651:          cens[i]= -1;
                   8652:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   8653:          cens[i]=0 ;
                   8654:       }
                   8655:       else cens[i]=-1;
                   8656:     }
                   8657:     
                   8658:     for (i=1;i<=NDIM;i++) {
                   8659:       for (j=1;j<=NDIM;j++)
                   8660:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   8661:     }
                   8662:     
1.145     brouard  8663:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  8664:     /*printf("%lf %lf", p[1], p[2]);*/
                   8665:     
                   8666:     
1.136     brouard  8667: #ifdef GSL
                   8668:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  8669: #else
1.126     brouard  8670:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  8671: #endif
1.201     brouard  8672:     strcpy(filerespow,"POW-MORT_"); 
                   8673:     strcat(filerespow,fileresu);
1.126     brouard  8674:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   8675:       printf("Problem with resultfile: %s\n", filerespow);
                   8676:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   8677:     }
1.136     brouard  8678: #ifdef GSL
                   8679:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  8680: #else
1.126     brouard  8681:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  8682: #endif
1.126     brouard  8683:     /*  for (i=1;i<=nlstate;i++)
                   8684:        for(j=1;j<=nlstate+ndeath;j++)
                   8685:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   8686:     */
                   8687:     fprintf(ficrespow,"\n");
1.136     brouard  8688: #ifdef GSL
                   8689:     /* gsl starts here */ 
                   8690:     T = gsl_multimin_fminimizer_nmsimplex;
                   8691:     gsl_multimin_fminimizer *sfm = NULL;
                   8692:     gsl_vector *ss, *x;
                   8693:     gsl_multimin_function minex_func;
                   8694: 
                   8695:     /* Initial vertex size vector */
                   8696:     ss = gsl_vector_alloc (NDIM);
                   8697:     
                   8698:     if (ss == NULL){
                   8699:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   8700:     }
                   8701:     /* Set all step sizes to 1 */
                   8702:     gsl_vector_set_all (ss, 0.001);
                   8703: 
                   8704:     /* Starting point */
1.126     brouard  8705:     
1.136     brouard  8706:     x = gsl_vector_alloc (NDIM);
                   8707:     
                   8708:     if (x == NULL){
                   8709:       gsl_vector_free(ss);
                   8710:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   8711:     }
                   8712:   
                   8713:     /* Initialize method and iterate */
                   8714:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  8715:     /*     gsl_vector_set(x, 0, 0.0268); */
                   8716:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  8717:     gsl_vector_set(x, 0, p[1]);
                   8718:     gsl_vector_set(x, 1, p[2]);
                   8719: 
                   8720:     minex_func.f = &gompertz_f;
                   8721:     minex_func.n = NDIM;
                   8722:     minex_func.params = (void *)&p; /* ??? */
                   8723:     
                   8724:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   8725:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   8726:     
                   8727:     printf("Iterations beginning .....\n\n");
                   8728:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   8729: 
                   8730:     iteri=0;
                   8731:     while (rval == GSL_CONTINUE){
                   8732:       iteri++;
                   8733:       status = gsl_multimin_fminimizer_iterate(sfm);
                   8734:       
                   8735:       if (status) printf("error: %s\n", gsl_strerror (status));
                   8736:       fflush(0);
                   8737:       
                   8738:       if (status) 
                   8739:         break;
                   8740:       
                   8741:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   8742:       ssval = gsl_multimin_fminimizer_size (sfm);
                   8743:       
                   8744:       if (rval == GSL_SUCCESS)
                   8745:         printf ("converged to a local maximum at\n");
                   8746:       
                   8747:       printf("%5d ", iteri);
                   8748:       for (it = 0; it < NDIM; it++){
                   8749:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   8750:       }
                   8751:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   8752:     }
                   8753:     
                   8754:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   8755:     
                   8756:     gsl_vector_free(x); /* initial values */
                   8757:     gsl_vector_free(ss); /* inital step size */
                   8758:     for (it=0; it<NDIM; it++){
                   8759:       p[it+1]=gsl_vector_get(sfm->x,it);
                   8760:       fprintf(ficrespow," %.12lf", p[it]);
                   8761:     }
                   8762:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   8763: #endif
                   8764: #ifdef POWELL
                   8765:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   8766: #endif  
1.126     brouard  8767:     fclose(ficrespow);
                   8768:     
1.203     brouard  8769:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  8770: 
                   8771:     for(i=1; i <=NDIM; i++)
                   8772:       for(j=i+1;j<=NDIM;j++)
                   8773:        matcov[i][j]=matcov[j][i];
                   8774:     
                   8775:     printf("\nCovariance matrix\n ");
1.203     brouard  8776:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  8777:     for(i=1; i <=NDIM; i++) {
                   8778:       for(j=1;j<=NDIM;j++){ 
                   8779:        printf("%f ",matcov[i][j]);
1.203     brouard  8780:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  8781:       }
1.203     brouard  8782:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  8783:     }
                   8784:     
                   8785:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  8786:     for (i=1;i<=NDIM;i++) {
1.126     brouard  8787:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  8788:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   8789:     }
1.126     brouard  8790:     lsurv=vector(1,AGESUP);
                   8791:     lpop=vector(1,AGESUP);
                   8792:     tpop=vector(1,AGESUP);
                   8793:     lsurv[agegomp]=100000;
                   8794:     
                   8795:     for (k=agegomp;k<=AGESUP;k++) {
                   8796:       agemortsup=k;
                   8797:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   8798:     }
                   8799:     
                   8800:     for (k=agegomp;k<agemortsup;k++)
                   8801:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   8802:     
                   8803:     for (k=agegomp;k<agemortsup;k++){
                   8804:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   8805:       sumlpop=sumlpop+lpop[k];
                   8806:     }
                   8807:     
                   8808:     tpop[agegomp]=sumlpop;
                   8809:     for (k=agegomp;k<(agemortsup-3);k++){
                   8810:       /*  tpop[k+1]=2;*/
                   8811:       tpop[k+1]=tpop[k]-lpop[k];
                   8812:     }
                   8813:     
                   8814:     
                   8815:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   8816:     for (k=agegomp;k<(agemortsup-2);k++) 
                   8817:       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]);
                   8818:     
                   8819:     
                   8820:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8821:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   8822:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8823: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8824: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8825:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8826: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8827: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8828:     }else
1.201     brouard  8829:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   8830:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  8831:                     stepm, weightopt,\
                   8832:                     model,imx,p,matcov,agemortsup);
                   8833:     
                   8834:     free_vector(lsurv,1,AGESUP);
                   8835:     free_vector(lpop,1,AGESUP);
                   8836:     free_vector(tpop,1,AGESUP);
1.136     brouard  8837: #ifdef GSL
                   8838:     free_ivector(cens,1,n);
                   8839:     free_vector(agecens,1,n);
                   8840:     free_ivector(dcwave,1,n);
                   8841:     free_matrix(ximort,1,NDIM,1,NDIM);
                   8842: #endif
1.186     brouard  8843:   } /* Endof if mle==-3 mortality only */
1.205     brouard  8844:   /* Standard  */
                   8845:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   8846:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8847:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  8848:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  8849:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8850:     for (k=1; k<=npar;k++)
                   8851:       printf(" %d %8.5f",k,p[k]);
                   8852:     printf("\n");
1.205     brouard  8853:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   8854:       /* mlikeli uses func not funcone */
                   8855:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   8856:     }
                   8857:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   8858:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8859:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   8860:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8861:     }
                   8862:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  8863:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8864:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8865:     for (k=1; k<=npar;k++)
                   8866:       printf(" %d %8.5f",k,p[k]);
                   8867:     printf("\n");
                   8868:     
                   8869:     /*--------- results files --------------*/
1.192     brouard  8870:     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  8871:     
                   8872:     
                   8873:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8874:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8875:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8876:     for(i=1,jk=1; i <=nlstate; i++){
                   8877:       for(k=1; k <=(nlstate+ndeath); k++){
                   8878:        if (k != i) {
                   8879:          printf("%d%d ",i,k);
                   8880:          fprintf(ficlog,"%d%d ",i,k);
                   8881:          fprintf(ficres,"%1d%1d ",i,k);
                   8882:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  8883:            printf("%12.7f ",p[jk]);
                   8884:            fprintf(ficlog,"%12.7f ",p[jk]);
                   8885:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  8886:            jk++; 
                   8887:          }
                   8888:          printf("\n");
                   8889:          fprintf(ficlog,"\n");
                   8890:          fprintf(ficres,"\n");
                   8891:        }
                   8892:       }
                   8893:     }
1.203     brouard  8894:     if(mle != 0){
                   8895:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  8896:       ftolhess=ftol; /* Usually correct */
1.203     brouard  8897:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   8898:       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");
                   8899:       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");
                   8900:       for(i=1,jk=1; i <=nlstate; i++){
                   8901:        for(k=1; k <=(nlstate+ndeath); k++){
                   8902:          if (k != i) {
                   8903:            printf("%d%d ",i,k);
                   8904:            fprintf(ficlog,"%d%d ",i,k);
                   8905:            for(j=1; j <=ncovmodel; j++){
                   8906:              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]));
                   8907:              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]));
                   8908:              jk++; 
                   8909:            }
                   8910:            printf("\n");
                   8911:            fprintf(ficlog,"\n");
1.193     brouard  8912:          }
                   8913:        }
                   8914:       }
1.203     brouard  8915:     } /* end of hesscov and Wald tests */
1.193     brouard  8916: 
1.203     brouard  8917:     /*  */
1.126     brouard  8918:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   8919:     printf("# Scales (for hessian or gradient estimation)\n");
                   8920:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   8921:     for(i=1,jk=1; i <=nlstate; i++){
                   8922:       for(j=1; j <=nlstate+ndeath; j++){
                   8923:        if (j!=i) {
                   8924:          fprintf(ficres,"%1d%1d",i,j);
                   8925:          printf("%1d%1d",i,j);
                   8926:          fprintf(ficlog,"%1d%1d",i,j);
                   8927:          for(k=1; k<=ncovmodel;k++){
                   8928:            printf(" %.5e",delti[jk]);
                   8929:            fprintf(ficlog," %.5e",delti[jk]);
                   8930:            fprintf(ficres," %.5e",delti[jk]);
                   8931:            jk++;
                   8932:          }
                   8933:          printf("\n");
                   8934:          fprintf(ficlog,"\n");
                   8935:          fprintf(ficres,"\n");
                   8936:        }
                   8937:       }
                   8938:     }
                   8939:     
                   8940:     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  8941:     if(mle >= 1) /* To big for the screen */
1.126     brouard  8942:       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");
                   8943:     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");
                   8944:     /* # 121 Var(a12)\n\ */
                   8945:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8946:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8947:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8948:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8949:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8950:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8951:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8952:     
                   8953:     
                   8954:     /* Just to have a covariance matrix which will be more understandable
                   8955:        even is we still don't want to manage dictionary of variables
                   8956:     */
                   8957:     for(itimes=1;itimes<=2;itimes++){
                   8958:       jj=0;
                   8959:       for(i=1; i <=nlstate; i++){
                   8960:        for(j=1; j <=nlstate+ndeath; j++){
                   8961:          if(j==i) continue;
                   8962:          for(k=1; k<=ncovmodel;k++){
                   8963:            jj++;
                   8964:            ca[0]= k+'a'-1;ca[1]='\0';
                   8965:            if(itimes==1){
                   8966:              if(mle>=1)
                   8967:                printf("#%1d%1d%d",i,j,k);
                   8968:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   8969:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   8970:            }else{
                   8971:              if(mle>=1)
                   8972:                printf("%1d%1d%d",i,j,k);
                   8973:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   8974:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   8975:            }
                   8976:            ll=0;
                   8977:            for(li=1;li <=nlstate; li++){
                   8978:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   8979:                if(lj==li) continue;
                   8980:                for(lk=1;lk<=ncovmodel;lk++){
                   8981:                  ll++;
                   8982:                  if(ll<=jj){
                   8983:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   8984:                    if(ll<jj){
                   8985:                      if(itimes==1){
                   8986:                        if(mle>=1)
                   8987:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8988:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8989:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8990:                      }else{
                   8991:                        if(mle>=1)
                   8992:                          printf(" %.5e",matcov[jj][ll]); 
                   8993:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   8994:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   8995:                      }
                   8996:                    }else{
                   8997:                      if(itimes==1){
                   8998:                        if(mle>=1)
                   8999:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   9000:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9001:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9002:                      }else{
                   9003:                        if(mle>=1)
1.203     brouard  9004:                          printf(" %.7e",matcov[jj][ll]); 
                   9005:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9006:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  9007:                      }
                   9008:                    }
                   9009:                  }
                   9010:                } /* end lk */
                   9011:              } /* end lj */
                   9012:            } /* end li */
                   9013:            if(mle>=1)
                   9014:              printf("\n");
                   9015:            fprintf(ficlog,"\n");
                   9016:            fprintf(ficres,"\n");
                   9017:            numlinepar++;
                   9018:          } /* end k*/
                   9019:        } /*end j */
                   9020:       } /* end i */
                   9021:     } /* end itimes */
                   9022:     
                   9023:     fflush(ficlog);
                   9024:     fflush(ficres);
1.209     brouard  9025:       while(fgets(line, MAXLINE, ficpar)) {
                   9026:     /* If line starts with a # it is a comment */
                   9027:     if (line[0] == '#') {
                   9028:       numlinepar++;
1.141     brouard  9029:       fputs(line,stdout);
1.126     brouard  9030:       fputs(line,ficparo);
1.209     brouard  9031:       fputs(line,ficlog);
                   9032:       continue;
                   9033:     }else
                   9034:       break;
                   9035:   }
                   9036: 
                   9037:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9038:     /*   ungetc(c,ficpar); */
                   9039:     /*   fgets(line, MAXLINE, ficpar); */
                   9040:     /*   fputs(line,stdout); */
                   9041:     /*   fputs(line,ficparo); */
                   9042:     /* } */
                   9043:     /* ungetc(c,ficpar); */
1.126     brouard  9044:     
                   9045:     estepm=0;
1.209     brouard  9046:     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){
                   9047: 
                   9048:     if (num_filled != 6) {
                   9049:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
                   9050:       printf("but line=%s\n",line);
                   9051:       goto end;
                   9052:     }
                   9053:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9054:   }
                   9055:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9056:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9057: 
                   9058:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  9059:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9060:     if (fage <= 2) {
                   9061:       bage = ageminpar;
                   9062:       fage = agemaxpar;
                   9063:     }
                   9064:     
                   9065:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  9066:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9067:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186     brouard  9068: 
                   9069:     /* Other stuffs, more or less useful */    
1.126     brouard  9070:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9071:       ungetc(c,ficpar);
                   9072:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9073:       fputs(line,stdout);
1.126     brouard  9074:       fputs(line,ficparo);
                   9075:     }
                   9076:     ungetc(c,ficpar);
                   9077:     
                   9078:     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);
                   9079:     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);
                   9080:     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);
                   9081:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9082:     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);
                   9083:     
                   9084:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9085:       ungetc(c,ficpar);
                   9086:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9087:       fputs(line,stdout);
1.126     brouard  9088:       fputs(line,ficparo);
                   9089:     }
                   9090:     ungetc(c,ficpar);
                   9091:     
                   9092:     
                   9093:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9094:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9095:     
                   9096:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  9097:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  9098:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9099:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9100:     
                   9101:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9102:       ungetc(c,ficpar);
                   9103:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9104:       fputs(line,stdout);
1.126     brouard  9105:       fputs(line,ficparo);
                   9106:     }
                   9107:     ungetc(c,ficpar);
                   9108:     
                   9109:     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);
                   9110:     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);
                   9111:     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);
                   9112:     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);
                   9113:     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);
                   9114:     /* day and month of proj2 are not used but only year anproj2.*/
                   9115:     
1.217   ! brouard  9116:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          9117:       ungetc(c,ficpar);
        !          9118:       fgets(line, MAXLINE, ficpar);
        !          9119:       fputs(line,stdout);
        !          9120:       fputs(line,ficparo);
        !          9121:     }
        !          9122:     ungetc(c,ficpar);
        !          9123:     
        !          9124:     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);
        !          9125:     fscanf(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);
        !          9126:     fscanf(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);
        !          9127:     fscanf(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);
        !          9128:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  9129:     
                   9130:     
1.145     brouard  9131:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   9132:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  9133:     
                   9134:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9135:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   9136:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9137: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9138: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9139:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9140: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9141: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9142:     }else
1.211     brouard  9143:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126     brouard  9144:     
1.201     brouard  9145:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.217   ! brouard  9146:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
1.213     brouard  9147:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.126     brouard  9148:       
                   9149:    /*------------ free_vector  -------------*/
                   9150:    /*  chdir(path); */
                   9151:  
1.215     brouard  9152:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9153:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9154:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9155:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  9156:     free_lvector(num,1,n);
                   9157:     free_vector(agedc,1,n);
                   9158:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9159:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9160:     fclose(ficparo);
                   9161:     fclose(ficres);
                   9162: 
                   9163: 
1.186     brouard  9164:     /* Other results (useful)*/
                   9165: 
                   9166: 
1.126     brouard  9167:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  9168:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9169:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  9170:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  9171:     fclose(ficrespl);
                   9172: 
1.217   ! brouard  9173:     /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
        !          9174:     /*#include "prevlim.h"*/  /* Use ficresplb, ficlog */
        !          9175:     bprlim=matrix(1,nlstate,1,nlstate);
        !          9176:     back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
        !          9177:     fclose(ficresplb);
        !          9178: 
        !          9179:     
1.145     brouard  9180: #ifdef FREEEXIT2
                   9181: #include "freeexit2.h"
                   9182: #endif
                   9183: 
1.126     brouard  9184:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  9185:     /*#include "hpijx.h"*/
                   9186:     hPijx(p, bage, fage);
1.145     brouard  9187:     fclose(ficrespij);
1.126     brouard  9188: 
1.217   ! brouard  9189:     hBijx(p, bage, fage);
        !          9190:     fclose(ficrespijb);
        !          9191: 
1.145     brouard  9192:   /*-------------- Variance of one-step probabilities---*/
                   9193:     k=1;
1.126     brouard  9194:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9195: 
                   9196: 
                   9197:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   9198:     for(i=1;i<=AGESUP;i++)
                   9199:       for(j=1;j<=NCOVMAX;j++)
                   9200:        for(k=1;k<=NCOVMAX;k++)
                   9201:          probs[i][j][k]=0.;
                   9202: 
                   9203:     /*---------- Forecasting ------------------*/
                   9204:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9205:     if(prevfcast==1){
                   9206:       /*    if(stepm ==1){*/
1.201     brouard  9207:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  9208:     }
1.217   ! brouard  9209:     if(backcast==1){
        !          9210:       prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff);
        !          9211:     }
        !          9212:     /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
        !          9213:     /*      }  */
        !          9214:     /*      else{ */
        !          9215:     /*        erreur=108; */
        !          9216:     /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
        !          9217:     /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
        !          9218:     /*      } */
        !          9219:     
1.186     brouard  9220:  
                   9221:     /* ------ Other prevalence ratios------------ */
1.126     brouard  9222: 
1.127     brouard  9223:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   9224: 
                   9225:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   9226:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
                   9227:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   9228:     */
1.215     brouard  9229:     free_ivector(wav,1,imx);
                   9230:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9231:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9232:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
                   9233: 
1.126     brouard  9234: 
1.127     brouard  9235:     if (mobilav!=0) {
                   9236:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   9237:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   9238:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9239:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9240:       }
1.126     brouard  9241:     }
                   9242: 
                   9243: 
1.127     brouard  9244:     /*---------- Health expectancies, no variances ------------*/
                   9245: 
1.201     brouard  9246:     strcpy(filerese,"E_");
                   9247:     strcat(filerese,fileresu);
1.126     brouard  9248:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9249:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9250:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9251:     }
1.208     brouard  9252:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9253:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  9254:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9255:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9256:           
                   9257:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  9258:        fprintf(ficreseij,"\n#****** ");
                   9259:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  9260:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  9261:        }
                   9262:        fprintf(ficreseij,"******\n");
                   9263: 
                   9264:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9265:        oldm=oldms;savm=savms;
                   9266:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   9267:       
                   9268:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  9269:       /*}*/
1.127     brouard  9270:     }
                   9271:     fclose(ficreseij);
1.208     brouard  9272:     printf("done evsij\n");fflush(stdout);
                   9273:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  9274: 
                   9275:     /*---------- Health expectancies and variances ------------*/
                   9276: 
                   9277: 
1.201     brouard  9278:     strcpy(filerest,"T_");
                   9279:     strcat(filerest,fileresu);
1.127     brouard  9280:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   9281:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   9282:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   9283:     }
1.208     brouard  9284:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   9285:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  9286: 
1.126     brouard  9287: 
1.201     brouard  9288:     strcpy(fileresstde,"STDE_");
                   9289:     strcat(fileresstde,fileresu);
1.126     brouard  9290:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   9291:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9292:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9293:     }
1.208     brouard  9294:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9295:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  9296: 
1.201     brouard  9297:     strcpy(filerescve,"CVE_");
                   9298:     strcat(filerescve,fileresu);
1.126     brouard  9299:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   9300:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9301:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9302:     }
1.208     brouard  9303:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9304:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  9305: 
1.201     brouard  9306:     strcpy(fileresv,"V_");
                   9307:     strcat(fileresv,fileresu);
1.126     brouard  9308:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   9309:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9310:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9311:     }
1.208     brouard  9312:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   9313:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  9314: 
1.145     brouard  9315:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9316:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9317:           
                   9318:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  9319:       fprintf(ficrest,"\n#****** ");
                   9320:       for(j=1;j<=cptcoveff;j++) 
                   9321:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9322:       fprintf(ficrest,"******\n");
                   9323:       
                   9324:       fprintf(ficresstdeij,"\n#****** ");
                   9325:       fprintf(ficrescveij,"\n#****** ");
                   9326:       for(j=1;j<=cptcoveff;j++) {
                   9327:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9328:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9329:       }
                   9330:       fprintf(ficresstdeij,"******\n");
                   9331:       fprintf(ficrescveij,"******\n");
                   9332:       
                   9333:       fprintf(ficresvij,"\n#****** ");
                   9334:       for(j=1;j<=cptcoveff;j++) 
                   9335:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9336:       fprintf(ficresvij,"******\n");
                   9337:       
                   9338:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9339:       oldm=oldms;savm=savms;
                   9340:       printf(" cvevsij %d, ",k);
                   9341:       fprintf(ficlog, " cvevsij %d, ",k);
                   9342:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   9343:       printf(" end cvevsij \n ");
                   9344:       fprintf(ficlog, " end cvevsij \n ");
                   9345:       
                   9346:       /*
                   9347:        */
                   9348:       /* goto endfree; */
                   9349:       
                   9350:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9351:       pstamp(ficrest);
                   9352:       
                   9353:       
                   9354:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   9355:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   9356:        cptcod= 0; /* To be deleted */
                   9357:        printf("varevsij %d \n",vpopbased);
                   9358:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209     brouard  9359:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.208     brouard  9360:        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 ");
                   9361:        if(vpopbased==1)
                   9362:          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);
                   9363:        else
                   9364:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   9365:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   9366:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   9367:        fprintf(ficrest,"\n");
                   9368:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   9369:        epj=vector(1,nlstate+1);
                   9370:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   9371:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   9372:        for(age=bage; age <=fage ;age++){
1.209     brouard  9373:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  9374:          if (vpopbased==1) {
                   9375:            if(mobilav ==0){
                   9376:              for(i=1; i<=nlstate;i++)
                   9377:                prlim[i][i]=probs[(int)age][i][k];
                   9378:            }else{ /* mobilav */ 
                   9379:              for(i=1; i<=nlstate;i++)
                   9380:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  9381:            }
1.208     brouard  9382:          }
                   9383:          
                   9384:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   9385:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   9386:          /* printf(" age %4.0f ",age); */
                   9387:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   9388:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   9389:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   9390:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   9391:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  9392:            }
1.208     brouard  9393:            epj[nlstate+1] +=epj[j];
                   9394:          }
                   9395:          /* printf(" age %4.0f \n",age); */
                   9396:          
                   9397:          for(i=1, vepp=0.;i <=nlstate;i++)
                   9398:            for(j=1;j <=nlstate;j++)
                   9399:              vepp += vareij[i][j][(int)age];
                   9400:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   9401:          for(j=1;j <=nlstate;j++){
                   9402:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  9403:          }
1.208     brouard  9404:          fprintf(ficrest,"\n");
1.126     brouard  9405:        }
1.208     brouard  9406:       } /* End vpopbased */
                   9407:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9408:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9409:       free_vector(epj,1,nlstate+1);
                   9410:       printf("done \n");fflush(stdout);
                   9411:       fprintf(ficlog,"done\n");fflush(ficlog);
                   9412:       
1.145     brouard  9413:       /*}*/
1.208     brouard  9414:     } /* End k */
1.126     brouard  9415:     free_vector(weight,1,n);
1.145     brouard  9416:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  9417:     free_imatrix(s,1,maxwav+1,1,n);
                   9418:     free_matrix(anint,1,maxwav,1,n); 
                   9419:     free_matrix(mint,1,maxwav,1,n);
                   9420:     free_ivector(cod,1,n);
                   9421:     free_ivector(tab,1,NCOVMAX);
                   9422:     fclose(ficresstdeij);
                   9423:     fclose(ficrescveij);
                   9424:     fclose(ficresvij);
                   9425:     fclose(ficrest);
1.208     brouard  9426:     printf("done Health expectancies\n");fflush(stdout);
                   9427:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  9428:     fclose(ficpar);
                   9429:   
                   9430:     /*------- Variance of period (stable) prevalence------*/   
                   9431: 
1.201     brouard  9432:     strcpy(fileresvpl,"VPL_");
                   9433:     strcat(fileresvpl,fileresu);
1.126     brouard  9434:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   9435:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   9436:       exit(0);
                   9437:     }
1.208     brouard  9438:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9439:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  9440: 
1.145     brouard  9441:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9442:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9443:           
                   9444:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   9445:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  9446:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  9447:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  9448:        fprintf(ficresvpl,"******\n");
                   9449:       
                   9450:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9451:        oldm=oldms;savm=savms;
1.209     brouard  9452:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  9453:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  9454:       /*}*/
1.126     brouard  9455:     }
                   9456: 
                   9457:     fclose(ficresvpl);
1.208     brouard  9458:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   9459:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  9460: 
                   9461:     /*---------- End : free ----------------*/
                   9462:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   9463:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   9464:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  9465:  /* endfree:*/
1.141     brouard  9466:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  9467:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   9468:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9469:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9470:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9471:     free_matrix(covar,0,NCOVMAX,1,n);
                   9472:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  9473:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  9474:     /*free_vector(delti,1,npar);*/
                   9475:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9476:     free_matrix(agev,1,maxwav,1,imx);
                   9477:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   9478: 
1.145     brouard  9479:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  9480:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  9481:     free_ivector(Tvar,1,NCOVMAX);
                   9482:     free_ivector(Tprod,1,NCOVMAX);
                   9483:     free_ivector(Tvaraff,1,NCOVMAX);
                   9484:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  9485: 
                   9486:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  9487:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  9488:   fflush(fichtm);
                   9489:   fflush(ficgp);
                   9490:   
                   9491: 
                   9492:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  9493:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   9494:     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  9495:   }else{
                   9496:     printf("End of Imach\n");
                   9497:     fprintf(ficlog,"End of Imach\n");
                   9498:   }
                   9499:   printf("See log file on %s\n",filelog);
                   9500:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  9501:   /*(void) gettimeofday(&end_time,&tzp);*/
                   9502:   rend_time = time(NULL);  
                   9503:   end_time = *localtime(&rend_time);
                   9504:   /* tml = *localtime(&end_time.tm_sec); */
                   9505:   strcpy(strtend,asctime(&end_time));
1.126     brouard  9506:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   9507:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  9508:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  9509: 
1.157     brouard  9510:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   9511:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   9512:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  9513:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   9514: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   9515:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9516:   fclose(fichtm);
                   9517:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9518:   fclose(fichtmcov);
                   9519:   fclose(ficgp);
                   9520:   fclose(ficlog);
                   9521:   /*------ End -----------*/
                   9522: 
                   9523: 
                   9524:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  9525: #ifdef WIN32
                   9526:    if (_chdir(pathcd) != 0)
                   9527:           printf("Can't move to directory %s!\n",path);
                   9528:    if(_getcwd(pathcd,MAXLINE) > 0)
                   9529: #else
1.126     brouard  9530:    if(chdir(pathcd) != 0)
1.184     brouard  9531:           printf("Can't move to directory %s!\n", path);
                   9532:    if (getcwd(pathcd, MAXLINE) > 0)
                   9533: #endif 
1.126     brouard  9534:     printf("Current directory %s!\n",pathcd);
                   9535:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   9536:   sprintf(plotcmd,"gnuplot");
1.157     brouard  9537: #ifdef _WIN32
1.126     brouard  9538:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   9539: #endif
                   9540:   if(!stat(plotcmd,&info)){
1.158     brouard  9541:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9542:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  9543:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  9544:     }else
                   9545:       strcpy(pplotcmd,plotcmd);
1.157     brouard  9546: #ifdef __unix
1.126     brouard  9547:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   9548:     if(!stat(plotcmd,&info)){
1.158     brouard  9549:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9550:     }else
                   9551:       strcpy(pplotcmd,plotcmd);
                   9552: #endif
                   9553:   }else
                   9554:     strcpy(pplotcmd,plotcmd);
                   9555:   
                   9556:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  9557:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9558: 
                   9559:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  9560:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  9561:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  9562:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  9563:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  9564:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  9565:   }
1.158     brouard  9566:   printf(" Successful, please wait...");
1.126     brouard  9567:   while (z[0] != 'q') {
                   9568:     /* chdir(path); */
1.154     brouard  9569:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  9570:     scanf("%s",z);
                   9571: /*     if (z[0] == 'c') system("./imach"); */
                   9572:     if (z[0] == 'e') {
1.158     brouard  9573: #ifdef __APPLE__
1.152     brouard  9574:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  9575: #elif __linux
                   9576:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  9577: #else
1.152     brouard  9578:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  9579: #endif
                   9580:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   9581:       system(pplotcmd);
1.126     brouard  9582:     }
                   9583:     else if (z[0] == 'g') system(plotcmd);
                   9584:     else if (z[0] == 'q') exit(0);
                   9585:   }
                   9586:   end:
                   9587:   while (z[0] != 'q') {
1.195     brouard  9588:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  9589:     scanf("%s",z);
                   9590:   }
                   9591: }

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