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

1.236   ! brouard     1: /* $Id: imach.c,v 1.235 2016/08/25 06:59:23 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.236   ! brouard     4:   Revision 1.235  2016/08/25 06:59:23  brouard
        !             5:   *** empty log message ***
        !             6: 
1.235     brouard     7:   Revision 1.234  2016/08/23 16:51:20  brouard
                      8:   *** empty log message ***
                      9: 
1.234     brouard    10:   Revision 1.233  2016/08/23 07:40:50  brouard
                     11:   Summary: not working
                     12: 
1.233     brouard    13:   Revision 1.232  2016/08/22 14:20:21  brouard
                     14:   Summary: not working
                     15: 
1.232     brouard    16:   Revision 1.231  2016/08/22 07:17:15  brouard
                     17:   Summary: not working
                     18: 
1.231     brouard    19:   Revision 1.230  2016/08/22 06:55:53  brouard
                     20:   Summary: Not working
                     21: 
1.230     brouard    22:   Revision 1.229  2016/07/23 09:45:53  brouard
                     23:   Summary: Completing for func too
                     24: 
1.229     brouard    25:   Revision 1.228  2016/07/22 17:45:30  brouard
                     26:   Summary: Fixing some arrays, still debugging
                     27: 
1.227     brouard    28:   Revision 1.226  2016/07/12 18:42:34  brouard
                     29:   Summary: temp
                     30: 
1.226     brouard    31:   Revision 1.225  2016/07/12 08:40:03  brouard
                     32:   Summary: saving but not running
                     33: 
1.225     brouard    34:   Revision 1.224  2016/07/01 13:16:01  brouard
                     35:   Summary: Fixes
                     36: 
1.224     brouard    37:   Revision 1.223  2016/02/19 09:23:35  brouard
                     38:   Summary: temporary
                     39: 
1.223     brouard    40:   Revision 1.222  2016/02/17 08:14:50  brouard
                     41:   Summary: Probably last 0.98 stable version 0.98r6
                     42: 
1.222     brouard    43:   Revision 1.221  2016/02/15 23:35:36  brouard
                     44:   Summary: minor bug
                     45: 
1.220     brouard    46:   Revision 1.219  2016/02/15 00:48:12  brouard
                     47:   *** empty log message ***
                     48: 
1.219     brouard    49:   Revision 1.218  2016/02/12 11:29:23  brouard
                     50:   Summary: 0.99 Back projections
                     51: 
1.218     brouard    52:   Revision 1.217  2015/12/23 17:18:31  brouard
                     53:   Summary: Experimental backcast
                     54: 
1.217     brouard    55:   Revision 1.216  2015/12/18 17:32:11  brouard
                     56:   Summary: 0.98r4 Warning and status=-2
                     57: 
                     58:   Version 0.98r4 is now:
                     59:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     60:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     61:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     62: 
1.216     brouard    63:   Revision 1.215  2015/12/16 08:52:24  brouard
                     64:   Summary: 0.98r4 working
                     65: 
1.215     brouard    66:   Revision 1.214  2015/12/16 06:57:54  brouard
                     67:   Summary: temporary not working
                     68: 
1.214     brouard    69:   Revision 1.213  2015/12/11 18:22:17  brouard
                     70:   Summary: 0.98r4
                     71: 
1.213     brouard    72:   Revision 1.212  2015/11/21 12:47:24  brouard
                     73:   Summary: minor typo
                     74: 
1.212     brouard    75:   Revision 1.211  2015/11/21 12:41:11  brouard
                     76:   Summary: 0.98r3 with some graph of projected cross-sectional
                     77: 
                     78:   Author: Nicolas Brouard
                     79: 
1.211     brouard    80:   Revision 1.210  2015/11/18 17:41:20  brouard
                     81:   Summary: Start working on projected prevalences
                     82: 
1.210     brouard    83:   Revision 1.209  2015/11/17 22:12:03  brouard
                     84:   Summary: Adding ftolpl parameter
                     85:   Author: N Brouard
                     86: 
                     87:   We had difficulties to get smoothed confidence intervals. It was due
                     88:   to the period prevalence which wasn't computed accurately. The inner
                     89:   parameter ftolpl is now an outer parameter of the .imach parameter
                     90:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     91:   computation are long.
                     92: 
1.209     brouard    93:   Revision 1.208  2015/11/17 14:31:57  brouard
                     94:   Summary: temporary
                     95: 
1.208     brouard    96:   Revision 1.207  2015/10/27 17:36:57  brouard
                     97:   *** empty log message ***
                     98: 
1.207     brouard    99:   Revision 1.206  2015/10/24 07:14:11  brouard
                    100:   *** empty log message ***
                    101: 
1.206     brouard   102:   Revision 1.205  2015/10/23 15:50:53  brouard
                    103:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    104: 
1.205     brouard   105:   Revision 1.204  2015/10/01 16:20:26  brouard
                    106:   Summary: Some new graphs of contribution to likelihood
                    107: 
1.204     brouard   108:   Revision 1.203  2015/09/30 17:45:14  brouard
                    109:   Summary: looking at better estimation of the hessian
                    110: 
                    111:   Also a better criteria for convergence to the period prevalence And
                    112:   therefore adding the number of years needed to converge. (The
                    113:   prevalence in any alive state shold sum to one
                    114: 
1.203     brouard   115:   Revision 1.202  2015/09/22 19:45:16  brouard
                    116:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    117: 
1.202     brouard   118:   Revision 1.201  2015/09/15 17:34:58  brouard
                    119:   Summary: 0.98r0
                    120: 
                    121:   - Some new graphs like suvival functions
                    122:   - Some bugs fixed like model=1+age+V2.
                    123: 
1.201     brouard   124:   Revision 1.200  2015/09/09 16:53:55  brouard
                    125:   Summary: Big bug thanks to Flavia
                    126: 
                    127:   Even model=1+age+V2. did not work anymore
                    128: 
1.200     brouard   129:   Revision 1.199  2015/09/07 14:09:23  brouard
                    130:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    131: 
1.199     brouard   132:   Revision 1.198  2015/09/03 07:14:39  brouard
                    133:   Summary: 0.98q5 Flavia
                    134: 
1.198     brouard   135:   Revision 1.197  2015/09/01 18:24:39  brouard
                    136:   *** empty log message ***
                    137: 
1.197     brouard   138:   Revision 1.196  2015/08/18 23:17:52  brouard
                    139:   Summary: 0.98q5
                    140: 
1.196     brouard   141:   Revision 1.195  2015/08/18 16:28:39  brouard
                    142:   Summary: Adding a hack for testing purpose
                    143: 
                    144:   After reading the title, ftol and model lines, if the comment line has
                    145:   a q, starting with #q, the answer at the end of the run is quit. It
                    146:   permits to run test files in batch with ctest. The former workaround was
                    147:   $ echo q | imach foo.imach
                    148: 
1.195     brouard   149:   Revision 1.194  2015/08/18 13:32:00  brouard
                    150:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    151: 
1.194     brouard   152:   Revision 1.193  2015/08/04 07:17:42  brouard
                    153:   Summary: 0.98q4
                    154: 
1.193     brouard   155:   Revision 1.192  2015/07/16 16:49:02  brouard
                    156:   Summary: Fixing some outputs
                    157: 
1.192     brouard   158:   Revision 1.191  2015/07/14 10:00:33  brouard
                    159:   Summary: Some fixes
                    160: 
1.191     brouard   161:   Revision 1.190  2015/05/05 08:51:13  brouard
                    162:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    163: 
                    164:   Fix 1+age+.
                    165: 
1.190     brouard   166:   Revision 1.189  2015/04/30 14:45:16  brouard
                    167:   Summary: 0.98q2
                    168: 
1.189     brouard   169:   Revision 1.188  2015/04/30 08:27:53  brouard
                    170:   *** empty log message ***
                    171: 
1.188     brouard   172:   Revision 1.187  2015/04/29 09:11:15  brouard
                    173:   *** empty log message ***
                    174: 
1.187     brouard   175:   Revision 1.186  2015/04/23 12:01:52  brouard
                    176:   Summary: V1*age is working now, version 0.98q1
                    177: 
                    178:   Some codes had been disabled in order to simplify and Vn*age was
                    179:   working in the optimization phase, ie, giving correct MLE parameters,
                    180:   but, as usual, outputs were not correct and program core dumped.
                    181: 
1.186     brouard   182:   Revision 1.185  2015/03/11 13:26:42  brouard
                    183:   Summary: Inclusion of compile and links command line for Intel Compiler
                    184: 
1.185     brouard   185:   Revision 1.184  2015/03/11 11:52:39  brouard
                    186:   Summary: Back from Windows 8. Intel Compiler
                    187: 
1.184     brouard   188:   Revision 1.183  2015/03/10 20:34:32  brouard
                    189:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    190: 
                    191:   We use directest instead of original Powell test; probably no
                    192:   incidence on the results, but better justifications;
                    193:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    194:   wrong results.
                    195: 
1.183     brouard   196:   Revision 1.182  2015/02/12 08:19:57  brouard
                    197:   Summary: Trying to keep directest which seems simpler and more general
                    198:   Author: Nicolas Brouard
                    199: 
1.182     brouard   200:   Revision 1.181  2015/02/11 23:22:24  brouard
                    201:   Summary: Comments on Powell added
                    202: 
                    203:   Author:
                    204: 
1.181     brouard   205:   Revision 1.180  2015/02/11 17:33:45  brouard
                    206:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    207: 
1.180     brouard   208:   Revision 1.179  2015/01/04 09:57:06  brouard
                    209:   Summary: back to OS/X
                    210: 
1.179     brouard   211:   Revision 1.178  2015/01/04 09:35:48  brouard
                    212:   *** empty log message ***
                    213: 
1.178     brouard   214:   Revision 1.177  2015/01/03 18:40:56  brouard
                    215:   Summary: Still testing ilc32 on OSX
                    216: 
1.177     brouard   217:   Revision 1.176  2015/01/03 16:45:04  brouard
                    218:   *** empty log message ***
                    219: 
1.176     brouard   220:   Revision 1.175  2015/01/03 16:33:42  brouard
                    221:   *** empty log message ***
                    222: 
1.175     brouard   223:   Revision 1.174  2015/01/03 16:15:49  brouard
                    224:   Summary: Still in cross-compilation
                    225: 
1.174     brouard   226:   Revision 1.173  2015/01/03 12:06:26  brouard
                    227:   Summary: trying to detect cross-compilation
                    228: 
1.173     brouard   229:   Revision 1.172  2014/12/27 12:07:47  brouard
                    230:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    231: 
1.172     brouard   232:   Revision 1.171  2014/12/23 13:26:59  brouard
                    233:   Summary: Back from Visual C
                    234: 
                    235:   Still problem with utsname.h on Windows
                    236: 
1.171     brouard   237:   Revision 1.170  2014/12/23 11:17:12  brouard
                    238:   Summary: Cleaning some \%% back to %%
                    239: 
                    240:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    241: 
1.170     brouard   242:   Revision 1.169  2014/12/22 23:08:31  brouard
                    243:   Summary: 0.98p
                    244: 
                    245:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    246: 
1.169     brouard   247:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   248:   Summary: update
1.169     brouard   249: 
1.168     brouard   250:   Revision 1.167  2014/12/22 13:50:56  brouard
                    251:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    252: 
                    253:   Testing on Linux 64
                    254: 
1.167     brouard   255:   Revision 1.166  2014/12/22 11:40:47  brouard
                    256:   *** empty log message ***
                    257: 
1.166     brouard   258:   Revision 1.165  2014/12/16 11:20:36  brouard
                    259:   Summary: After compiling on Visual C
                    260: 
                    261:   * imach.c (Module): Merging 1.61 to 1.162
                    262: 
1.165     brouard   263:   Revision 1.164  2014/12/16 10:52:11  brouard
                    264:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    265: 
                    266:   * imach.c (Module): Merging 1.61 to 1.162
                    267: 
1.164     brouard   268:   Revision 1.163  2014/12/16 10:30:11  brouard
                    269:   * imach.c (Module): Merging 1.61 to 1.162
                    270: 
1.163     brouard   271:   Revision 1.162  2014/09/25 11:43:39  brouard
                    272:   Summary: temporary backup 0.99!
                    273: 
1.162     brouard   274:   Revision 1.1  2014/09/16 11:06:58  brouard
                    275:   Summary: With some code (wrong) for nlopt
                    276: 
                    277:   Author:
                    278: 
                    279:   Revision 1.161  2014/09/15 20:41:41  brouard
                    280:   Summary: Problem with macro SQR on Intel compiler
                    281: 
1.161     brouard   282:   Revision 1.160  2014/09/02 09:24:05  brouard
                    283:   *** empty log message ***
                    284: 
1.160     brouard   285:   Revision 1.159  2014/09/01 10:34:10  brouard
                    286:   Summary: WIN32
                    287:   Author: Brouard
                    288: 
1.159     brouard   289:   Revision 1.158  2014/08/27 17:11:51  brouard
                    290:   *** empty log message ***
                    291: 
1.158     brouard   292:   Revision 1.157  2014/08/27 16:26:55  brouard
                    293:   Summary: Preparing windows Visual studio version
                    294:   Author: Brouard
                    295: 
                    296:   In order to compile on Visual studio, time.h is now correct and time_t
                    297:   and tm struct should be used. difftime should be used but sometimes I
                    298:   just make the differences in raw time format (time(&now).
                    299:   Trying to suppress #ifdef LINUX
                    300:   Add xdg-open for __linux in order to open default browser.
                    301: 
1.157     brouard   302:   Revision 1.156  2014/08/25 20:10:10  brouard
                    303:   *** empty log message ***
                    304: 
1.156     brouard   305:   Revision 1.155  2014/08/25 18:32:34  brouard
                    306:   Summary: New compile, minor changes
                    307:   Author: Brouard
                    308: 
1.155     brouard   309:   Revision 1.154  2014/06/20 17:32:08  brouard
                    310:   Summary: Outputs now all graphs of convergence to period prevalence
                    311: 
1.154     brouard   312:   Revision 1.153  2014/06/20 16:45:46  brouard
                    313:   Summary: If 3 live state, convergence to period prevalence on same graph
                    314:   Author: Brouard
                    315: 
1.153     brouard   316:   Revision 1.152  2014/06/18 17:54:09  brouard
                    317:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    318: 
1.152     brouard   319:   Revision 1.151  2014/06/18 16:43:30  brouard
                    320:   *** empty log message ***
                    321: 
1.151     brouard   322:   Revision 1.150  2014/06/18 16:42:35  brouard
                    323:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    324:   Author: brouard
                    325: 
1.150     brouard   326:   Revision 1.149  2014/06/18 15:51:14  brouard
                    327:   Summary: Some fixes in parameter files errors
                    328:   Author: Nicolas Brouard
                    329: 
1.149     brouard   330:   Revision 1.148  2014/06/17 17:38:48  brouard
                    331:   Summary: Nothing new
                    332:   Author: Brouard
                    333: 
                    334:   Just a new packaging for OS/X version 0.98nS
                    335: 
1.148     brouard   336:   Revision 1.147  2014/06/16 10:33:11  brouard
                    337:   *** empty log message ***
                    338: 
1.147     brouard   339:   Revision 1.146  2014/06/16 10:20:28  brouard
                    340:   Summary: Merge
                    341:   Author: Brouard
                    342: 
                    343:   Merge, before building revised version.
                    344: 
1.146     brouard   345:   Revision 1.145  2014/06/10 21:23:15  brouard
                    346:   Summary: Debugging with valgrind
                    347:   Author: Nicolas Brouard
                    348: 
                    349:   Lot of changes in order to output the results with some covariates
                    350:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    351:   improve the code.
                    352:   No more memory valgrind error but a lot has to be done in order to
                    353:   continue the work of splitting the code into subroutines.
                    354:   Also, decodemodel has been improved. Tricode is still not
                    355:   optimal. nbcode should be improved. Documentation has been added in
                    356:   the source code.
                    357: 
1.144     brouard   358:   Revision 1.143  2014/01/26 09:45:38  brouard
                    359:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    360: 
                    361:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    362:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    363: 
1.143     brouard   364:   Revision 1.142  2014/01/26 03:57:36  brouard
                    365:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    366: 
                    367:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    368: 
1.142     brouard   369:   Revision 1.141  2014/01/26 02:42:01  brouard
                    370:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    371: 
1.141     brouard   372:   Revision 1.140  2011/09/02 10:37:54  brouard
                    373:   Summary: times.h is ok with mingw32 now.
                    374: 
1.140     brouard   375:   Revision 1.139  2010/06/14 07:50:17  brouard
                    376:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    377:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    378: 
1.139     brouard   379:   Revision 1.138  2010/04/30 18:19:40  brouard
                    380:   *** empty log message ***
                    381: 
1.138     brouard   382:   Revision 1.137  2010/04/29 18:11:38  brouard
                    383:   (Module): Checking covariates for more complex models
                    384:   than V1+V2. A lot of change to be done. Unstable.
                    385: 
1.137     brouard   386:   Revision 1.136  2010/04/26 20:30:53  brouard
                    387:   (Module): merging some libgsl code. Fixing computation
                    388:   of likelione (using inter/intrapolation if mle = 0) in order to
                    389:   get same likelihood as if mle=1.
                    390:   Some cleaning of code and comments added.
                    391: 
1.136     brouard   392:   Revision 1.135  2009/10/29 15:33:14  brouard
                    393:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    394: 
1.135     brouard   395:   Revision 1.134  2009/10/29 13:18:53  brouard
                    396:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    397: 
1.134     brouard   398:   Revision 1.133  2009/07/06 10:21:25  brouard
                    399:   just nforces
                    400: 
1.133     brouard   401:   Revision 1.132  2009/07/06 08:22:05  brouard
                    402:   Many tings
                    403: 
1.132     brouard   404:   Revision 1.131  2009/06/20 16:22:47  brouard
                    405:   Some dimensions resccaled
                    406: 
1.131     brouard   407:   Revision 1.130  2009/05/26 06:44:34  brouard
                    408:   (Module): Max Covariate is now set to 20 instead of 8. A
                    409:   lot of cleaning with variables initialized to 0. Trying to make
                    410:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    411: 
1.130     brouard   412:   Revision 1.129  2007/08/31 13:49:27  lievre
                    413:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    414: 
1.129     lievre    415:   Revision 1.128  2006/06/30 13:02:05  brouard
                    416:   (Module): Clarifications on computing e.j
                    417: 
1.128     brouard   418:   Revision 1.127  2006/04/28 18:11:50  brouard
                    419:   (Module): Yes the sum of survivors was wrong since
                    420:   imach-114 because nhstepm was no more computed in the age
                    421:   loop. Now we define nhstepma in the age loop.
                    422:   (Module): In order to speed up (in case of numerous covariates) we
                    423:   compute health expectancies (without variances) in a first step
                    424:   and then all the health expectancies with variances or standard
                    425:   deviation (needs data from the Hessian matrices) which slows the
                    426:   computation.
                    427:   In the future we should be able to stop the program is only health
                    428:   expectancies and graph are needed without standard deviations.
                    429: 
1.127     brouard   430:   Revision 1.126  2006/04/28 17:23:28  brouard
                    431:   (Module): Yes the sum of survivors was wrong since
                    432:   imach-114 because nhstepm was no more computed in the age
                    433:   loop. Now we define nhstepma in the age loop.
                    434:   Version 0.98h
                    435: 
1.126     brouard   436:   Revision 1.125  2006/04/04 15:20:31  lievre
                    437:   Errors in calculation of health expectancies. Age was not initialized.
                    438:   Forecasting file added.
                    439: 
                    440:   Revision 1.124  2006/03/22 17:13:53  lievre
                    441:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    442:   The log-likelihood is printed in the log file
                    443: 
                    444:   Revision 1.123  2006/03/20 10:52:43  brouard
                    445:   * imach.c (Module): <title> changed, corresponds to .htm file
                    446:   name. <head> headers where missing.
                    447: 
                    448:   * imach.c (Module): Weights can have a decimal point as for
                    449:   English (a comma might work with a correct LC_NUMERIC environment,
                    450:   otherwise the weight is truncated).
                    451:   Modification of warning when the covariates values are not 0 or
                    452:   1.
                    453:   Version 0.98g
                    454: 
                    455:   Revision 1.122  2006/03/20 09:45:41  brouard
                    456:   (Module): Weights can have a decimal point as for
                    457:   English (a comma might work with a correct LC_NUMERIC environment,
                    458:   otherwise the weight is truncated).
                    459:   Modification of warning when the covariates values are not 0 or
                    460:   1.
                    461:   Version 0.98g
                    462: 
                    463:   Revision 1.121  2006/03/16 17:45:01  lievre
                    464:   * imach.c (Module): Comments concerning covariates added
                    465: 
                    466:   * imach.c (Module): refinements in the computation of lli if
                    467:   status=-2 in order to have more reliable computation if stepm is
                    468:   not 1 month. Version 0.98f
                    469: 
                    470:   Revision 1.120  2006/03/16 15:10:38  lievre
                    471:   (Module): refinements in the computation of lli if
                    472:   status=-2 in order to have more reliable computation if stepm is
                    473:   not 1 month. Version 0.98f
                    474: 
                    475:   Revision 1.119  2006/03/15 17:42:26  brouard
                    476:   (Module): Bug if status = -2, the loglikelihood was
                    477:   computed as likelihood omitting the logarithm. Version O.98e
                    478: 
                    479:   Revision 1.118  2006/03/14 18:20:07  brouard
                    480:   (Module): varevsij Comments added explaining the second
                    481:   table of variances if popbased=1 .
                    482:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    483:   (Module): Function pstamp added
                    484:   (Module): Version 0.98d
                    485: 
                    486:   Revision 1.117  2006/03/14 17:16:22  brouard
                    487:   (Module): varevsij Comments added explaining the second
                    488:   table of variances if popbased=1 .
                    489:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    490:   (Module): Function pstamp added
                    491:   (Module): Version 0.98d
                    492: 
                    493:   Revision 1.116  2006/03/06 10:29:27  brouard
                    494:   (Module): Variance-covariance wrong links and
                    495:   varian-covariance of ej. is needed (Saito).
                    496: 
                    497:   Revision 1.115  2006/02/27 12:17:45  brouard
                    498:   (Module): One freematrix added in mlikeli! 0.98c
                    499: 
                    500:   Revision 1.114  2006/02/26 12:57:58  brouard
                    501:   (Module): Some improvements in processing parameter
                    502:   filename with strsep.
                    503: 
                    504:   Revision 1.113  2006/02/24 14:20:24  brouard
                    505:   (Module): Memory leaks checks with valgrind and:
                    506:   datafile was not closed, some imatrix were not freed and on matrix
                    507:   allocation too.
                    508: 
                    509:   Revision 1.112  2006/01/30 09:55:26  brouard
                    510:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    511: 
                    512:   Revision 1.111  2006/01/25 20:38:18  brouard
                    513:   (Module): Lots of cleaning and bugs added (Gompertz)
                    514:   (Module): Comments can be added in data file. Missing date values
                    515:   can be a simple dot '.'.
                    516: 
                    517:   Revision 1.110  2006/01/25 00:51:50  brouard
                    518:   (Module): Lots of cleaning and bugs added (Gompertz)
                    519: 
                    520:   Revision 1.109  2006/01/24 19:37:15  brouard
                    521:   (Module): Comments (lines starting with a #) are allowed in data.
                    522: 
                    523:   Revision 1.108  2006/01/19 18:05:42  lievre
                    524:   Gnuplot problem appeared...
                    525:   To be fixed
                    526: 
                    527:   Revision 1.107  2006/01/19 16:20:37  brouard
                    528:   Test existence of gnuplot in imach path
                    529: 
                    530:   Revision 1.106  2006/01/19 13:24:36  brouard
                    531:   Some cleaning and links added in html output
                    532: 
                    533:   Revision 1.105  2006/01/05 20:23:19  lievre
                    534:   *** empty log message ***
                    535: 
                    536:   Revision 1.104  2005/09/30 16:11:43  lievre
                    537:   (Module): sump fixed, loop imx fixed, and simplifications.
                    538:   (Module): If the status is missing at the last wave but we know
                    539:   that the person is alive, then we can code his/her status as -2
                    540:   (instead of missing=-1 in earlier versions) and his/her
                    541:   contributions to the likelihood is 1 - Prob of dying from last
                    542:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    543:   the healthy state at last known wave). Version is 0.98
                    544: 
                    545:   Revision 1.103  2005/09/30 15:54:49  lievre
                    546:   (Module): sump fixed, loop imx fixed, and simplifications.
                    547: 
                    548:   Revision 1.102  2004/09/15 17:31:30  brouard
                    549:   Add the possibility to read data file including tab characters.
                    550: 
                    551:   Revision 1.101  2004/09/15 10:38:38  brouard
                    552:   Fix on curr_time
                    553: 
                    554:   Revision 1.100  2004/07/12 18:29:06  brouard
                    555:   Add version for Mac OS X. Just define UNIX in Makefile
                    556: 
                    557:   Revision 1.99  2004/06/05 08:57:40  brouard
                    558:   *** empty log message ***
                    559: 
                    560:   Revision 1.98  2004/05/16 15:05:56  brouard
                    561:   New version 0.97 . First attempt to estimate force of mortality
                    562:   directly from the data i.e. without the need of knowing the health
                    563:   state at each age, but using a Gompertz model: log u =a + b*age .
                    564:   This is the basic analysis of mortality and should be done before any
                    565:   other analysis, in order to test if the mortality estimated from the
                    566:   cross-longitudinal survey is different from the mortality estimated
                    567:   from other sources like vital statistic data.
                    568: 
                    569:   The same imach parameter file can be used but the option for mle should be -3.
                    570: 
1.133     brouard   571:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   572:   former routines in order to include the new code within the former code.
                    573: 
                    574:   The output is very simple: only an estimate of the intercept and of
                    575:   the slope with 95% confident intervals.
                    576: 
                    577:   Current limitations:
                    578:   A) Even if you enter covariates, i.e. with the
                    579:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    580:   B) There is no computation of Life Expectancy nor Life Table.
                    581: 
                    582:   Revision 1.97  2004/02/20 13:25:42  lievre
                    583:   Version 0.96d. Population forecasting command line is (temporarily)
                    584:   suppressed.
                    585: 
                    586:   Revision 1.96  2003/07/15 15:38:55  brouard
                    587:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    588:   rewritten within the same printf. Workaround: many printfs.
                    589: 
                    590:   Revision 1.95  2003/07/08 07:54:34  brouard
                    591:   * imach.c (Repository):
                    592:   (Repository): Using imachwizard code to output a more meaningful covariance
                    593:   matrix (cov(a12,c31) instead of numbers.
                    594: 
                    595:   Revision 1.94  2003/06/27 13:00:02  brouard
                    596:   Just cleaning
                    597: 
                    598:   Revision 1.93  2003/06/25 16:33:55  brouard
                    599:   (Module): On windows (cygwin) function asctime_r doesn't
                    600:   exist so I changed back to asctime which exists.
                    601:   (Module): Version 0.96b
                    602: 
                    603:   Revision 1.92  2003/06/25 16:30:45  brouard
                    604:   (Module): On windows (cygwin) function asctime_r doesn't
                    605:   exist so I changed back to asctime which exists.
                    606: 
                    607:   Revision 1.91  2003/06/25 15:30:29  brouard
                    608:   * imach.c (Repository): Duplicated warning errors corrected.
                    609:   (Repository): Elapsed time after each iteration is now output. It
                    610:   helps to forecast when convergence will be reached. Elapsed time
                    611:   is stamped in powell.  We created a new html file for the graphs
                    612:   concerning matrix of covariance. It has extension -cov.htm.
                    613: 
                    614:   Revision 1.90  2003/06/24 12:34:15  brouard
                    615:   (Module): Some bugs corrected for windows. Also, when
                    616:   mle=-1 a template is output in file "or"mypar.txt with the design
                    617:   of the covariance matrix to be input.
                    618: 
                    619:   Revision 1.89  2003/06/24 12:30:52  brouard
                    620:   (Module): Some bugs corrected for windows. Also, when
                    621:   mle=-1 a template is output in file "or"mypar.txt with the design
                    622:   of the covariance matrix to be input.
                    623: 
                    624:   Revision 1.88  2003/06/23 17:54:56  brouard
                    625:   * 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.
                    626: 
                    627:   Revision 1.87  2003/06/18 12:26:01  brouard
                    628:   Version 0.96
                    629: 
                    630:   Revision 1.86  2003/06/17 20:04:08  brouard
                    631:   (Module): Change position of html and gnuplot routines and added
                    632:   routine fileappend.
                    633: 
                    634:   Revision 1.85  2003/06/17 13:12:43  brouard
                    635:   * imach.c (Repository): Check when date of death was earlier that
                    636:   current date of interview. It may happen when the death was just
                    637:   prior to the death. In this case, dh was negative and likelihood
                    638:   was wrong (infinity). We still send an "Error" but patch by
                    639:   assuming that the date of death was just one stepm after the
                    640:   interview.
                    641:   (Repository): Because some people have very long ID (first column)
                    642:   we changed int to long in num[] and we added a new lvector for
                    643:   memory allocation. But we also truncated to 8 characters (left
                    644:   truncation)
                    645:   (Repository): No more line truncation errors.
                    646: 
                    647:   Revision 1.84  2003/06/13 21:44:43  brouard
                    648:   * imach.c (Repository): Replace "freqsummary" at a correct
                    649:   place. It differs from routine "prevalence" which may be called
                    650:   many times. Probs is memory consuming and must be used with
                    651:   parcimony.
                    652:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    653: 
                    654:   Revision 1.83  2003/06/10 13:39:11  lievre
                    655:   *** empty log message ***
                    656: 
                    657:   Revision 1.82  2003/06/05 15:57:20  brouard
                    658:   Add log in  imach.c and  fullversion number is now printed.
                    659: 
                    660: */
                    661: /*
                    662:    Interpolated Markov Chain
                    663: 
                    664:   Short summary of the programme:
                    665:   
1.227     brouard   666:   This program computes Healthy Life Expectancies or State-specific
                    667:   (if states aren't health statuses) Expectancies from
                    668:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    669: 
                    670:   -1- a first survey ("cross") where individuals from different ages
                    671:   are interviewed on their health status or degree of disability (in
                    672:   the case of a health survey which is our main interest)
                    673: 
                    674:   -2- at least a second wave of interviews ("longitudinal") which
                    675:   measure each change (if any) in individual health status.  Health
                    676:   expectancies are computed from the time spent in each health state
                    677:   according to a model. More health states you consider, more time is
                    678:   necessary to reach the Maximum Likelihood of the parameters involved
                    679:   in the model.  The simplest model is the multinomial logistic model
                    680:   where pij is the probability to be observed in state j at the second
                    681:   wave conditional to be observed in state i at the first
                    682:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    683:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    684:   have a more complex model than "constant and age", you should modify
                    685:   the program where the markup *Covariates have to be included here
                    686:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   687:   convergence.
                    688: 
                    689:   The advantage of this computer programme, compared to a simple
                    690:   multinomial logistic model, is clear when the delay between waves is not
                    691:   identical for each individual. Also, if a individual missed an
                    692:   intermediate interview, the information is lost, but taken into
                    693:   account using an interpolation or extrapolation.  
                    694: 
                    695:   hPijx is the probability to be observed in state i at age x+h
                    696:   conditional to the observed state i at age x. The delay 'h' can be
                    697:   split into an exact number (nh*stepm) of unobserved intermediate
                    698:   states. This elementary transition (by month, quarter,
                    699:   semester or year) is modelled as a multinomial logistic.  The hPx
                    700:   matrix is simply the matrix product of nh*stepm elementary matrices
                    701:   and the contribution of each individual to the likelihood is simply
                    702:   hPijx.
                    703: 
                    704:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   705:   of the life expectancies. It also computes the period (stable) prevalence.
                    706: 
                    707: Back prevalence and projections:
1.227     brouard   708: 
                    709:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    710:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    711:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    712:    mobilavproj)
                    713: 
                    714:     Computes the back prevalence limit for any combination of
                    715:     covariate values k at any age between ageminpar and agemaxpar and
                    716:     returns it in **bprlim. In the loops,
                    717: 
                    718:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    719:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    720: 
                    721:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   722:    Computes for any combination of covariates k and any age between bage and fage 
                    723:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    724:                        oldm=oldms;savm=savms;
1.227     brouard   725: 
                    726:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   727:      Computes the transition matrix starting at age 'age' over
                    728:      'nhstepm*hstepm*stepm' months (i.e. until
                    729:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   730:      nhstepm*hstepm matrices. 
                    731: 
                    732:      Returns p3mat[i][j][h] after calling
                    733:      p3mat[i][j][h]=matprod2(newm,
                    734:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    735:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    736:      oldm);
1.226     brouard   737: 
                    738: Important routines
                    739: 
                    740: - func (or funcone), computes logit (pij) distinguishing
                    741:   o fixed variables (single or product dummies or quantitative);
                    742:   o varying variables by:
                    743:    (1) wave (single, product dummies, quantitative), 
                    744:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    745:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    746:        % varying dummy (not done) or quantitative (not done);
                    747: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    748:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    749: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    750:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    751:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   752: 
1.226     brouard   753: 
                    754:   
1.133     brouard   755:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    756:            Institut national d'études démographiques, Paris.
1.126     brouard   757:   This software have been partly granted by Euro-REVES, a concerted action
                    758:   from the European Union.
                    759:   It is copyrighted identically to a GNU software product, ie programme and
                    760:   software can be distributed freely for non commercial use. Latest version
                    761:   can be accessed at http://euroreves.ined.fr/imach .
                    762: 
                    763:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    764:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    765:   
                    766:   **********************************************************************/
                    767: /*
                    768:   main
                    769:   read parameterfile
                    770:   read datafile
                    771:   concatwav
                    772:   freqsummary
                    773:   if (mle >= 1)
                    774:     mlikeli
                    775:   print results files
                    776:   if mle==1 
                    777:      computes hessian
                    778:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    779:       begin-prev-date,...
                    780:   open gnuplot file
                    781:   open html file
1.145     brouard   782:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    783:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    784:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    785:     freexexit2 possible for memory heap.
                    786: 
                    787:   h Pij x                         | pij_nom  ficrestpij
                    788:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    789:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    790:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    791: 
                    792:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    793:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    794:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    795:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    796:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    797: 
1.126     brouard   798:   forecasting if prevfcast==1 prevforecast call prevalence()
                    799:   health expectancies
                    800:   Variance-covariance of DFLE
                    801:   prevalence()
                    802:    movingaverage()
                    803:   varevsij() 
                    804:   if popbased==1 varevsij(,popbased)
                    805:   total life expectancies
                    806:   Variance of period (stable) prevalence
                    807:  end
                    808: */
                    809: 
1.187     brouard   810: /* #define DEBUG */
                    811: /* #define DEBUGBRENT */
1.203     brouard   812: /* #define DEBUGLINMIN */
                    813: /* #define DEBUGHESS */
                    814: #define DEBUGHESSIJ
1.224     brouard   815: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   816: #define POWELL /* Instead of NLOPT */
1.224     brouard   817: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   818: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    819: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   820: 
                    821: #include <math.h>
                    822: #include <stdio.h>
                    823: #include <stdlib.h>
                    824: #include <string.h>
1.226     brouard   825: #include <ctype.h>
1.159     brouard   826: 
                    827: #ifdef _WIN32
                    828: #include <io.h>
1.172     brouard   829: #include <windows.h>
                    830: #include <tchar.h>
1.159     brouard   831: #else
1.126     brouard   832: #include <unistd.h>
1.159     brouard   833: #endif
1.126     brouard   834: 
                    835: #include <limits.h>
                    836: #include <sys/types.h>
1.171     brouard   837: 
                    838: #if defined(__GNUC__)
                    839: #include <sys/utsname.h> /* Doesn't work on Windows */
                    840: #endif
                    841: 
1.126     brouard   842: #include <sys/stat.h>
                    843: #include <errno.h>
1.159     brouard   844: /* extern int errno; */
1.126     brouard   845: 
1.157     brouard   846: /* #ifdef LINUX */
                    847: /* #include <time.h> */
                    848: /* #include "timeval.h" */
                    849: /* #else */
                    850: /* #include <sys/time.h> */
                    851: /* #endif */
                    852: 
1.126     brouard   853: #include <time.h>
                    854: 
1.136     brouard   855: #ifdef GSL
                    856: #include <gsl/gsl_errno.h>
                    857: #include <gsl/gsl_multimin.h>
                    858: #endif
                    859: 
1.167     brouard   860: 
1.162     brouard   861: #ifdef NLOPT
                    862: #include <nlopt.h>
                    863: typedef struct {
                    864:   double (* function)(double [] );
                    865: } myfunc_data ;
                    866: #endif
                    867: 
1.126     brouard   868: /* #include <libintl.h> */
                    869: /* #define _(String) gettext (String) */
                    870: 
1.141     brouard   871: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   872: 
                    873: #define GNUPLOTPROGRAM "gnuplot"
                    874: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    875: #define FILENAMELENGTH 132
                    876: 
                    877: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    878: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    879: 
1.144     brouard   880: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    881: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   882: 
                    883: #define NINTERVMAX 8
1.144     brouard   884: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    885: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    886: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   887: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   888: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    889: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   890: #define MAXN 20000
1.144     brouard   891: #define YEARM 12. /**< Number of months per year */
1.218     brouard   892: /* #define AGESUP 130 */
                    893: #define AGESUP 150
                    894: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   895: #define AGEBASE 40
1.194     brouard   896: #define AGEOVERFLOW 1.e20
1.164     brouard   897: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   898: #ifdef _WIN32
                    899: #define DIRSEPARATOR '\\'
                    900: #define CHARSEPARATOR "\\"
                    901: #define ODIRSEPARATOR '/'
                    902: #else
1.126     brouard   903: #define DIRSEPARATOR '/'
                    904: #define CHARSEPARATOR "/"
                    905: #define ODIRSEPARATOR '\\'
                    906: #endif
                    907: 
1.236   ! brouard   908: /* $Id: imach.c,v 1.235 2016/08/25 06:59:23 brouard Exp $ */
1.126     brouard   909: /* $State: Exp $ */
1.196     brouard   910: #include "version.h"
                    911: char version[]=__IMACH_VERSION__;
1.224     brouard   912: char copyright[]="February 2016,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
1.236   ! brouard   913: char fullversion[]="$Revision: 1.235 $ $Date: 2016/08/25 06:59:23 $"; 
1.126     brouard   914: char strstart[80];
                    915: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   916: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   917: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   918: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    919: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    920: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   921: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    922: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   923: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    924: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    925: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   926: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    927: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   928: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   929: int nsd=0; /**< Total number of single dummy variables (output) */
                    930: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   931: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   932: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   933: int ntveff=0; /**< ntveff number of effective time varying variables */
                    934: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   935: int cptcov=0; /* Working variable */
1.218     brouard   936: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   937: int npar=NPARMAX;
                    938: int nlstate=2; /* Number of live states */
                    939: int ndeath=1; /* Number of dead states */
1.130     brouard   940: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   941: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   942: int popbased=0;
                    943: 
                    944: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   945: int maxwav=0; /* Maxim number of waves */
                    946: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    947: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    948: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   949:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   950: int mle=1, weightopt=0;
1.126     brouard   951: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    952: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    953: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    954:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   955: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   956: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    957: 
1.130     brouard   958: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   959: double **matprod2(); /* test */
1.126     brouard   960: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    961: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   962: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    963: 
1.136     brouard   964: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   965: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   966: FILE *ficlog, *ficrespow;
1.130     brouard   967: int globpr=0; /* Global variable for printing or not */
1.126     brouard   968: double fretone; /* Only one call to likelihood */
1.130     brouard   969: long ipmx=0; /* Number of contributions */
1.126     brouard   970: double sw; /* Sum of weights */
                    971: char filerespow[FILENAMELENGTH];
                    972: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    973: FILE *ficresilk;
                    974: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    975: FILE *ficresprobmorprev;
                    976: FILE *fichtm, *fichtmcov; /* Html File */
                    977: FILE *ficreseij;
                    978: char filerese[FILENAMELENGTH];
                    979: FILE *ficresstdeij;
                    980: char fileresstde[FILENAMELENGTH];
                    981: FILE *ficrescveij;
                    982: char filerescve[FILENAMELENGTH];
                    983: FILE  *ficresvij;
                    984: char fileresv[FILENAMELENGTH];
                    985: FILE  *ficresvpl;
                    986: char fileresvpl[FILENAMELENGTH];
                    987: char title[MAXLINE];
1.234     brouard   988: char model[MAXLINE]; /**< The model line */
1.217     brouard   989: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   990: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    991: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    992: char command[FILENAMELENGTH];
                    993: int  outcmd=0;
                    994: 
1.217     brouard   995: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   996: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   997: char filelog[FILENAMELENGTH]; /* Log file */
                    998: char filerest[FILENAMELENGTH];
                    999: char fileregp[FILENAMELENGTH];
                   1000: char popfile[FILENAMELENGTH];
                   1001: 
                   1002: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1003: 
1.157     brouard  1004: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1005: /* struct timezone tzp; */
                   1006: /* extern int gettimeofday(); */
                   1007: struct tm tml, *gmtime(), *localtime();
                   1008: 
                   1009: extern time_t time();
                   1010: 
                   1011: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1012: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1013: struct tm tm;
                   1014: 
1.126     brouard  1015: char strcurr[80], strfor[80];
                   1016: 
                   1017: char *endptr;
                   1018: long lval;
                   1019: double dval;
                   1020: 
                   1021: #define NR_END 1
                   1022: #define FREE_ARG char*
                   1023: #define FTOL 1.0e-10
                   1024: 
                   1025: #define NRANSI 
                   1026: #define ITMAX 200 
                   1027: 
                   1028: #define TOL 2.0e-4 
                   1029: 
                   1030: #define CGOLD 0.3819660 
                   1031: #define ZEPS 1.0e-10 
                   1032: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1033: 
                   1034: #define GOLD 1.618034 
                   1035: #define GLIMIT 100.0 
                   1036: #define TINY 1.0e-20 
                   1037: 
                   1038: static double maxarg1,maxarg2;
                   1039: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1040: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1041:   
                   1042: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1043: #define rint(a) floor(a+0.5)
1.166     brouard  1044: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1045: #define mytinydouble 1.0e-16
1.166     brouard  1046: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1047: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1048: /* static double dsqrarg; */
                   1049: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1050: static double sqrarg;
                   1051: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1052: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1053: int agegomp= AGEGOMP;
                   1054: 
                   1055: int imx; 
                   1056: int stepm=1;
                   1057: /* Stepm, step in month: minimum step interpolation*/
                   1058: 
                   1059: int estepm;
                   1060: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1061: 
                   1062: int m,nb;
                   1063: long *num;
1.197     brouard  1064: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1065: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1066:                   covariate for which somebody answered excluding 
                   1067:                   undefined. Usually 2: 0 and 1. */
                   1068: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1069:                             covariate for which somebody answered including 
                   1070:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1071: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1072: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1073: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1074: double *ageexmed,*agecens;
                   1075: double dateintmean=0;
                   1076: 
                   1077: double *weight;
                   1078: int **s; /* Status */
1.141     brouard  1079: double *agedc;
1.145     brouard  1080: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1081:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1082:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1083: double **coqvar; /* Fixed quantitative covariate iqv */
                   1084: double ***cotvar; /* Time varying covariate itv */
                   1085: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1086: double  idx; 
                   1087: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1088: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1089: /*k          1  2   3   4     5    6    7     8    9 */
                   1090: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1091: /* Tndvar[k]    1   2   3               4          5 */
                   1092: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1093: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1094: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1095: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1096: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1097: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1098: /* Tprod[i]=k           4               7            */
                   1099: /* Tage[i]=k                  5               8      */
                   1100: /* */
                   1101: /* Type                    */
                   1102: /* V         1  2  3  4  5 */
                   1103: /*           F  F  V  V  V */
                   1104: /*           D  Q  D  D  Q */
                   1105: /*                         */
                   1106: int *TvarsD;
                   1107: int *TvarsDind;
                   1108: int *TvarsQ;
                   1109: int *TvarsQind;
                   1110: 
1.235     brouard  1111: #define MAXRESULTLINES 10
                   1112: int nresult=0;
                   1113: int TKresult[MAXRESULTLINES];
                   1114: double Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1115: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1116: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
                   1117: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1118: 
1.234     brouard  1119: /* int *TDvar; /\**< TDvar[1]=4,  TDvarF[2]=3, TDvar[3]=6  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
1.232     brouard  1120: int *TvarF; /**< TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1121: int *TvarFind; /**< TvarFind[1]=6,  TvarFind[2]=7, Tvarind[3]=9  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1122: int *TvarV; /**< TvarV[1]=Tvar[1]=5, TvarV[2]=Tvar[2]=4  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1123: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1124: int *TvarA; /**< TvarA[1]=Tvar[5]=5, TvarA[2]=Tvar[8]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1125: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  1126: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1127: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1128: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1129: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1130: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1131: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1132: int *TvarVQ; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   1133: int *TvarVQind; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   1134: 
1.230     brouard  1135: int *Tvarsel; /**< Selected covariates for output */
                   1136: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1137: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1138: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1139: int *Dummy; /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.197     brouard  1140: int *Tage;
1.227     brouard  1141: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1142: int *Tmodelind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.230     brouard  1143: int *TmodelInvind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/ 
                   1144: int *TmodelInvQind; /** Tmodelqind[1]=1 for V5(quantitative varying) position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1  */
1.145     brouard  1145: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1146: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1147: int **Tvard;
                   1148: int *Tprod;/**< Gives the k position of the k1 product */
                   1149: int *Tposprod; /**< Gives the k1 product from the k position */
                   1150: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   1151:    if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   1152:    Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
                   1153: */
                   1154: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1155: double *lsurv, *lpop, *tpop;
                   1156: 
1.231     brouard  1157: #define FD 1; /* Fixed dummy covariate */
                   1158: #define FQ 2; /* Fixed quantitative covariate */
                   1159: #define FP 3; /* Fixed product covariate */
                   1160: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1161: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1162: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1163: #define VD 10; /* Varying dummy covariate */
                   1164: #define VQ 11; /* Varying quantitative covariate */
                   1165: #define VP 12; /* Varying product covariate */
                   1166: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1167: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1168: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1169: #define APFD 16; /* Age product * fixed dummy covariate */
                   1170: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1171: #define APVD 18; /* Age product * varying dummy covariate */
                   1172: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1173: 
                   1174: #define FTYPE 1; /* Fixed covariate */
                   1175: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1176: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1177: 
                   1178: struct kmodel{
                   1179:        int maintype; /* main type */
                   1180:        int subtype; /* subtype */
                   1181: };
                   1182: struct kmodel modell[NCOVMAX];
                   1183: 
1.143     brouard  1184: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1185: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1186: 
                   1187: /**************** split *************************/
                   1188: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1189: {
                   1190:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1191:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1192:   */ 
                   1193:   char *ss;                            /* pointer */
1.186     brouard  1194:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1195: 
                   1196:   l1 = strlen(path );                  /* length of path */
                   1197:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1198:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1199:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1200:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1201:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1202:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1203:     /* get current working directory */
                   1204:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1205: #ifdef WIN32
                   1206:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1207: #else
                   1208:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1209: #endif
1.126     brouard  1210:       return( GLOCK_ERROR_GETCWD );
                   1211:     }
                   1212:     /* got dirc from getcwd*/
                   1213:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1214:   } else {                             /* strip directory from path */
1.126     brouard  1215:     ss++;                              /* after this, the filename */
                   1216:     l2 = strlen( ss );                 /* length of filename */
                   1217:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1218:     strcpy( name, ss );                /* save file name */
                   1219:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1220:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1221:     printf(" DIRC2 = %s \n",dirc);
                   1222:   }
                   1223:   /* We add a separator at the end of dirc if not exists */
                   1224:   l1 = strlen( dirc );                 /* length of directory */
                   1225:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1226:     dirc[l1] =  DIRSEPARATOR;
                   1227:     dirc[l1+1] = 0; 
                   1228:     printf(" DIRC3 = %s \n",dirc);
                   1229:   }
                   1230:   ss = strrchr( name, '.' );           /* find last / */
                   1231:   if (ss >0){
                   1232:     ss++;
                   1233:     strcpy(ext,ss);                    /* save extension */
                   1234:     l1= strlen( name);
                   1235:     l2= strlen(ss)+1;
                   1236:     strncpy( finame, name, l1-l2);
                   1237:     finame[l1-l2]= 0;
                   1238:   }
                   1239: 
                   1240:   return( 0 );                         /* we're done */
                   1241: }
                   1242: 
                   1243: 
                   1244: /******************************************/
                   1245: 
                   1246: void replace_back_to_slash(char *s, char*t)
                   1247: {
                   1248:   int i;
                   1249:   int lg=0;
                   1250:   i=0;
                   1251:   lg=strlen(t);
                   1252:   for(i=0; i<= lg; i++) {
                   1253:     (s[i] = t[i]);
                   1254:     if (t[i]== '\\') s[i]='/';
                   1255:   }
                   1256: }
                   1257: 
1.132     brouard  1258: char *trimbb(char *out, char *in)
1.137     brouard  1259: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1260:   char *s;
                   1261:   s=out;
                   1262:   while (*in != '\0'){
1.137     brouard  1263:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1264:       in++;
                   1265:     }
                   1266:     *out++ = *in++;
                   1267:   }
                   1268:   *out='\0';
                   1269:   return s;
                   1270: }
                   1271: 
1.187     brouard  1272: /* char *substrchaine(char *out, char *in, char *chain) */
                   1273: /* { */
                   1274: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1275: /*   char *s, *t; */
                   1276: /*   t=in;s=out; */
                   1277: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1278: /*     *out++ = *in++; */
                   1279: /*   } */
                   1280: 
                   1281: /*   /\* *in matches *chain *\/ */
                   1282: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1283: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1284: /*   } */
                   1285: /*   in--; chain--; */
                   1286: /*   while ( (*in != '\0')){ */
                   1287: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1288: /*     *out++ = *in++; */
                   1289: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1290: /*   } */
                   1291: /*   *out='\0'; */
                   1292: /*   out=s; */
                   1293: /*   return out; */
                   1294: /* } */
                   1295: char *substrchaine(char *out, char *in, char *chain)
                   1296: {
                   1297:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1298:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1299: 
                   1300:   char *strloc;
                   1301: 
                   1302:   strcpy (out, in); 
                   1303:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1304:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1305:   if(strloc != NULL){ 
                   1306:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1307:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1308:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1309:   }
                   1310:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1311:   return out;
                   1312: }
                   1313: 
                   1314: 
1.145     brouard  1315: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1316: {
1.187     brouard  1317:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1318:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1319:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1320:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1321:   */
1.160     brouard  1322:   char *s, *t;
1.145     brouard  1323:   t=in;s=in;
                   1324:   while ((*in != occ) && (*in != '\0')){
                   1325:     *alocc++ = *in++;
                   1326:   }
                   1327:   if( *in == occ){
                   1328:     *(alocc)='\0';
                   1329:     s=++in;
                   1330:   }
                   1331:  
                   1332:   if (s == t) {/* occ not found */
                   1333:     *(alocc-(in-s))='\0';
                   1334:     in=s;
                   1335:   }
                   1336:   while ( *in != '\0'){
                   1337:     *blocc++ = *in++;
                   1338:   }
                   1339: 
                   1340:   *blocc='\0';
                   1341:   return t;
                   1342: }
1.137     brouard  1343: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1344: {
1.187     brouard  1345:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1346:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1347:      gives blocc="abcdef2ghi" and alocc="j".
                   1348:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1349:   */
                   1350:   char *s, *t;
                   1351:   t=in;s=in;
                   1352:   while (*in != '\0'){
                   1353:     while( *in == occ){
                   1354:       *blocc++ = *in++;
                   1355:       s=in;
                   1356:     }
                   1357:     *blocc++ = *in++;
                   1358:   }
                   1359:   if (s == t) /* occ not found */
                   1360:     *(blocc-(in-s))='\0';
                   1361:   else
                   1362:     *(blocc-(in-s)-1)='\0';
                   1363:   in=s;
                   1364:   while ( *in != '\0'){
                   1365:     *alocc++ = *in++;
                   1366:   }
                   1367: 
                   1368:   *alocc='\0';
                   1369:   return s;
                   1370: }
                   1371: 
1.126     brouard  1372: int nbocc(char *s, char occ)
                   1373: {
                   1374:   int i,j=0;
                   1375:   int lg=20;
                   1376:   i=0;
                   1377:   lg=strlen(s);
                   1378:   for(i=0; i<= lg; i++) {
1.234     brouard  1379:     if  (s[i] == occ ) j++;
1.126     brouard  1380:   }
                   1381:   return j;
                   1382: }
                   1383: 
1.137     brouard  1384: /* void cutv(char *u,char *v, char*t, char occ) */
                   1385: /* { */
                   1386: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1387: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1388: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1389: /*   int i,lg,j,p=0; */
                   1390: /*   i=0; */
                   1391: /*   lg=strlen(t); */
                   1392: /*   for(j=0; j<=lg-1; j++) { */
                   1393: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1394: /*   } */
1.126     brouard  1395: 
1.137     brouard  1396: /*   for(j=0; j<p; j++) { */
                   1397: /*     (u[j] = t[j]); */
                   1398: /*   } */
                   1399: /*      u[p]='\0'; */
1.126     brouard  1400: 
1.137     brouard  1401: /*    for(j=0; j<= lg; j++) { */
                   1402: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1403: /*   } */
                   1404: /* } */
1.126     brouard  1405: 
1.160     brouard  1406: #ifdef _WIN32
                   1407: char * strsep(char **pp, const char *delim)
                   1408: {
                   1409:   char *p, *q;
                   1410:          
                   1411:   if ((p = *pp) == NULL)
                   1412:     return 0;
                   1413:   if ((q = strpbrk (p, delim)) != NULL)
                   1414:   {
                   1415:     *pp = q + 1;
                   1416:     *q = '\0';
                   1417:   }
                   1418:   else
                   1419:     *pp = 0;
                   1420:   return p;
                   1421: }
                   1422: #endif
                   1423: 
1.126     brouard  1424: /********************** nrerror ********************/
                   1425: 
                   1426: void nrerror(char error_text[])
                   1427: {
                   1428:   fprintf(stderr,"ERREUR ...\n");
                   1429:   fprintf(stderr,"%s\n",error_text);
                   1430:   exit(EXIT_FAILURE);
                   1431: }
                   1432: /*********************** vector *******************/
                   1433: double *vector(int nl, int nh)
                   1434: {
                   1435:   double *v;
                   1436:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1437:   if (!v) nrerror("allocation failure in vector");
                   1438:   return v-nl+NR_END;
                   1439: }
                   1440: 
                   1441: /************************ free vector ******************/
                   1442: void free_vector(double*v, int nl, int nh)
                   1443: {
                   1444:   free((FREE_ARG)(v+nl-NR_END));
                   1445: }
                   1446: 
                   1447: /************************ivector *******************************/
                   1448: int *ivector(long nl,long nh)
                   1449: {
                   1450:   int *v;
                   1451:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1452:   if (!v) nrerror("allocation failure in ivector");
                   1453:   return v-nl+NR_END;
                   1454: }
                   1455: 
                   1456: /******************free ivector **************************/
                   1457: void free_ivector(int *v, long nl, long nh)
                   1458: {
                   1459:   free((FREE_ARG)(v+nl-NR_END));
                   1460: }
                   1461: 
                   1462: /************************lvector *******************************/
                   1463: long *lvector(long nl,long nh)
                   1464: {
                   1465:   long *v;
                   1466:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1467:   if (!v) nrerror("allocation failure in ivector");
                   1468:   return v-nl+NR_END;
                   1469: }
                   1470: 
                   1471: /******************free lvector **************************/
                   1472: void free_lvector(long *v, long nl, long nh)
                   1473: {
                   1474:   free((FREE_ARG)(v+nl-NR_END));
                   1475: }
                   1476: 
                   1477: /******************* imatrix *******************************/
                   1478: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1479:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1480: { 
                   1481:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1482:   int **m; 
                   1483:   
                   1484:   /* allocate pointers to rows */ 
                   1485:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1486:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1487:   m += NR_END; 
                   1488:   m -= nrl; 
                   1489:   
                   1490:   
                   1491:   /* allocate rows and set pointers to them */ 
                   1492:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1493:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1494:   m[nrl] += NR_END; 
                   1495:   m[nrl] -= ncl; 
                   1496:   
                   1497:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1498:   
                   1499:   /* return pointer to array of pointers to rows */ 
                   1500:   return m; 
                   1501: } 
                   1502: 
                   1503: /****************** free_imatrix *************************/
                   1504: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1505:       int **m;
                   1506:       long nch,ncl,nrh,nrl; 
                   1507:      /* free an int matrix allocated by imatrix() */ 
                   1508: { 
                   1509:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1510:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1511: } 
                   1512: 
                   1513: /******************* matrix *******************************/
                   1514: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1515: {
                   1516:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1517:   double **m;
                   1518: 
                   1519:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1520:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1521:   m += NR_END;
                   1522:   m -= nrl;
                   1523: 
                   1524:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1525:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1526:   m[nrl] += NR_END;
                   1527:   m[nrl] -= ncl;
                   1528: 
                   1529:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1530:   return m;
1.145     brouard  1531:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1532: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1533: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1534:    */
                   1535: }
                   1536: 
                   1537: /*************************free matrix ************************/
                   1538: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1539: {
                   1540:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1541:   free((FREE_ARG)(m+nrl-NR_END));
                   1542: }
                   1543: 
                   1544: /******************* ma3x *******************************/
                   1545: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1546: {
                   1547:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1548:   double ***m;
                   1549: 
                   1550:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1551:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1552:   m += NR_END;
                   1553:   m -= nrl;
                   1554: 
                   1555:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1556:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1557:   m[nrl] += NR_END;
                   1558:   m[nrl] -= ncl;
                   1559: 
                   1560:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1561: 
                   1562:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1563:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1564:   m[nrl][ncl] += NR_END;
                   1565:   m[nrl][ncl] -= nll;
                   1566:   for (j=ncl+1; j<=nch; j++) 
                   1567:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1568:   
                   1569:   for (i=nrl+1; i<=nrh; i++) {
                   1570:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1571:     for (j=ncl+1; j<=nch; j++) 
                   1572:       m[i][j]=m[i][j-1]+nlay;
                   1573:   }
                   1574:   return m; 
                   1575:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1576:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1577:   */
                   1578: }
                   1579: 
                   1580: /*************************free ma3x ************************/
                   1581: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1582: {
                   1583:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1584:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1585:   free((FREE_ARG)(m+nrl-NR_END));
                   1586: }
                   1587: 
                   1588: /*************** function subdirf ***********/
                   1589: char *subdirf(char fileres[])
                   1590: {
                   1591:   /* Caution optionfilefiname is hidden */
                   1592:   strcpy(tmpout,optionfilefiname);
                   1593:   strcat(tmpout,"/"); /* Add to the right */
                   1594:   strcat(tmpout,fileres);
                   1595:   return tmpout;
                   1596: }
                   1597: 
                   1598: /*************** function subdirf2 ***********/
                   1599: char *subdirf2(char fileres[], char *preop)
                   1600: {
                   1601:   
                   1602:   /* Caution optionfilefiname is hidden */
                   1603:   strcpy(tmpout,optionfilefiname);
                   1604:   strcat(tmpout,"/");
                   1605:   strcat(tmpout,preop);
                   1606:   strcat(tmpout,fileres);
                   1607:   return tmpout;
                   1608: }
                   1609: 
                   1610: /*************** function subdirf3 ***********/
                   1611: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1612: {
                   1613:   
                   1614:   /* Caution optionfilefiname is hidden */
                   1615:   strcpy(tmpout,optionfilefiname);
                   1616:   strcat(tmpout,"/");
                   1617:   strcat(tmpout,preop);
                   1618:   strcat(tmpout,preop2);
                   1619:   strcat(tmpout,fileres);
                   1620:   return tmpout;
                   1621: }
1.213     brouard  1622:  
                   1623: /*************** function subdirfext ***********/
                   1624: char *subdirfext(char fileres[], char *preop, char *postop)
                   1625: {
                   1626:   
                   1627:   strcpy(tmpout,preop);
                   1628:   strcat(tmpout,fileres);
                   1629:   strcat(tmpout,postop);
                   1630:   return tmpout;
                   1631: }
1.126     brouard  1632: 
1.213     brouard  1633: /*************** function subdirfext3 ***********/
                   1634: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1635: {
                   1636:   
                   1637:   /* Caution optionfilefiname is hidden */
                   1638:   strcpy(tmpout,optionfilefiname);
                   1639:   strcat(tmpout,"/");
                   1640:   strcat(tmpout,preop);
                   1641:   strcat(tmpout,fileres);
                   1642:   strcat(tmpout,postop);
                   1643:   return tmpout;
                   1644: }
                   1645:  
1.162     brouard  1646: char *asc_diff_time(long time_sec, char ascdiff[])
                   1647: {
                   1648:   long sec_left, days, hours, minutes;
                   1649:   days = (time_sec) / (60*60*24);
                   1650:   sec_left = (time_sec) % (60*60*24);
                   1651:   hours = (sec_left) / (60*60) ;
                   1652:   sec_left = (sec_left) %(60*60);
                   1653:   minutes = (sec_left) /60;
                   1654:   sec_left = (sec_left) % (60);
                   1655:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1656:   return ascdiff;
                   1657: }
                   1658: 
1.126     brouard  1659: /***************** f1dim *************************/
                   1660: extern int ncom; 
                   1661: extern double *pcom,*xicom;
                   1662: extern double (*nrfunc)(double []); 
                   1663:  
                   1664: double f1dim(double x) 
                   1665: { 
                   1666:   int j; 
                   1667:   double f;
                   1668:   double *xt; 
                   1669:  
                   1670:   xt=vector(1,ncom); 
                   1671:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1672:   f=(*nrfunc)(xt); 
                   1673:   free_vector(xt,1,ncom); 
                   1674:   return f; 
                   1675: } 
                   1676: 
                   1677: /*****************brent *************************/
                   1678: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1679: {
                   1680:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1681:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1682:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1683:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1684:    * returned function value. 
                   1685:   */
1.126     brouard  1686:   int iter; 
                   1687:   double a,b,d,etemp;
1.159     brouard  1688:   double fu=0,fv,fw,fx;
1.164     brouard  1689:   double ftemp=0.;
1.126     brouard  1690:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1691:   double e=0.0; 
                   1692:  
                   1693:   a=(ax < cx ? ax : cx); 
                   1694:   b=(ax > cx ? ax : cx); 
                   1695:   x=w=v=bx; 
                   1696:   fw=fv=fx=(*f)(x); 
                   1697:   for (iter=1;iter<=ITMAX;iter++) { 
                   1698:     xm=0.5*(a+b); 
                   1699:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1700:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1701:     printf(".");fflush(stdout);
                   1702:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1703: #ifdef DEBUGBRENT
1.126     brouard  1704:     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);
                   1705:     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);
                   1706:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1707: #endif
                   1708:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1709:       *xmin=x; 
                   1710:       return fx; 
                   1711:     } 
                   1712:     ftemp=fu;
                   1713:     if (fabs(e) > tol1) { 
                   1714:       r=(x-w)*(fx-fv); 
                   1715:       q=(x-v)*(fx-fw); 
                   1716:       p=(x-v)*q-(x-w)*r; 
                   1717:       q=2.0*(q-r); 
                   1718:       if (q > 0.0) p = -p; 
                   1719:       q=fabs(q); 
                   1720:       etemp=e; 
                   1721:       e=d; 
                   1722:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1723:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1724:       else { 
1.224     brouard  1725:                                d=p/q; 
                   1726:                                u=x+d; 
                   1727:                                if (u-a < tol2 || b-u < tol2) 
                   1728:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1729:       } 
                   1730:     } else { 
                   1731:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1732:     } 
                   1733:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1734:     fu=(*f)(u); 
                   1735:     if (fu <= fx) { 
                   1736:       if (u >= x) a=x; else b=x; 
                   1737:       SHFT(v,w,x,u) 
1.183     brouard  1738:       SHFT(fv,fw,fx,fu) 
                   1739:     } else { 
                   1740:       if (u < x) a=u; else b=u; 
                   1741:       if (fu <= fw || w == x) { 
1.224     brouard  1742:                                v=w; 
                   1743:                                w=u; 
                   1744:                                fv=fw; 
                   1745:                                fw=fu; 
1.183     brouard  1746:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1747:                                v=u; 
                   1748:                                fv=fu; 
1.183     brouard  1749:       } 
                   1750:     } 
1.126     brouard  1751:   } 
                   1752:   nrerror("Too many iterations in brent"); 
                   1753:   *xmin=x; 
                   1754:   return fx; 
                   1755: } 
                   1756: 
                   1757: /****************** mnbrak ***********************/
                   1758: 
                   1759: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1760:            double (*func)(double)) 
1.183     brouard  1761: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1762: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1763: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1764: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1765:    */
1.126     brouard  1766:   double ulim,u,r,q, dum;
                   1767:   double fu; 
1.187     brouard  1768: 
                   1769:   double scale=10.;
                   1770:   int iterscale=0;
                   1771: 
                   1772:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1773:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1774: 
                   1775: 
                   1776:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1777:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1778:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1779:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1780:   /* } */
                   1781: 
1.126     brouard  1782:   if (*fb > *fa) { 
                   1783:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1784:     SHFT(dum,*fb,*fa,dum) 
                   1785:   } 
1.126     brouard  1786:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1787:   *fc=(*func)(*cx); 
1.183     brouard  1788: #ifdef DEBUG
1.224     brouard  1789:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1790:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
1.183     brouard  1791: #endif
1.224     brouard  1792:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
1.126     brouard  1793:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1794:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1795:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1796:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1797:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1798:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1799:       fu=(*func)(u); 
1.163     brouard  1800: #ifdef DEBUG
                   1801:       /* f(x)=A(x-u)**2+f(u) */
                   1802:       double A, fparabu; 
                   1803:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1804:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1805:       printf("\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
                   1806:       fprintf(ficlog,"\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
1.183     brouard  1807:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1808:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1809:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1810:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1811: #endif 
1.184     brouard  1812: #ifdef MNBRAKORIGINAL
1.183     brouard  1813: #else
1.191     brouard  1814: /*       if (fu > *fc) { */
                   1815: /* #ifdef DEBUG */
                   1816: /*       printf("mnbrak4  fu > fc \n"); */
                   1817: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1818: /* #endif */
                   1819: /*     /\* 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 *\\/  *\/ */
                   1820: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1821: /*     dum=u; /\* Shifting c and u *\/ */
                   1822: /*     u = *cx; */
                   1823: /*     *cx = dum; */
                   1824: /*     dum = fu; */
                   1825: /*     fu = *fc; */
                   1826: /*     *fc =dum; */
                   1827: /*       } else { /\* end *\/ */
                   1828: /* #ifdef DEBUG */
                   1829: /*       printf("mnbrak3  fu < fc \n"); */
                   1830: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1831: /* #endif */
                   1832: /*     dum=u; /\* Shifting c and u *\/ */
                   1833: /*     u = *cx; */
                   1834: /*     *cx = dum; */
                   1835: /*     dum = fu; */
                   1836: /*     fu = *fc; */
                   1837: /*     *fc =dum; */
                   1838: /*       } */
1.224     brouard  1839: #ifdef DEBUGMNBRAK
                   1840:                 double A, fparabu; 
                   1841:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1842:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1843:      printf("\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
                   1844:      fprintf(ficlog,"\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
1.183     brouard  1845: #endif
1.191     brouard  1846:       dum=u; /* Shifting c and u */
                   1847:       u = *cx;
                   1848:       *cx = dum;
                   1849:       dum = fu;
                   1850:       fu = *fc;
                   1851:       *fc =dum;
1.183     brouard  1852: #endif
1.162     brouard  1853:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1854: #ifdef DEBUG
1.224     brouard  1855:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1856:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1857: #endif
1.126     brouard  1858:       fu=(*func)(u); 
                   1859:       if (fu < *fc) { 
1.183     brouard  1860: #ifdef DEBUG
1.224     brouard  1861:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1862:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1863: #endif
                   1864:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1865:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1866: #ifdef DEBUG
                   1867:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1868: #endif
                   1869:       } 
1.162     brouard  1870:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1871: #ifdef DEBUG
1.224     brouard  1872:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1873:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1874: #endif
1.126     brouard  1875:       u=ulim; 
                   1876:       fu=(*func)(u); 
1.183     brouard  1877:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1878: #ifdef DEBUG
1.224     brouard  1879:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1880:       fprintf(ficlog,"\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
1.183     brouard  1881: #endif
1.126     brouard  1882:       u=(*cx)+GOLD*(*cx-*bx); 
                   1883:       fu=(*func)(u); 
1.224     brouard  1884: #ifdef DEBUG
                   1885:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1886:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1887: #endif
1.183     brouard  1888:     } /* end tests */
1.126     brouard  1889:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1890:     SHFT(*fa,*fb,*fc,fu) 
                   1891: #ifdef DEBUG
1.224     brouard  1892:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1893:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
1.183     brouard  1894: #endif
                   1895:   } /* 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  1896: } 
                   1897: 
                   1898: /*************** linmin ************************/
1.162     brouard  1899: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1900: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1901: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1902: the value of func at the returned location p . This is actually all accomplished by calling the
                   1903: routines mnbrak and brent .*/
1.126     brouard  1904: int ncom; 
                   1905: double *pcom,*xicom;
                   1906: double (*nrfunc)(double []); 
                   1907:  
1.224     brouard  1908: #ifdef LINMINORIGINAL
1.126     brouard  1909: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1910: #else
                   1911: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1912: #endif
1.126     brouard  1913: { 
                   1914:   double brent(double ax, double bx, double cx, 
                   1915:               double (*f)(double), double tol, double *xmin); 
                   1916:   double f1dim(double x); 
                   1917:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1918:              double *fc, double (*func)(double)); 
                   1919:   int j; 
                   1920:   double xx,xmin,bx,ax; 
                   1921:   double fx,fb,fa;
1.187     brouard  1922: 
1.203     brouard  1923: #ifdef LINMINORIGINAL
                   1924: #else
                   1925:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1926: #endif
                   1927:   
1.126     brouard  1928:   ncom=n; 
                   1929:   pcom=vector(1,n); 
                   1930:   xicom=vector(1,n); 
                   1931:   nrfunc=func; 
                   1932:   for (j=1;j<=n;j++) { 
                   1933:     pcom[j]=p[j]; 
1.202     brouard  1934:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1935:   } 
1.187     brouard  1936: 
1.203     brouard  1937: #ifdef LINMINORIGINAL
                   1938:   xx=1.;
                   1939: #else
                   1940:   axs=0.0;
                   1941:   xxs=1.;
                   1942:   do{
                   1943:     xx= xxs;
                   1944: #endif
1.187     brouard  1945:     ax=0.;
                   1946:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1947:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1948:     /* 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))   */
                   1949:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1950:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1951:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1952:     /* 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  1953: #ifdef LINMINORIGINAL
                   1954: #else
                   1955:     if (fx != fx){
1.224     brouard  1956:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1957:                        printf("|");
                   1958:                        fprintf(ficlog,"|");
1.203     brouard  1959: #ifdef DEBUGLINMIN
1.224     brouard  1960:                        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);
1.203     brouard  1961: #endif
                   1962:     }
1.224     brouard  1963:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1964: #endif
                   1965:   
1.191     brouard  1966: #ifdef DEBUGLINMIN
                   1967:   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  1968:   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  1969: #endif
1.224     brouard  1970: #ifdef LINMINORIGINAL
                   1971: #else
                   1972:        if(fb == fx){ /* Flat function in the direction */
                   1973:                xmin=xx;
                   1974:     *flat=1;
                   1975:        }else{
                   1976:     *flat=0;
                   1977: #endif
                   1978:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  1979:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1980:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1981:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1982:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1983:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1984: #ifdef DEBUG
1.224     brouard  1985:   printf("retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
                   1986:   fprintf(ficlog,"retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
                   1987: #endif
                   1988: #ifdef LINMINORIGINAL
                   1989: #else
                   1990:                        }
1.126     brouard  1991: #endif
1.191     brouard  1992: #ifdef DEBUGLINMIN
                   1993:   printf("linmin end ");
1.202     brouard  1994:   fprintf(ficlog,"linmin end ");
1.191     brouard  1995: #endif
1.126     brouard  1996:   for (j=1;j<=n;j++) { 
1.203     brouard  1997: #ifdef LINMINORIGINAL
                   1998:     xi[j] *= xmin; 
                   1999: #else
                   2000: #ifdef DEBUGLINMIN
                   2001:     if(xxs <1.0)
                   2002:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2003: #endif
                   2004:     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) */
                   2005: #ifdef DEBUGLINMIN
                   2006:     if(xxs <1.0)
                   2007:       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 );
                   2008: #endif
                   2009: #endif
1.187     brouard  2010:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2011:   } 
1.191     brouard  2012: #ifdef DEBUGLINMIN
1.203     brouard  2013:   printf("\n");
1.191     brouard  2014:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2015:   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  2016:   for (j=1;j<=n;j++) { 
1.202     brouard  2017:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2018:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2019:     if(j % ncovmodel == 0){
1.191     brouard  2020:       printf("\n");
1.202     brouard  2021:       fprintf(ficlog,"\n");
                   2022:     }
1.191     brouard  2023:   }
1.203     brouard  2024: #else
1.191     brouard  2025: #endif
1.126     brouard  2026:   free_vector(xicom,1,n); 
                   2027:   free_vector(pcom,1,n); 
                   2028: } 
                   2029: 
                   2030: 
                   2031: /*************** powell ************************/
1.162     brouard  2032: /*
                   2033: Minimization of a function func of n variables. Input consists of an initial starting point
                   2034: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2035: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2036: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2037: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2038: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2039:  */
1.224     brouard  2040: #ifdef LINMINORIGINAL
                   2041: #else
                   2042:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2043:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2044: #endif
1.126     brouard  2045: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2046:            double (*func)(double [])) 
                   2047: { 
1.224     brouard  2048: #ifdef LINMINORIGINAL
                   2049:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2050:              double (*func)(double [])); 
1.224     brouard  2051: #else 
                   2052:  void linmin(double p[], double xi[], int n, double *fret, 
                   2053:                                                 double (*func)(double []),int *flat); 
                   2054: #endif
1.126     brouard  2055:   int i,ibig,j; 
                   2056:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2057:   double directest;
1.126     brouard  2058:   double fp,fptt;
                   2059:   double *xits;
                   2060:   int niterf, itmp;
1.224     brouard  2061: #ifdef LINMINORIGINAL
                   2062: #else
                   2063: 
                   2064:   flatdir=ivector(1,n); 
                   2065:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2066: #endif
1.126     brouard  2067: 
                   2068:   pt=vector(1,n); 
                   2069:   ptt=vector(1,n); 
                   2070:   xit=vector(1,n); 
                   2071:   xits=vector(1,n); 
                   2072:   *fret=(*func)(p); 
                   2073:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2074:   rcurr_time = time(NULL);  
1.126     brouard  2075:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2076:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2077:     ibig=0; 
                   2078:     del=0.0; 
1.157     brouard  2079:     rlast_time=rcurr_time;
                   2080:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2081:     rcurr_time = time(NULL);  
                   2082:     curr_time = *localtime(&rcurr_time);
                   2083:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2084:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2085: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2086:     for (i=1;i<=n;i++) {
1.126     brouard  2087:       printf(" %d %.12f",i, p[i]);
                   2088:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   2089:       fprintf(ficrespow," %.12lf", p[i]);
                   2090:     }
                   2091:     printf("\n");
                   2092:     fprintf(ficlog,"\n");
                   2093:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2094:     if(*iter <=3){
1.157     brouard  2095:       tml = *localtime(&rcurr_time);
                   2096:       strcpy(strcurr,asctime(&tml));
                   2097:       rforecast_time=rcurr_time; 
1.126     brouard  2098:       itmp = strlen(strcurr);
                   2099:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.224     brouard  2100:                                strcurr[itmp-1]='\0';
1.162     brouard  2101:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2102:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2103:       for(niterf=10;niterf<=30;niterf+=10){
1.224     brouard  2104:                                rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2105:                                forecast_time = *localtime(&rforecast_time);
                   2106:                                strcpy(strfor,asctime(&forecast_time));
                   2107:                                itmp = strlen(strfor);
                   2108:                                if(strfor[itmp-1]=='\n')
                   2109:                                        strfor[itmp-1]='\0';
                   2110:                                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);
                   2111:                                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  2112:       }
                   2113:     }
1.187     brouard  2114:     for (i=1;i<=n;i++) { /* For each direction i */
                   2115:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2116:       fptt=(*fret); 
                   2117: #ifdef DEBUG
1.203     brouard  2118:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2119:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2120: #endif
1.203     brouard  2121:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2122:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2123: #ifdef LINMINORIGINAL
1.188     brouard  2124:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2125: #else
                   2126:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2127:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2128: #endif
                   2129:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2130:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2131:                                /* because that direction will be replaced unless the gain del is small */
                   2132:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2133:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2134:                                /* with the new direction. */
                   2135:                                del=fabs(fptt-(*fret)); 
                   2136:                                ibig=i; 
1.126     brouard  2137:       } 
                   2138: #ifdef DEBUG
                   2139:       printf("%d %.12e",i,(*fret));
                   2140:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2141:       for (j=1;j<=n;j++) {
1.224     brouard  2142:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2143:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2144:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2145:       }
                   2146:       for(j=1;j<=n;j++) {
1.225     brouard  2147:                                printf(" p(%d)=%.12e",j,p[j]);
                   2148:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2149:       }
                   2150:       printf("\n");
                   2151:       fprintf(ficlog,"\n");
                   2152: #endif
1.187     brouard  2153:     } /* end loop on each direction i */
                   2154:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2155:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2156:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2157:       for(j=1;j<=n;j++) {
1.225     brouard  2158:                                if(flatdir[j] >0){
                   2159:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2160:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2161:                                }
                   2162:                                /* printf("\n"); */
                   2163:                                /* fprintf(ficlog,"\n"); */
                   2164:                        }
1.182     brouard  2165:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  2166:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2167:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2168:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2169:       /* decreased of more than 3.84  */
                   2170:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2171:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2172:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2173:                        
1.188     brouard  2174:       /* Starting the program with initial values given by a former maximization will simply change */
                   2175:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2176:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2177:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2178: #ifdef DEBUG
                   2179:       int k[2],l;
                   2180:       k[0]=1;
                   2181:       k[1]=-1;
                   2182:       printf("Max: %.12e",(*func)(p));
                   2183:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2184:       for (j=1;j<=n;j++) {
                   2185:        printf(" %.12e",p[j]);
                   2186:        fprintf(ficlog," %.12e",p[j]);
                   2187:       }
                   2188:       printf("\n");
                   2189:       fprintf(ficlog,"\n");
                   2190:       for(l=0;l<=1;l++) {
                   2191:        for (j=1;j<=n;j++) {
                   2192:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2193:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2194:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2195:        }
                   2196:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2197:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2198:       }
                   2199: #endif
                   2200: 
1.224     brouard  2201: #ifdef LINMINORIGINAL
                   2202: #else
                   2203:       free_ivector(flatdir,1,n); 
                   2204: #endif
1.126     brouard  2205:       free_vector(xit,1,n); 
                   2206:       free_vector(xits,1,n); 
                   2207:       free_vector(ptt,1,n); 
                   2208:       free_vector(pt,1,n); 
                   2209:       return; 
1.192     brouard  2210:     } /* enough precision */ 
1.126     brouard  2211:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2212:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2213:       ptt[j]=2.0*p[j]-pt[j]; 
                   2214:       xit[j]=p[j]-pt[j]; 
                   2215:       pt[j]=p[j]; 
                   2216:     } 
1.181     brouard  2217:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2218: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2219:                if (*iter <=4) {
1.225     brouard  2220: #else
                   2221: #endif
1.224     brouard  2222: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2223: #else
1.161     brouard  2224:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2225: #endif
1.162     brouard  2226:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2227:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2228:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2229:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2230:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2231:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2232:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2233:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2234:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2235:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2236:       /* mu² and del² are equal when f3=f1 */
                   2237:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2238:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2239:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2240:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2241: #ifdef NRCORIGINAL
                   2242:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2243: #else
                   2244:       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  2245:       t= t- del*SQR(fp-fptt);
1.183     brouard  2246: #endif
1.202     brouard  2247:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2248: #ifdef DEBUG
1.181     brouard  2249:       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);
                   2250:       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  2251:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2252:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2253:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2254:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2255:       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);
                   2256:       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);
                   2257: #endif
1.183     brouard  2258: #ifdef POWELLORIGINAL
                   2259:       if (t < 0.0) { /* Then we use it for new direction */
                   2260: #else
1.182     brouard  2261:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2262:                                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  2263:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.224     brouard  2264:         fprintf(ficlog,"directest= %.12lf (if directest<0 or t<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  2265:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2266:       } 
1.181     brouard  2267:       if (directest < 0.0) { /* Then we use it for new direction */
                   2268: #endif
1.191     brouard  2269: #ifdef DEBUGLINMIN
1.234     brouard  2270:        printf("Before linmin in direction P%d-P0\n",n);
                   2271:        for (j=1;j<=n;j++) {
                   2272:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2273:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2274:          if(j % ncovmodel == 0){
                   2275:            printf("\n");
                   2276:            fprintf(ficlog,"\n");
                   2277:          }
                   2278:        }
1.224     brouard  2279: #endif
                   2280: #ifdef LINMINORIGINAL
1.234     brouard  2281:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2282: #else
1.234     brouard  2283:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2284:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2285: #endif
1.234     brouard  2286:        
1.191     brouard  2287: #ifdef DEBUGLINMIN
1.234     brouard  2288:        for (j=1;j<=n;j++) { 
                   2289:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2290:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2291:          if(j % ncovmodel == 0){
                   2292:            printf("\n");
                   2293:            fprintf(ficlog,"\n");
                   2294:          }
                   2295:        }
1.224     brouard  2296: #endif
1.234     brouard  2297:        for (j=1;j<=n;j++) { 
                   2298:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2299:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2300:        }
1.224     brouard  2301: #ifdef LINMINORIGINAL
                   2302: #else
1.234     brouard  2303:        for (j=1, flatd=0;j<=n;j++) {
                   2304:          if(flatdir[j]>0)
                   2305:            flatd++;
                   2306:        }
                   2307:        if(flatd >0){
                   2308:          printf("%d flat directions\n",flatd);
                   2309:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2310:          for (j=1;j<=n;j++) { 
                   2311:            if(flatdir[j]>0){
                   2312:              printf("%d ",j);
                   2313:              fprintf(ficlog,"%d ",j);
                   2314:            }
                   2315:          }
                   2316:          printf("\n");
                   2317:          fprintf(ficlog,"\n");
                   2318:        }
1.191     brouard  2319: #endif
1.234     brouard  2320:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2321:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2322:        
1.126     brouard  2323: #ifdef DEBUG
1.234     brouard  2324:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2325:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2326:        for(j=1;j<=n;j++){
                   2327:          printf(" %lf",xit[j]);
                   2328:          fprintf(ficlog," %lf",xit[j]);
                   2329:        }
                   2330:        printf("\n");
                   2331:        fprintf(ficlog,"\n");
1.126     brouard  2332: #endif
1.192     brouard  2333:       } /* end of t or directest negative */
1.224     brouard  2334: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2335: #else
1.234     brouard  2336:       } /* end if (fptt < fp)  */
1.192     brouard  2337: #endif
1.225     brouard  2338: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2339:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2340: #else
1.224     brouard  2341: #endif
1.234     brouard  2342:                } /* loop iteration */ 
1.126     brouard  2343: } 
1.234     brouard  2344:   
1.126     brouard  2345: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2346:   
1.235     brouard  2347:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
1.234     brouard  2348:   {
1.235     brouard  2349:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2350:        (and selected quantitative values in nres)
                   2351:        by left multiplying the unit
1.234     brouard  2352:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2353:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2354:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2355:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2356:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2357:   /* Initial matrix pimij */
                   2358:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2359:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2360:   /*  0,                   0                  , 1} */
                   2361:   /*
                   2362:    * and after some iteration: */
                   2363:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2364:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2365:   /*  0,                   0                  , 1} */
                   2366:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2367:   /* {0.51571254859325999, 0.4842874514067399, */
                   2368:   /*  0.51326036147820708, 0.48673963852179264} */
                   2369:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2370:     
1.126     brouard  2371:   int i, ii,j,k;
1.209     brouard  2372:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2373:   /* double **matprod2(); */ /* test */
1.218     brouard  2374:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2375:   double **newm;
1.209     brouard  2376:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2377:   int ncvloop=0;
1.169     brouard  2378:   
1.209     brouard  2379:   min=vector(1,nlstate);
                   2380:   max=vector(1,nlstate);
                   2381:   meandiff=vector(1,nlstate);
                   2382: 
1.218     brouard  2383:        /* Starting with matrix unity */
1.126     brouard  2384:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2385:     for (j=1;j<=nlstate+ndeath;j++){
                   2386:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2387:     }
1.169     brouard  2388:   
                   2389:   cov[1]=1.;
                   2390:   
                   2391:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2392:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2393:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2394:     ncvloop++;
1.126     brouard  2395:     newm=savm;
                   2396:     /* Covariates have to be included here again */
1.138     brouard  2397:     cov[2]=agefin;
1.187     brouard  2398:     if(nagesqr==1)
                   2399:       cov[3]= agefin*agefin;;
1.234     brouard  2400:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2401:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2402:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2403:       /* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
1.234     brouard  2404:     }
                   2405:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2406:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2407:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2408:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
1.138     brouard  2409:     }
1.234     brouard  2410:     for (k=1; k<=cptcovage;k++){
                   2411:       if(Dummy[Tvar[Tage[k]]]){
                   2412:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2413:       } else{
1.235     brouard  2414:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2415:       }
1.235     brouard  2416:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
1.234     brouard  2417:     }
                   2418:     for (k=1; k<=cptcovprod;k++){ /*  */
1.235     brouard  2419:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
1.200     brouard  2420:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.234     brouard  2421:     }
1.138     brouard  2422:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2423:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2424:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2425:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2426:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2427:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2428:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2429:     
1.126     brouard  2430:     savm=oldm;
                   2431:     oldm=newm;
1.209     brouard  2432: 
                   2433:     for(j=1; j<=nlstate; j++){
                   2434:       max[j]=0.;
                   2435:       min[j]=1.;
                   2436:     }
                   2437:     for(i=1;i<=nlstate;i++){
                   2438:       sumnew=0;
                   2439:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2440:       for(j=1; j<=nlstate; j++){ 
                   2441:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2442:        max[j]=FMAX(max[j],prlim[i][j]);
                   2443:        min[j]=FMIN(min[j],prlim[i][j]);
                   2444:       }
                   2445:     }
                   2446: 
1.126     brouard  2447:     maxmax=0.;
1.209     brouard  2448:     for(j=1; j<=nlstate; j++){
                   2449:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2450:       maxmax=FMAX(maxmax,meandiff[j]);
                   2451:       /* 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  2452:     } /* j loop */
1.203     brouard  2453:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2454:     /* 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  2455:     if(maxmax < ftolpl){
1.209     brouard  2456:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2457:       free_vector(min,1,nlstate);
                   2458:       free_vector(max,1,nlstate);
                   2459:       free_vector(meandiff,1,nlstate);
1.126     brouard  2460:       return prlim;
                   2461:     }
1.169     brouard  2462:   } /* age loop */
1.208     brouard  2463:     /* After some age loop it doesn't converge */
1.209     brouard  2464:   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  2465: 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  2466:   /* 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); */
                   2467:   free_vector(min,1,nlstate);
                   2468:   free_vector(max,1,nlstate);
                   2469:   free_vector(meandiff,1,nlstate);
1.208     brouard  2470:   
1.169     brouard  2471:   return prlim; /* should not reach here */
1.126     brouard  2472: }
                   2473: 
1.217     brouard  2474: 
                   2475:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2476: 
1.218     brouard  2477:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2478:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2479:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2480: {
1.218     brouard  2481:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2482:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2483:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2484:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2485:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2486:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2487:   /* Initial matrix pimij */
                   2488:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2489:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2490:   /*  0,                   0                  , 1} */
                   2491:   /*
                   2492:    * and after some iteration: */
                   2493:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2494:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2495:   /*  0,                   0                  , 1} */
                   2496:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2497:   /* {0.51571254859325999, 0.4842874514067399, */
                   2498:   /*  0.51326036147820708, 0.48673963852179264} */
                   2499:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2500: 
                   2501:   int i, ii,j,k;
                   2502:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2503:   /* double **matprod2(); */ /* test */
                   2504:   double **out, cov[NCOVMAX+1], **bmij();
                   2505:   double **newm;
1.218     brouard  2506:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2507:   double        **oldm, **savm;  /* for use */
                   2508: 
1.217     brouard  2509:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2510:   int ncvloop=0;
                   2511:   
                   2512:   min=vector(1,nlstate);
                   2513:   max=vector(1,nlstate);
                   2514:   meandiff=vector(1,nlstate);
                   2515: 
1.218     brouard  2516:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2517:        oldm=oldms; savm=savms;
                   2518: 
                   2519:        /* Starting with matrix unity */
                   2520:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2521:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2522:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2523:     }
                   2524:   
                   2525:   cov[1]=1.;
                   2526:   
                   2527:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2528:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2529:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2530:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2531:     ncvloop++;
1.218     brouard  2532:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2533:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2534:     /* Covariates have to be included here again */
                   2535:     cov[2]=agefin;
                   2536:     if(nagesqr==1)
                   2537:       cov[3]= agefin*agefin;;
                   2538:     for (k=1; k<=cptcovn;k++) {
                   2539:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2540:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2541:       /* 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])]); */
                   2542:     }
                   2543:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2544:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2545:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2546:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2547:     
                   2548:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2549:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2550:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2551:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2552:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2553:                /* ij should be linked to the correct index of cov */
                   2554:                /* age and covariate values ij are in 'cov', but we need to pass
                   2555:                 * ij for the observed prevalence at age and status and covariate
                   2556:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2557:                 */
                   2558:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2559:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2560:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.217     brouard  2561:     savm=oldm;
                   2562:     oldm=newm;
                   2563:     for(j=1; j<=nlstate; j++){
                   2564:       max[j]=0.;
                   2565:       min[j]=1.;
                   2566:     }
                   2567:     for(j=1; j<=nlstate; j++){ 
                   2568:       for(i=1;i<=nlstate;i++){
1.234     brouard  2569:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2570:        bprlim[i][j]= newm[i][j];
                   2571:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2572:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2573:       }
                   2574:     }
1.218     brouard  2575:                
1.217     brouard  2576:     maxmax=0.;
                   2577:     for(i=1; i<=nlstate; i++){
                   2578:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2579:       maxmax=FMAX(maxmax,meandiff[i]);
                   2580:       /* 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); */
                   2581:     } /* j loop */
                   2582:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2583:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2584:     if(maxmax < ftolpl){
1.220     brouard  2585:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2586:       free_vector(min,1,nlstate);
                   2587:       free_vector(max,1,nlstate);
                   2588:       free_vector(meandiff,1,nlstate);
                   2589:       return bprlim;
                   2590:     }
                   2591:   } /* age loop */
                   2592:     /* After some age loop it doesn't converge */
                   2593:   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\
                   2594: 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);
                   2595:   /* 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); */
                   2596:   free_vector(min,1,nlstate);
                   2597:   free_vector(max,1,nlstate);
                   2598:   free_vector(meandiff,1,nlstate);
                   2599:   
                   2600:   return bprlim; /* should not reach here */
                   2601: }
                   2602: 
1.126     brouard  2603: /*************** transition probabilities ***************/ 
                   2604: 
                   2605: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2606: {
1.138     brouard  2607:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2608:      computes the probability to be observed in state j being in state i by appying the
                   2609:      model to the ncovmodel covariates (including constant and age).
                   2610:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2611:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2612:      ncth covariate in the global vector x is given by the formula:
                   2613:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2614:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2615:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2616:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2617:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2618:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2619:   */
                   2620:   double s1, lnpijopii;
1.126     brouard  2621:   /*double t34;*/
1.164     brouard  2622:   int i,j, nc, ii, jj;
1.126     brouard  2623: 
1.223     brouard  2624:   for(i=1; i<= nlstate; i++){
                   2625:     for(j=1; j<i;j++){
                   2626:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2627:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2628:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2629:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2630:       }
                   2631:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2632:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2633:     }
                   2634:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2635:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2636:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2637:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2638:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2639:       }
                   2640:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2641:     }
                   2642:   }
1.218     brouard  2643:   
1.223     brouard  2644:   for(i=1; i<= nlstate; i++){
                   2645:     s1=0;
                   2646:     for(j=1; j<i; j++){
                   2647:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2648:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2649:     }
                   2650:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2651:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2652:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2653:     }
                   2654:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2655:     ps[i][i]=1./(s1+1.);
                   2656:     /* Computing other pijs */
                   2657:     for(j=1; j<i; j++)
                   2658:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2659:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2660:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2661:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2662:   } /* end i */
1.218     brouard  2663:   
1.223     brouard  2664:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2665:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2666:       ps[ii][jj]=0;
                   2667:       ps[ii][ii]=1;
                   2668:     }
                   2669:   }
1.218     brouard  2670:   
                   2671:   
1.223     brouard  2672:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2673:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2674:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2675:   /*   } */
                   2676:   /*   printf("\n "); */
                   2677:   /* } */
                   2678:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2679:   /*
                   2680:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2681:                goto end;*/
1.223     brouard  2682:   return ps;
1.126     brouard  2683: }
                   2684: 
1.218     brouard  2685: /*************** backward transition probabilities ***************/ 
                   2686: 
                   2687:  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2688: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2689:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2690: {
1.222     brouard  2691:   /* Computes the backward probability at age agefin and covariate ij
                   2692:    * and returns in **ps as well as **bmij.
                   2693:    */
1.218     brouard  2694:   int i, ii, j,k;
1.222     brouard  2695:   
                   2696:   double **out, **pmij();
                   2697:   double sumnew=0.;
1.218     brouard  2698:   double agefin;
1.222     brouard  2699:   
                   2700:   double **dnewm, **dsavm, **doldm;
                   2701:   double **bbmij;
                   2702:   
1.218     brouard  2703:   doldm=ddoldms; /* global pointers */
1.222     brouard  2704:   dnewm=ddnewms;
                   2705:   dsavm=ddsavms;
                   2706:   
                   2707:   agefin=cov[2];
                   2708:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2709:      the observed prevalence (with this covariate ij) */
                   2710:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2711:   /* We do have the matrix Px in savm  and we need pij */
                   2712:   for (j=1;j<=nlstate+ndeath;j++){
                   2713:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2714:     for (ii=1;ii<=nlstate;ii++){
                   2715:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2716:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2717:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2718:       if(sumnew >= 1.e-10){
                   2719:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2720:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2721:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2722:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2723:        /* }else */
                   2724:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2725:       }else{
                   2726:        printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
                   2727:       }
                   2728:     } /*End ii */
                   2729:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2730:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2731:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2732:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2733:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2734:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2735:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2736:   for (j=1;j<=nlstate+ndeath;j++){
                   2737:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2738:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2739:     }
                   2740:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2741:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2742:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2743:   /* end bmij */
                   2744:   return ps; 
1.218     brouard  2745: }
1.217     brouard  2746: /*************** transition probabilities ***************/ 
                   2747: 
1.218     brouard  2748: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2749: {
                   2750:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2751:      computes the probability to be observed in state j being in state i by appying the
                   2752:      model to the ncovmodel covariates (including constant and age).
                   2753:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2754:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2755:      ncth covariate in the global vector x is given by the formula:
                   2756:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2757:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2758:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2759:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2760:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2761:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2762:   */
                   2763:   double s1, lnpijopii;
                   2764:   /*double t34;*/
                   2765:   int i,j, nc, ii, jj;
                   2766: 
1.234     brouard  2767:   for(i=1; i<= nlstate; i++){
                   2768:     for(j=1; j<i;j++){
                   2769:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2770:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2771:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2772:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2773:       }
                   2774:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2775:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2776:     }
                   2777:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2778:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2779:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2780:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2781:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2782:       }
                   2783:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2784:     }
                   2785:   }
                   2786:   
                   2787:   for(i=1; i<= nlstate; i++){
                   2788:     s1=0;
                   2789:     for(j=1; j<i; j++){
                   2790:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2791:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2792:     }
                   2793:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2794:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2795:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2796:     }
                   2797:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2798:     ps[i][i]=1./(s1+1.);
                   2799:     /* Computing other pijs */
                   2800:     for(j=1; j<i; j++)
                   2801:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2802:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2803:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2804:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2805:   } /* end i */
                   2806:   
                   2807:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2808:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2809:       ps[ii][jj]=0;
                   2810:       ps[ii][ii]=1;
                   2811:     }
                   2812:   }
                   2813:   /* Added for backcast */ /* Transposed matrix too */
                   2814:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2815:     s1=0.;
                   2816:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2817:       s1+=ps[ii][jj];
                   2818:     }
                   2819:     for(ii=1; ii<= nlstate; ii++){
                   2820:       ps[ii][jj]=ps[ii][jj]/s1;
                   2821:     }
                   2822:   }
                   2823:   /* Transposition */
                   2824:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2825:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2826:       s1=ps[ii][jj];
                   2827:       ps[ii][jj]=ps[jj][ii];
                   2828:       ps[jj][ii]=s1;
                   2829:     }
                   2830:   }
                   2831:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2832:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2833:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2834:   /*   } */
                   2835:   /*   printf("\n "); */
                   2836:   /* } */
                   2837:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2838:   /*
                   2839:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2840:     goto end;*/
                   2841:   return ps;
1.217     brouard  2842: }
                   2843: 
                   2844: 
1.126     brouard  2845: /**************** Product of 2 matrices ******************/
                   2846: 
1.145     brouard  2847: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2848: {
                   2849:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2850:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2851:   /* in, b, out are matrice of pointers which should have been initialized 
                   2852:      before: only the contents of out is modified. The function returns
                   2853:      a pointer to pointers identical to out */
1.145     brouard  2854:   int i, j, k;
1.126     brouard  2855:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2856:     for(k=ncolol; k<=ncoloh; k++){
                   2857:       out[i][k]=0.;
                   2858:       for(j=ncl; j<=nch; j++)
                   2859:        out[i][k] +=in[i][j]*b[j][k];
                   2860:     }
1.126     brouard  2861:   return out;
                   2862: }
                   2863: 
                   2864: 
                   2865: /************* Higher Matrix Product ***************/
                   2866: 
1.235     brouard  2867: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
1.126     brouard  2868: {
1.218     brouard  2869:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2870:      'nhstepm*hstepm*stepm' months (i.e. until
                   2871:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2872:      nhstepm*hstepm matrices. 
                   2873:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2874:      (typically every 2 years instead of every month which is too big 
                   2875:      for the memory).
                   2876:      Model is determined by parameters x and covariates have to be 
                   2877:      included manually here. 
                   2878: 
                   2879:      */
                   2880: 
                   2881:   int i, j, d, h, k;
1.131     brouard  2882:   double **out, cov[NCOVMAX+1];
1.126     brouard  2883:   double **newm;
1.187     brouard  2884:   double agexact;
1.214     brouard  2885:   double agebegin, ageend;
1.126     brouard  2886: 
                   2887:   /* Hstepm could be zero and should return the unit matrix */
                   2888:   for (i=1;i<=nlstate+ndeath;i++)
                   2889:     for (j=1;j<=nlstate+ndeath;j++){
                   2890:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2891:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2892:     }
                   2893:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2894:   for(h=1; h <=nhstepm; h++){
                   2895:     for(d=1; d <=hstepm; d++){
                   2896:       newm=savm;
                   2897:       /* Covariates have to be included here again */
                   2898:       cov[1]=1.;
1.214     brouard  2899:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2900:       cov[2]=agexact;
                   2901:       if(nagesqr==1)
1.227     brouard  2902:        cov[3]= agexact*agexact;
1.235     brouard  2903:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2904:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2905:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2906:        /* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
                   2907:       }
                   2908:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2909:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2910:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2911:        /* printf("hPxij Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
                   2912:       }
                   2913:       for (k=1; k<=cptcovage;k++){
                   2914:        if(Dummy[Tvar[Tage[k]]]){
                   2915:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2916:        } else{
                   2917:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2918:        }
                   2919:        /* printf("hPxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
                   2920:       }
                   2921:       for (k=1; k<=cptcovprod;k++){ /*  */
                   2922:        /* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
                   2923:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2924:       }
                   2925:       /* for (k=1; k<=cptcovn;k++)  */
                   2926:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2927:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   2928:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2929:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   2930:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  2931:       
                   2932:       
1.126     brouard  2933:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2934:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2935:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2936:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2937:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2938:       /* if((int)age == 70){ */
                   2939:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2940:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2941:       /*         printf("%d pmmij ",i); */
                   2942:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2943:       /*           printf("%f ",pmmij[i][j]); */
                   2944:       /*         } */
                   2945:       /*         printf(" oldm "); */
                   2946:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2947:       /*           printf("%f ",oldm[i][j]); */
                   2948:       /*         } */
                   2949:       /*         printf("\n"); */
                   2950:       /*       } */
                   2951:       /* } */
1.126     brouard  2952:       savm=oldm;
                   2953:       oldm=newm;
                   2954:     }
                   2955:     for(i=1; i<=nlstate+ndeath; i++)
                   2956:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2957:                                po[i][j][h]=newm[i][j];
                   2958:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2959:       }
1.128     brouard  2960:     /*printf("h=%d ",h);*/
1.126     brouard  2961:   } /* end h */
1.218     brouard  2962:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2963:   return po;
                   2964: }
                   2965: 
1.217     brouard  2966: /************* Higher Back Matrix Product ***************/
1.218     brouard  2967: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
1.222     brouard  2968: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2969: {
1.218     brouard  2970:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2971:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2972:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2973:      nhstepm*hstepm matrices.
                   2974:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2975:      (typically every 2 years instead of every month which is too big
1.217     brouard  2976:      for the memory).
1.218     brouard  2977:      Model is determined by parameters x and covariates have to be
                   2978:      included manually here.
1.217     brouard  2979: 
1.222     brouard  2980:   */
1.217     brouard  2981: 
                   2982:   int i, j, d, h, k;
                   2983:   double **out, cov[NCOVMAX+1];
                   2984:   double **newm;
                   2985:   double agexact;
                   2986:   double agebegin, ageend;
1.222     brouard  2987:   double **oldm, **savm;
1.217     brouard  2988: 
1.222     brouard  2989:   oldm=oldms;savm=savms;
1.217     brouard  2990:   /* Hstepm could be zero and should return the unit matrix */
                   2991:   for (i=1;i<=nlstate+ndeath;i++)
                   2992:     for (j=1;j<=nlstate+ndeath;j++){
                   2993:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2994:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2995:     }
                   2996:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2997:   for(h=1; h <=nhstepm; h++){
                   2998:     for(d=1; d <=hstepm; d++){
                   2999:       newm=savm;
                   3000:       /* Covariates have to be included here again */
                   3001:       cov[1]=1.;
                   3002:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3003:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3004:       cov[2]=agexact;
                   3005:       if(nagesqr==1)
1.222     brouard  3006:        cov[3]= agexact*agexact;
1.218     brouard  3007:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3008:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3009:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3010:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3011:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3012:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3013:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3014:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3015:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3016:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.218     brouard  3017:                        
                   3018:                        
1.217     brouard  3019:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3020:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3021:       /* Careful transposed matrix */
1.222     brouard  3022:       /* age is in cov[2] */
1.218     brouard  3023:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3024:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3025:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3026:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3027:       /* if((int)age == 70){ */
                   3028:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3029:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3030:       /*         printf("%d pmmij ",i); */
                   3031:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3032:       /*           printf("%f ",pmmij[i][j]); */
                   3033:       /*         } */
                   3034:       /*         printf(" oldm "); */
                   3035:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3036:       /*           printf("%f ",oldm[i][j]); */
                   3037:       /*         } */
                   3038:       /*         printf("\n"); */
                   3039:       /*       } */
                   3040:       /* } */
                   3041:       savm=oldm;
                   3042:       oldm=newm;
                   3043:     }
                   3044:     for(i=1; i<=nlstate+ndeath; i++)
                   3045:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3046:        po[i][j][h]=newm[i][j];
                   3047:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3048:       }
                   3049:     /*printf("h=%d ",h);*/
                   3050:   } /* end h */
1.222     brouard  3051:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3052:   return po;
                   3053: }
                   3054: 
                   3055: 
1.162     brouard  3056: #ifdef NLOPT
                   3057:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3058:   double fret;
                   3059:   double *xt;
                   3060:   int j;
                   3061:   myfunc_data *d2 = (myfunc_data *) pd;
                   3062: /* xt = (p1-1); */
                   3063:   xt=vector(1,n); 
                   3064:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3065: 
                   3066:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3067:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3068:   printf("Function = %.12lf ",fret);
                   3069:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3070:   printf("\n");
                   3071:  free_vector(xt,1,n);
                   3072:   return fret;
                   3073: }
                   3074: #endif
1.126     brouard  3075: 
                   3076: /*************** log-likelihood *************/
                   3077: double func( double *x)
                   3078: {
1.226     brouard  3079:   int i, ii, j, k, mi, d, kk;
                   3080:   int ioffset=0;
                   3081:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3082:   double **out;
                   3083:   double lli; /* Individual log likelihood */
                   3084:   int s1, s2;
1.228     brouard  3085:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.226     brouard  3086:   double bbh, survp;
                   3087:   long ipmx;
                   3088:   double agexact;
                   3089:   /*extern weight */
                   3090:   /* We are differentiating ll according to initial status */
                   3091:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3092:   /*for(i=1;i<imx;i++) 
                   3093:     printf(" %d\n",s[4][i]);
                   3094:   */
1.162     brouard  3095: 
1.226     brouard  3096:   ++countcallfunc;
1.162     brouard  3097: 
1.226     brouard  3098:   cov[1]=1.;
1.126     brouard  3099: 
1.226     brouard  3100:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3101:   ioffset=0;
1.226     brouard  3102:   if(mle==1){
                   3103:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3104:       /* Computes the values of the ncovmodel covariates of the model
                   3105:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3106:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3107:         to be observed in j being in i according to the model.
                   3108:       */
                   3109:       ioffset=2+nagesqr+cptcovage;
1.233     brouard  3110:    /* Fixed */
1.234     brouard  3111:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3112:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   3113:       }
1.226     brouard  3114:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3115:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3116:         has been calculated etc */
                   3117:       /* For an individual i, wav[i] gives the number of effective waves */
                   3118:       /* We compute the contribution to Likelihood of each effective transition
                   3119:         mw[mi][i] is real wave of the mi th effectve wave */
                   3120:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3121:         s2=s[mw[mi+1][i]][i];
                   3122:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3123:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3124:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3125:       */
                   3126:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3127:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
                   3128:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
                   3129:        }
                   3130:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3131:          for (j=1;j<=nlstate+ndeath;j++){
                   3132:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3133:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3134:          }
                   3135:        for(d=0; d<dh[mi][i]; d++){
                   3136:          newm=savm;
                   3137:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3138:          cov[2]=agexact;
                   3139:          if(nagesqr==1)
                   3140:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3141:          for (kk=1; kk<=cptcovage;kk++) {
                   3142:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3143:          }
                   3144:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3145:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3146:          savm=oldm;
                   3147:          oldm=newm;
                   3148:        } /* end mult */
                   3149:        
                   3150:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3151:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3152:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3153:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3154:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3155:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3156:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3157:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3158:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3159:                                 * -stepm/2 to stepm/2 .
                   3160:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3161:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3162:                                 */
1.234     brouard  3163:        s1=s[mw[mi][i]][i];
                   3164:        s2=s[mw[mi+1][i]][i];
                   3165:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3166:        /* bias bh is positive if real duration
                   3167:         * is higher than the multiple of stepm and negative otherwise.
                   3168:         */
                   3169:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3170:        if( s2 > nlstate){ 
                   3171:          /* i.e. if s2 is a death state and if the date of death is known 
                   3172:             then the contribution to the likelihood is the probability to 
                   3173:             die between last step unit time and current  step unit time, 
                   3174:             which is also equal to probability to die before dh 
                   3175:             minus probability to die before dh-stepm . 
                   3176:             In version up to 0.92 likelihood was computed
                   3177:             as if date of death was unknown. Death was treated as any other
                   3178:             health state: the date of the interview describes the actual state
                   3179:             and not the date of a change in health state. The former idea was
                   3180:             to consider that at each interview the state was recorded
                   3181:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3182:             introduced the exact date of death then we should have modified
                   3183:             the contribution of an exact death to the likelihood. This new
                   3184:             contribution is smaller and very dependent of the step unit
                   3185:             stepm. It is no more the probability to die between last interview
                   3186:             and month of death but the probability to survive from last
                   3187:             interview up to one month before death multiplied by the
                   3188:             probability to die within a month. Thanks to Chris
                   3189:             Jackson for correcting this bug.  Former versions increased
                   3190:             mortality artificially. The bad side is that we add another loop
                   3191:             which slows down the processing. The difference can be up to 10%
                   3192:             lower mortality.
                   3193:          */
                   3194:          /* If, at the beginning of the maximization mostly, the
                   3195:             cumulative probability or probability to be dead is
                   3196:             constant (ie = 1) over time d, the difference is equal to
                   3197:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3198:             s1 at precedent wave, to be dead a month before current
                   3199:             wave is equal to probability, being at state s1 at
                   3200:             precedent wave, to be dead at mont of the current
                   3201:             wave. Then the observed probability (that this person died)
                   3202:             is null according to current estimated parameter. In fact,
                   3203:             it should be very low but not zero otherwise the log go to
                   3204:             infinity.
                   3205:          */
1.183     brouard  3206: /* #ifdef INFINITYORIGINAL */
                   3207: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3208: /* #else */
                   3209: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3210: /*         lli=log(mytinydouble); */
                   3211: /*       else */
                   3212: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3213: /* #endif */
1.226     brouard  3214:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3215:          
1.226     brouard  3216:        } else if  ( s2==-1 ) { /* alive */
                   3217:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3218:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3219:          /*survp += out[s1][j]; */
                   3220:          lli= log(survp);
                   3221:        }
                   3222:        else if  (s2==-4) { 
                   3223:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3224:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3225:          lli= log(survp); 
                   3226:        } 
                   3227:        else if  (s2==-5) { 
                   3228:          for (j=1,survp=0. ; j<=2; j++)  
                   3229:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3230:          lli= log(survp); 
                   3231:        } 
                   3232:        else{
                   3233:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3234:          /*  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 */
                   3235:        } 
                   3236:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3237:        /*if(lli ==000.0)*/
                   3238:        /*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); */
                   3239:        ipmx +=1;
                   3240:        sw += weight[i];
                   3241:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3242:        /* if (lli < log(mytinydouble)){ */
                   3243:        /*   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); */
                   3244:        /*   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]); */
                   3245:        /* } */
                   3246:       } /* end of wave */
                   3247:     } /* end of individual */
                   3248:   }  else if(mle==2){
                   3249:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3250:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3251:       for(mi=1; mi<= wav[i]-1; mi++){
                   3252:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3253:          for (j=1;j<=nlstate+ndeath;j++){
                   3254:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3255:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3256:          }
                   3257:        for(d=0; d<=dh[mi][i]; d++){
                   3258:          newm=savm;
                   3259:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3260:          cov[2]=agexact;
                   3261:          if(nagesqr==1)
                   3262:            cov[3]= agexact*agexact;
                   3263:          for (kk=1; kk<=cptcovage;kk++) {
                   3264:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3265:          }
                   3266:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3267:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3268:          savm=oldm;
                   3269:          oldm=newm;
                   3270:        } /* end mult */
                   3271:       
                   3272:        s1=s[mw[mi][i]][i];
                   3273:        s2=s[mw[mi+1][i]][i];
                   3274:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3275:        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 */
                   3276:        ipmx +=1;
                   3277:        sw += weight[i];
                   3278:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3279:       } /* end of wave */
                   3280:     } /* end of individual */
                   3281:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3282:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3283:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3284:       for(mi=1; mi<= wav[i]-1; mi++){
                   3285:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3286:          for (j=1;j<=nlstate+ndeath;j++){
                   3287:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3288:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3289:          }
                   3290:        for(d=0; d<dh[mi][i]; d++){
                   3291:          newm=savm;
                   3292:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3293:          cov[2]=agexact;
                   3294:          if(nagesqr==1)
                   3295:            cov[3]= agexact*agexact;
                   3296:          for (kk=1; kk<=cptcovage;kk++) {
                   3297:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3298:          }
                   3299:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3300:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3301:          savm=oldm;
                   3302:          oldm=newm;
                   3303:        } /* end mult */
                   3304:       
                   3305:        s1=s[mw[mi][i]][i];
                   3306:        s2=s[mw[mi+1][i]][i];
                   3307:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3308:        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 */
                   3309:        ipmx +=1;
                   3310:        sw += weight[i];
                   3311:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3312:       } /* end of wave */
                   3313:     } /* end of individual */
                   3314:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3315:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3316:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3317:       for(mi=1; mi<= wav[i]-1; mi++){
                   3318:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3319:          for (j=1;j<=nlstate+ndeath;j++){
                   3320:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3321:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3322:          }
                   3323:        for(d=0; d<dh[mi][i]; d++){
                   3324:          newm=savm;
                   3325:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3326:          cov[2]=agexact;
                   3327:          if(nagesqr==1)
                   3328:            cov[3]= agexact*agexact;
                   3329:          for (kk=1; kk<=cptcovage;kk++) {
                   3330:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3331:          }
1.126     brouard  3332:        
1.226     brouard  3333:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3334:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3335:          savm=oldm;
                   3336:          oldm=newm;
                   3337:        } /* end mult */
                   3338:       
                   3339:        s1=s[mw[mi][i]][i];
                   3340:        s2=s[mw[mi+1][i]][i];
                   3341:        if( s2 > nlstate){ 
                   3342:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3343:        } else if  ( s2==-1 ) { /* alive */
                   3344:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3345:            survp += out[s1][j];
                   3346:          lli= log(survp);
                   3347:        }else{
                   3348:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3349:        }
                   3350:        ipmx +=1;
                   3351:        sw += weight[i];
                   3352:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3353: /*     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.226     brouard  3354:       } /* end of wave */
                   3355:     } /* end of individual */
                   3356:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3357:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3358:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3359:       for(mi=1; mi<= wav[i]-1; mi++){
                   3360:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3361:          for (j=1;j<=nlstate+ndeath;j++){
                   3362:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3363:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3364:          }
                   3365:        for(d=0; d<dh[mi][i]; d++){
                   3366:          newm=savm;
                   3367:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3368:          cov[2]=agexact;
                   3369:          if(nagesqr==1)
                   3370:            cov[3]= agexact*agexact;
                   3371:          for (kk=1; kk<=cptcovage;kk++) {
                   3372:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3373:          }
1.126     brouard  3374:        
1.226     brouard  3375:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3376:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3377:          savm=oldm;
                   3378:          oldm=newm;
                   3379:        } /* end mult */
                   3380:       
                   3381:        s1=s[mw[mi][i]][i];
                   3382:        s2=s[mw[mi+1][i]][i];
                   3383:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3384:        ipmx +=1;
                   3385:        sw += weight[i];
                   3386:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3387:        /*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]);*/
                   3388:       } /* end of wave */
                   3389:     } /* end of individual */
                   3390:   } /* End of if */
                   3391:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3392:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3393:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3394:   return -l;
1.126     brouard  3395: }
                   3396: 
                   3397: /*************** log-likelihood *************/
                   3398: double funcone( double *x)
                   3399: {
1.228     brouard  3400:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3401:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3402:   int ioffset=0;
1.131     brouard  3403:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3404:   double **out;
                   3405:   double lli; /* Individual log likelihood */
                   3406:   double llt;
                   3407:   int s1, s2;
1.228     brouard  3408:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3409: 
1.126     brouard  3410:   double bbh, survp;
1.187     brouard  3411:   double agexact;
1.214     brouard  3412:   double agebegin, ageend;
1.126     brouard  3413:   /*extern weight */
                   3414:   /* We are differentiating ll according to initial status */
                   3415:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3416:   /*for(i=1;i<imx;i++) 
                   3417:     printf(" %d\n",s[4][i]);
                   3418:   */
                   3419:   cov[1]=1.;
                   3420: 
                   3421:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3422:   ioffset=0;
                   3423:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.225     brouard  3424:     ioffset=2+nagesqr+cptcovage;
1.232     brouard  3425:     /* Fixed */
1.224     brouard  3426:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3427:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3428:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3429:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   3430: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3431: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3432: /*    cov[2+6]=covar[2][i]; V2  */
                   3433: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3434: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3435: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3436: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3437: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3438: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3439:     }
1.232     brouard  3440:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3441:     /*   cov[++ioffset]=coqvar[TvarFQ[k]][i];/\* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V2 and V1*V2 is fixed (k=6 and 7?)*\/ */
                   3442:     /* } */
1.231     brouard  3443:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3444:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3445:     /* } */
1.225     brouard  3446:     
1.233     brouard  3447: 
                   3448:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3449:     /* Wave varying (but not age varying) */
                   3450:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.233     brouard  3451:                                cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
1.232     brouard  3452:                        }
                   3453:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.231     brouard  3454:                                /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3455:                                /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
1.232     brouard  3456:                                /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3457:                                /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
1.231     brouard  3458:                                /* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
1.232     brouard  3459:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3460:                        /*      iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3461:                        /*      /\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
                   3462:                        /*      cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3463:       /* } */
1.126     brouard  3464:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.231     brouard  3465:                                for (j=1;j<=nlstate+ndeath;j++){
                   3466:                                        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3467:                                        savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3468:                                }
1.214     brouard  3469:       
                   3470:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3471:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3472:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.231     brouard  3473:                                /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3474:                                        and mw[mi+1][i]. dh depends on stepm.*/
                   3475:                                newm=savm;
                   3476:                                agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3477:                                cov[2]=agexact;
                   3478:                                if(nagesqr==1)
                   3479:                                        cov[3]= agexact*agexact;
                   3480:                                for (kk=1; kk<=cptcovage;kk++) {
                   3481:                                        cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3482:                                }
                   3483:                                /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3484:                                /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3485:                                out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3486:                                                                                 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3487:                                /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3488:                                /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3489:                                savm=oldm;
                   3490:                                oldm=newm;
1.126     brouard  3491:       } /* end mult */
                   3492:       
                   3493:       s1=s[mw[mi][i]][i];
                   3494:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3495:       /* if(s2==-1){ */
                   3496:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3497:       /*       /\* exit(1); *\/ */
                   3498:       /* } */
1.126     brouard  3499:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3500:       /* bias is positive if real duration
                   3501:        * is higher than the multiple of stepm and negative otherwise.
                   3502:        */
                   3503:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.232     brouard  3504:                                lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3505:       } else if  ( s2==-1 ) { /* alive */
1.232     brouard  3506:                                for (j=1,survp=0. ; j<=nlstate; j++) 
                   3507:                                        survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3508:                                lli= log(survp);
1.126     brouard  3509:       }else if (mle==1){
1.232     brouard  3510:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3511:       } else if(mle==2){
1.232     brouard  3512:                                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 */
1.126     brouard  3513:       } else if(mle==3){  /* exponential inter-extrapolation */
1.232     brouard  3514:                                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 */
1.126     brouard  3515:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.232     brouard  3516:                                lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3517:       } else{  /* mle=0 back to 1 */
1.232     brouard  3518:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3519:                                /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3520:       } /* End of if */
                   3521:       ipmx +=1;
                   3522:       sw += weight[i];
                   3523:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3524:       /*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  3525:       if(globpr){
1.232     brouard  3526:                                fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3527:  %11.6f %11.6f %11.6f ", \
1.232     brouard  3528:                                                                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3529:                                                                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3530:                                for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3531:                                        llt +=ll[k]*gipmx/gsw;
                   3532:                                        fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3533:                                }
                   3534:                                fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3535:       }
1.232     brouard  3536:        } /* end of wave */
                   3537: } /* end of individual */
                   3538: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3539: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3540: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3541: if(globpr==0){ /* First time we count the contributions and weights */
                   3542:        gipmx=ipmx;
                   3543:        gsw=sw;
                   3544: }
                   3545: return -l;
1.126     brouard  3546: }
                   3547: 
                   3548: 
                   3549: /*************** function likelione ***********/
                   3550: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3551: {
                   3552:   /* This routine should help understanding what is done with 
                   3553:      the selection of individuals/waves and
                   3554:      to check the exact contribution to the likelihood.
                   3555:      Plotting could be done.
                   3556:    */
                   3557:   int k;
                   3558: 
                   3559:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3560:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3561:     strcat(fileresilk,fileresu);
1.126     brouard  3562:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3563:       printf("Problem with resultfile: %s\n", fileresilk);
                   3564:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3565:     }
1.214     brouard  3566:     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");
                   3567:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3568:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3569:     for(k=1; k<=nlstate; k++) 
                   3570:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3571:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3572:   }
                   3573: 
                   3574:   *fretone=(*funcone)(p);
                   3575:   if(*globpri !=0){
                   3576:     fclose(ficresilk);
1.205     brouard  3577:     if (mle ==0)
                   3578:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3579:     else if(mle >=1)
                   3580:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3581:     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  3582:     
1.208     brouard  3583:       
                   3584:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3585:       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  3586: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3587:     }
1.207     brouard  3588:     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  3589: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3590:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3591: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3592:     fflush(fichtm);
1.205     brouard  3593:   }
1.126     brouard  3594:   return;
                   3595: }
                   3596: 
                   3597: 
                   3598: /*********** Maximum Likelihood Estimation ***************/
                   3599: 
                   3600: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3601: {
1.165     brouard  3602:   int i,j, iter=0;
1.126     brouard  3603:   double **xi;
                   3604:   double fret;
                   3605:   double fretone; /* Only one call to likelihood */
                   3606:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3607: 
                   3608: #ifdef NLOPT
                   3609:   int creturn;
                   3610:   nlopt_opt opt;
                   3611:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3612:   double *lb;
                   3613:   double minf; /* the minimum objective value, upon return */
                   3614:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3615:   myfunc_data dinst, *d = &dinst;
                   3616: #endif
                   3617: 
                   3618: 
1.126     brouard  3619:   xi=matrix(1,npar,1,npar);
                   3620:   for (i=1;i<=npar;i++)
                   3621:     for (j=1;j<=npar;j++)
                   3622:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3623:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3624:   strcpy(filerespow,"POW_"); 
1.126     brouard  3625:   strcat(filerespow,fileres);
                   3626:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3627:     printf("Problem with resultfile: %s\n", filerespow);
                   3628:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3629:   }
                   3630:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3631:   for (i=1;i<=nlstate;i++)
                   3632:     for(j=1;j<=nlstate+ndeath;j++)
                   3633:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3634:   fprintf(ficrespow,"\n");
1.162     brouard  3635: #ifdef POWELL
1.126     brouard  3636:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3637: #endif
1.126     brouard  3638: 
1.162     brouard  3639: #ifdef NLOPT
                   3640: #ifdef NEWUOA
                   3641:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3642: #else
                   3643:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3644: #endif
                   3645:   lb=vector(0,npar-1);
                   3646:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3647:   nlopt_set_lower_bounds(opt, lb);
                   3648:   nlopt_set_initial_step1(opt, 0.1);
                   3649:   
                   3650:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3651:   d->function = func;
                   3652:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3653:   nlopt_set_min_objective(opt, myfunc, d);
                   3654:   nlopt_set_xtol_rel(opt, ftol);
                   3655:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3656:     printf("nlopt failed! %d\n",creturn); 
                   3657:   }
                   3658:   else {
                   3659:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3660:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3661:     iter=1; /* not equal */
                   3662:   }
                   3663:   nlopt_destroy(opt);
                   3664: #endif
1.126     brouard  3665:   free_matrix(xi,1,npar,1,npar);
                   3666:   fclose(ficrespow);
1.203     brouard  3667:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3668:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3669:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3670: 
                   3671: }
                   3672: 
                   3673: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3674: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3675: {
                   3676:   double  **a,**y,*x,pd;
1.203     brouard  3677:   /* double **hess; */
1.164     brouard  3678:   int i, j;
1.126     brouard  3679:   int *indx;
                   3680: 
                   3681:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3682:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3683:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3684:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3685:   double gompertz(double p[]);
1.203     brouard  3686:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3687: 
                   3688:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3689:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3690:   for (i=1;i<=npar;i++){
1.203     brouard  3691:     printf("%d-",i);fflush(stdout);
                   3692:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3693:    
                   3694:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3695:     
                   3696:     /*  printf(" %f ",p[i]);
                   3697:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3698:   }
                   3699:   
                   3700:   for (i=1;i<=npar;i++) {
                   3701:     for (j=1;j<=npar;j++)  {
                   3702:       if (j>i) { 
1.203     brouard  3703:        printf(".%d-%d",i,j);fflush(stdout);
                   3704:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3705:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3706:        
                   3707:        hess[j][i]=hess[i][j];    
                   3708:        /*printf(" %lf ",hess[i][j]);*/
                   3709:       }
                   3710:     }
                   3711:   }
                   3712:   printf("\n");
                   3713:   fprintf(ficlog,"\n");
                   3714: 
                   3715:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3716:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3717:   
                   3718:   a=matrix(1,npar,1,npar);
                   3719:   y=matrix(1,npar,1,npar);
                   3720:   x=vector(1,npar);
                   3721:   indx=ivector(1,npar);
                   3722:   for (i=1;i<=npar;i++)
                   3723:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3724:   ludcmp(a,npar,indx,&pd);
                   3725: 
                   3726:   for (j=1;j<=npar;j++) {
                   3727:     for (i=1;i<=npar;i++) x[i]=0;
                   3728:     x[j]=1;
                   3729:     lubksb(a,npar,indx,x);
                   3730:     for (i=1;i<=npar;i++){ 
                   3731:       matcov[i][j]=x[i];
                   3732:     }
                   3733:   }
                   3734: 
                   3735:   printf("\n#Hessian matrix#\n");
                   3736:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3737:   for (i=1;i<=npar;i++) { 
                   3738:     for (j=1;j<=npar;j++) { 
1.203     brouard  3739:       printf("%.6e ",hess[i][j]);
                   3740:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3741:     }
                   3742:     printf("\n");
                   3743:     fprintf(ficlog,"\n");
                   3744:   }
                   3745: 
1.203     brouard  3746:   /* printf("\n#Covariance matrix#\n"); */
                   3747:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3748:   /* for (i=1;i<=npar;i++) {  */
                   3749:   /*   for (j=1;j<=npar;j++) {  */
                   3750:   /*     printf("%.6e ",matcov[i][j]); */
                   3751:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3752:   /*   } */
                   3753:   /*   printf("\n"); */
                   3754:   /*   fprintf(ficlog,"\n"); */
                   3755:   /* } */
                   3756: 
1.126     brouard  3757:   /* Recompute Inverse */
1.203     brouard  3758:   /* for (i=1;i<=npar;i++) */
                   3759:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3760:   /* ludcmp(a,npar,indx,&pd); */
                   3761: 
                   3762:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3763: 
                   3764:   /* for (j=1;j<=npar;j++) { */
                   3765:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3766:   /*   x[j]=1; */
                   3767:   /*   lubksb(a,npar,indx,x); */
                   3768:   /*   for (i=1;i<=npar;i++){  */
                   3769:   /*     y[i][j]=x[i]; */
                   3770:   /*     printf("%.3e ",y[i][j]); */
                   3771:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3772:   /*   } */
                   3773:   /*   printf("\n"); */
                   3774:   /*   fprintf(ficlog,"\n"); */
                   3775:   /* } */
                   3776: 
                   3777:   /* Verifying the inverse matrix */
                   3778: #ifdef DEBUGHESS
                   3779:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3780: 
1.203     brouard  3781:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3782:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3783: 
                   3784:   for (j=1;j<=npar;j++) {
                   3785:     for (i=1;i<=npar;i++){ 
1.203     brouard  3786:       printf("%.2f ",y[i][j]);
                   3787:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3788:     }
                   3789:     printf("\n");
                   3790:     fprintf(ficlog,"\n");
                   3791:   }
1.203     brouard  3792: #endif
1.126     brouard  3793: 
                   3794:   free_matrix(a,1,npar,1,npar);
                   3795:   free_matrix(y,1,npar,1,npar);
                   3796:   free_vector(x,1,npar);
                   3797:   free_ivector(indx,1,npar);
1.203     brouard  3798:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3799: 
                   3800: 
                   3801: }
                   3802: 
                   3803: /*************** hessian matrix ****************/
                   3804: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3805: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3806:   int i;
                   3807:   int l=1, lmax=20;
1.203     brouard  3808:   double k1,k2, res, fx;
1.132     brouard  3809:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3810:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3811:   int k=0,kmax=10;
                   3812:   double l1;
                   3813: 
                   3814:   fx=func(x);
                   3815:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3816:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3817:     l1=pow(10,l);
                   3818:     delts=delt;
                   3819:     for(k=1 ; k <kmax; k=k+1){
                   3820:       delt = delta*(l1*k);
                   3821:       p2[theta]=x[theta] +delt;
1.145     brouard  3822:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3823:       p2[theta]=x[theta]-delt;
                   3824:       k2=func(p2)-fx;
                   3825:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3826:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3827:       
1.203     brouard  3828: #ifdef DEBUGHESSII
1.126     brouard  3829:       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);
                   3830:       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);
                   3831: #endif
                   3832:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3833:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3834:        k=kmax;
                   3835:       }
                   3836:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3837:        k=kmax; l=lmax*10;
1.126     brouard  3838:       }
                   3839:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3840:        delts=delt;
                   3841:       }
1.203     brouard  3842:     } /* End loop k */
1.126     brouard  3843:   }
                   3844:   delti[theta]=delts;
                   3845:   return res; 
                   3846:   
                   3847: }
                   3848: 
1.203     brouard  3849: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3850: {
                   3851:   int i;
1.164     brouard  3852:   int l=1, lmax=20;
1.126     brouard  3853:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3854:   double p2[MAXPARM+1];
1.203     brouard  3855:   int k, kmax=1;
                   3856:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3857: 
                   3858:   int firstime=0;
1.203     brouard  3859:   
1.126     brouard  3860:   fx=func(x);
1.203     brouard  3861:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3862:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3863:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3864:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3865:     k1=func(p2)-fx;
                   3866:   
1.203     brouard  3867:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3868:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3869:     k2=func(p2)-fx;
                   3870:   
1.203     brouard  3871:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3872:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3873:     k3=func(p2)-fx;
                   3874:   
1.203     brouard  3875:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3876:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3877:     k4=func(p2)-fx;
1.203     brouard  3878:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3879:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3880:       firstime=1;
1.203     brouard  3881:       kmax=kmax+10;
1.208     brouard  3882:     }
                   3883:     if(kmax >=10 || firstime ==1){
1.218     brouard  3884:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3885:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  3886:       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);
                   3887:       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);
                   3888:     }
                   3889: #ifdef DEBUGHESSIJ
                   3890:     v1=hess[thetai][thetai];
                   3891:     v2=hess[thetaj][thetaj];
                   3892:     cv12=res;
                   3893:     /* Computing eigen value of Hessian matrix */
                   3894:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3895:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3896:     if ((lc2 <0) || (lc1 <0) ){
                   3897:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3898:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3899:       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);
                   3900:       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);
                   3901:     }
1.126     brouard  3902: #endif
                   3903:   }
                   3904:   return res;
                   3905: }
                   3906: 
1.203     brouard  3907:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3908: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3909: /* { */
                   3910: /*   int i; */
                   3911: /*   int l=1, lmax=20; */
                   3912: /*   double k1,k2,k3,k4,res,fx; */
                   3913: /*   double p2[MAXPARM+1]; */
                   3914: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3915: /*   int k=0,kmax=10; */
                   3916: /*   double l1; */
                   3917:   
                   3918: /*   fx=func(x); */
                   3919: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3920: /*     l1=pow(10,l); */
                   3921: /*     delts=delt; */
                   3922: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3923: /*       delt = delti*(l1*k); */
                   3924: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3925: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3926: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3927: /*       k1=func(p2)-fx; */
                   3928:       
                   3929: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3930: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3931: /*       k2=func(p2)-fx; */
                   3932:       
                   3933: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3934: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3935: /*       k3=func(p2)-fx; */
                   3936:       
                   3937: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3938: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3939: /*       k4=func(p2)-fx; */
                   3940: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3941: /* #ifdef DEBUGHESSIJ */
                   3942: /*       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); */
                   3943: /*       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); */
                   3944: /* #endif */
                   3945: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3946: /*     k=kmax; */
                   3947: /*       } */
                   3948: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3949: /*     k=kmax; l=lmax*10; */
                   3950: /*       } */
                   3951: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3952: /*     delts=delt; */
                   3953: /*       } */
                   3954: /*     } /\* End loop k *\/ */
                   3955: /*   } */
                   3956: /*   delti[theta]=delts; */
                   3957: /*   return res;  */
                   3958: /* } */
                   3959: 
                   3960: 
1.126     brouard  3961: /************** Inverse of matrix **************/
                   3962: void ludcmp(double **a, int n, int *indx, double *d) 
                   3963: { 
                   3964:   int i,imax,j,k; 
                   3965:   double big,dum,sum,temp; 
                   3966:   double *vv; 
                   3967:  
                   3968:   vv=vector(1,n); 
                   3969:   *d=1.0; 
                   3970:   for (i=1;i<=n;i++) { 
                   3971:     big=0.0; 
                   3972:     for (j=1;j<=n;j++) 
                   3973:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3974:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3975:     vv[i]=1.0/big; 
                   3976:   } 
                   3977:   for (j=1;j<=n;j++) { 
                   3978:     for (i=1;i<j;i++) { 
                   3979:       sum=a[i][j]; 
                   3980:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3981:       a[i][j]=sum; 
                   3982:     } 
                   3983:     big=0.0; 
                   3984:     for (i=j;i<=n;i++) { 
                   3985:       sum=a[i][j]; 
                   3986:       for (k=1;k<j;k++) 
                   3987:        sum -= a[i][k]*a[k][j]; 
                   3988:       a[i][j]=sum; 
                   3989:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3990:        big=dum; 
                   3991:        imax=i; 
                   3992:       } 
                   3993:     } 
                   3994:     if (j != imax) { 
                   3995:       for (k=1;k<=n;k++) { 
                   3996:        dum=a[imax][k]; 
                   3997:        a[imax][k]=a[j][k]; 
                   3998:        a[j][k]=dum; 
                   3999:       } 
                   4000:       *d = -(*d); 
                   4001:       vv[imax]=vv[j]; 
                   4002:     } 
                   4003:     indx[j]=imax; 
                   4004:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4005:     if (j != n) { 
                   4006:       dum=1.0/(a[j][j]); 
                   4007:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4008:     } 
                   4009:   } 
                   4010:   free_vector(vv,1,n);  /* Doesn't work */
                   4011: ;
                   4012: } 
                   4013: 
                   4014: void lubksb(double **a, int n, int *indx, double b[]) 
                   4015: { 
                   4016:   int i,ii=0,ip,j; 
                   4017:   double sum; 
                   4018:  
                   4019:   for (i=1;i<=n;i++) { 
                   4020:     ip=indx[i]; 
                   4021:     sum=b[ip]; 
                   4022:     b[ip]=b[i]; 
                   4023:     if (ii) 
                   4024:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4025:     else if (sum) ii=i; 
                   4026:     b[i]=sum; 
                   4027:   } 
                   4028:   for (i=n;i>=1;i--) { 
                   4029:     sum=b[i]; 
                   4030:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4031:     b[i]=sum/a[i][i]; 
                   4032:   } 
                   4033: } 
                   4034: 
                   4035: void pstamp(FILE *fichier)
                   4036: {
1.196     brouard  4037:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4038: }
                   4039: 
                   4040: /************ Frequencies ********************/
1.226     brouard  4041: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4042:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4043:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4044: {  /* Some frequencies */
                   4045:   
1.227     brouard  4046:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4047:   int iind=0, iage=0;
                   4048:   int mi; /* Effective wave */
                   4049:   int first;
                   4050:   double ***freq; /* Frequencies */
                   4051:   double *meanq;
                   4052:   double **meanqt;
                   4053:   double *pp, **prop, *posprop, *pospropt;
                   4054:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4055:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4056:   double agebegin, ageend;
                   4057:     
                   4058:   pp=vector(1,nlstate);
                   4059:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4060:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4061:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4062:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4063:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4064:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4065:   strcpy(fileresp,"P_");
                   4066:   strcat(fileresp,fileresu);
                   4067:   /*strcat(fileresphtm,fileresu);*/
                   4068:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4069:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4070:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4071:     exit(0);
                   4072:   }
1.214     brouard  4073: 
1.226     brouard  4074:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4075:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4076:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4077:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4078:     fflush(ficlog);
                   4079:     exit(70); 
                   4080:   }
                   4081:   else{
                   4082:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  4083: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   4084: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4085:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4086:   }
                   4087:   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);
1.214     brouard  4088:     
1.226     brouard  4089:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4090:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4091:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4092:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4093:     fflush(ficlog);
                   4094:     exit(70); 
                   4095:   }
                   4096:   else{
                   4097:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  4098: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   4099: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4100:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4101:   }
                   4102:   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);
1.214     brouard  4103: 
1.226     brouard  4104:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4105:   j1=0;
1.126     brouard  4106:   
1.227     brouard  4107:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4108:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4109:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.220     brouard  4110: 
1.226     brouard  4111:   first=1;
1.220     brouard  4112: 
1.226     brouard  4113:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4114:      reference=low_education V1=0,V2=0
                   4115:      med_educ                V1=1 V2=0, 
                   4116:      high_educ               V1=0 V2=1
                   4117:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4118:   */
1.126     brouard  4119: 
1.227     brouard  4120:   for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
1.226     brouard  4121:     posproptt=0.;
                   4122:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4123:       scanf("%d", i);*/
                   4124:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4125:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.231     brouard  4126:                                for(m=iagemin; m <= iagemax+3; m++)
                   4127:                                        freq[i][jk][m]=0;
                   4128:                
1.226     brouard  4129:     for (i=1; i<=nlstate; i++)  {
                   4130:       for(m=iagemin; m <= iagemax+3; m++)
1.231     brouard  4131:                                prop[i][m]=0;
1.226     brouard  4132:       posprop[i]=0;
                   4133:       pospropt[i]=0;
                   4134:     }
1.227     brouard  4135:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4136:     /*   meanq[z1]+=0.; */
                   4137:     /*   for(m=1;m<=lastpass;m++){ */
                   4138:     /*         meanqt[m][z1]=0.; */
                   4139:     /*   } */
                   4140:     /* } */
1.231     brouard  4141:                
1.226     brouard  4142:     dateintsum=0;
                   4143:     k2cpt=0;
1.227     brouard  4144:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4145:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4146:       bool=1;
1.227     brouard  4147:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4148:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4149:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4150:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4151:          /* } */
1.234     brouard  4152:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4153:            /* if(Tvaraff[z1] ==-20){ */
                   4154:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4155:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4156:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4157:            /* }else  */
                   4158:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4159:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4160:              bool=0;
                   4161:              /* 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", 
                   4162:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4163:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4164:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4165:            } /* Onlyf fixed */
                   4166:          } /* end z1 */
                   4167:        } /* cptcovn > 0 */
1.227     brouard  4168:       } /* end any */
                   4169:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4170:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4171:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4172:          m=mw[mi][iind];
                   4173:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4174:            for (z1=1; z1<=cptcoveff; z1++) {
                   4175:              if( Fixed[Tmodelind[z1]]==1){
                   4176:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4177:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4178:                  bool=0;
                   4179:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4180:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4181:                  bool=0;
                   4182:                }
                   4183:              }
                   4184:            }
                   4185:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4186:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4187:          if(bool==1){
                   4188:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4189:               and mw[mi+1][iind]. dh depends on stepm. */
                   4190:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4191:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4192:            if(m >=firstpass && m <=lastpass){
                   4193:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4194:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4195:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4196:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4197:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4198:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4199:              if (m<lastpass) {
                   4200:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4201:                /*   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
                   4202:                if(s[m][iind]==-1)
                   4203:                  printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
                   4204:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4205:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4206:                freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
                   4207:              }
                   4208:            } /* end if between passes */  
                   4209:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4210:              dateintsum=dateintsum+k2;
                   4211:              k2cpt++;
                   4212:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4213:            }
                   4214:          } /* end bool 2 */
                   4215:        } /* end m */
1.226     brouard  4216:       } /* end bool */
                   4217:     } /* end iind = 1 to imx */
                   4218:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4219:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.231     brouard  4220:                
                   4221:                
1.226     brouard  4222:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4223:     pstamp(ficresp);
1.227     brouard  4224:     /* if  (ncoveff>0) { */
                   4225:     if  (cptcoveff>0) {
1.226     brouard  4226:       fprintf(ficresp, "\n#********** Variable "); 
                   4227:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4228:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.227     brouard  4229:       for (z1=1; z1<=cptcoveff; z1++){
1.234     brouard  4230:        fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4231:        fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4232:        fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.226     brouard  4233:       }
                   4234:       fprintf(ficresp, "**********\n#");
                   4235:       fprintf(ficresphtm, "**********</h3>\n");
                   4236:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4237:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4238:       for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.226     brouard  4239:       fprintf(ficlog, "**********\n");
                   4240:     }
                   4241:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4242:     for(i=1; i<=nlstate;i++) {
                   4243:       fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   4244:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4245:     }
                   4246:     fprintf(ficresp, "\n");
                   4247:     fprintf(ficresphtm, "\n");
1.231     brouard  4248:                
1.226     brouard  4249:     /* Header of frequency table by age */
                   4250:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4251:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4252:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4253:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4254:        if(jk!=0 && m!=0)
                   4255:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4256:       }
                   4257:     }
                   4258:     fprintf(ficresphtmfr, "\n");
1.231     brouard  4259:                
1.226     brouard  4260:     /* For each age */
                   4261:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4262:       fprintf(ficresphtm,"<tr>");
                   4263:       if(iage==iagemax+1){
1.231     brouard  4264:                                fprintf(ficlog,"1");
                   4265:                                fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4266:       }else if(iage==iagemax+2){
1.231     brouard  4267:                                fprintf(ficlog,"0");
                   4268:                                fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4269:       }else if(iage==iagemax+3){
1.231     brouard  4270:                                fprintf(ficlog,"Total");
                   4271:                                fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4272:       }else{
1.231     brouard  4273:                                if(first==1){
                   4274:                                        first=0;
                   4275:                                        printf("See log file for details...\n");
                   4276:                                }
                   4277:                                fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4278:                                fprintf(ficlog,"Age %d", iage);
1.226     brouard  4279:       }
                   4280:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4281:                                for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4282:                                        pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4283:       }
                   4284:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4285:                                for(m=-1, pos=0; m <=0 ; m++)
                   4286:                                        pos += freq[jk][m][iage];
                   4287:                                if(pp[jk]>=1.e-10){
                   4288:                                        if(first==1){
                   4289:                                                printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4290:                                        }
                   4291:                                        fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4292:                                }else{
                   4293:                                        if(first==1)
                   4294:                                                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4295:                                        fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4296:                                }
1.226     brouard  4297:       }
1.231     brouard  4298:                        
1.226     brouard  4299:       for(jk=1; jk <=nlstate ; jk++){ 
1.231     brouard  4300:                                /* posprop[jk]=0; */
                   4301:                                for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4302:                                        pp[jk] += freq[jk][m][iage];
1.226     brouard  4303:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.231     brouard  4304:                        
1.226     brouard  4305:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.231     brouard  4306:                                pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4307:                                posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4308:                                                                                                                                                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4309:                                pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4310:                                                                                                                                                                from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4311:       }
                   4312:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4313:                                if(pos>=1.e-5){
                   4314:                                        if(first==1)
                   4315:                                                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4316:                                        fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4317:                                }else{
                   4318:                                        if(first==1)
                   4319:                                                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4320:                                        fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4321:                                }
                   4322:                                if( iage <= iagemax){
                   4323:                                        if(pos>=1.e-5){
                   4324:                                                fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4325:                                                fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4326:                                                /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4327:                                                /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4328:                                        }
                   4329:                                        else{
                   4330:                                                fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4331:                                                fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4332:                                        }
                   4333:                                }
                   4334:                                pospropt[jk] +=posprop[jk];
1.226     brouard  4335:       } /* end loop jk */
                   4336:       /* pospropt=0.; */
                   4337:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.231     brouard  4338:                                for(m=-1; m <=nlstate+ndeath; m++){
                   4339:                                        if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4340:                                                if(first==1){
                   4341:                                                        printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4342:                                                }
                   4343:                                                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4344:                                        }
                   4345:                                        if(jk!=0 && m!=0)
                   4346:                                                fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4347:                                }
1.226     brouard  4348:       } /* end loop jk */
                   4349:       posproptt=0.; 
                   4350:       for(jk=1; jk <=nlstate; jk++){
1.231     brouard  4351:                                posproptt += pospropt[jk];
1.226     brouard  4352:       }
                   4353:       fprintf(ficresphtmfr,"</tr>\n ");
                   4354:       if(iage <= iagemax){
1.231     brouard  4355:                                fprintf(ficresp,"\n");
                   4356:                                fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4357:       }
                   4358:       if(first==1)
1.231     brouard  4359:                                printf("Others in log...\n");
1.226     brouard  4360:       fprintf(ficlog,"\n");
                   4361:     } /* end loop age iage */
                   4362:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4363:     for(jk=1; jk <=nlstate ; jk++){
                   4364:       if(posproptt < 1.e-5){
1.231     brouard  4365:                                fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4366:       }else{
1.231     brouard  4367:                                fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4368:       }
                   4369:     }
                   4370:     fprintf(ficresphtm,"</tr>\n");
                   4371:     fprintf(ficresphtm,"</table>\n");
                   4372:     fprintf(ficresphtmfr,"</table>\n");
                   4373:     if(posproptt < 1.e-5){
                   4374:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4375:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4376:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4377:       invalidvarcomb[j1]=1;
                   4378:     }else{
                   4379:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4380:       invalidvarcomb[j1]=0;
                   4381:     }
                   4382:     fprintf(ficresphtmfr,"</table>\n");
                   4383:   } /* end selected combination of covariate j1 */
                   4384:   dateintmean=dateintsum/k2cpt; 
1.231     brouard  4385:        
1.226     brouard  4386:   fclose(ficresp);
                   4387:   fclose(ficresphtm);
                   4388:   fclose(ficresphtmfr);
                   4389:   free_vector(meanq,1,nqfveff);
                   4390:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4391:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4392:   free_vector(pospropt,1,nlstate);
                   4393:   free_vector(posprop,1,nlstate);
                   4394:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4395:   free_vector(pp,1,nlstate);
                   4396:   /* End of freqsummary */
                   4397: }
1.126     brouard  4398: 
                   4399: /************ Prevalence ********************/
1.227     brouard  4400: 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)
                   4401: {  
                   4402:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4403:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4404:      We still use firstpass and lastpass as another selection.
                   4405:   */
1.126     brouard  4406:  
1.227     brouard  4407:   int i, m, jk, j1, bool, z1,j, iv;
                   4408:   int mi; /* Effective wave */
                   4409:   int iage;
                   4410:   double agebegin, ageend;
                   4411: 
                   4412:   double **prop;
                   4413:   double posprop; 
                   4414:   double  y2; /* in fractional years */
                   4415:   int iagemin, iagemax;
                   4416:   int first; /** to stop verbosity which is redirected to log file */
                   4417: 
                   4418:   iagemin= (int) agemin;
                   4419:   iagemax= (int) agemax;
                   4420:   /*pp=vector(1,nlstate);*/
                   4421:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4422:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4423:   j1=0;
1.222     brouard  4424:   
1.227     brouard  4425:   /*j=cptcoveff;*/
                   4426:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4427:   
1.227     brouard  4428:   first=1;
                   4429:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4430:     for (i=1; i<=nlstate; i++)  
                   4431:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4432:        prop[i][iage]=0.0;
                   4433:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4434:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4435:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4436:     
                   4437:     for (i=1; i<=imx; i++) { /* Each individual */
                   4438:       bool=1;
                   4439:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4440:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4441:        m=mw[mi][i];
                   4442:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4443:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4444:        for (z1=1; z1<=cptcoveff; z1++){
                   4445:          if( Fixed[Tmodelind[z1]]==1){
                   4446:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4447:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4448:              bool=0;
                   4449:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4450:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4451:              bool=0;
                   4452:            }
                   4453:        }
                   4454:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4455:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4456:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4457:          if(m >=firstpass && m <=lastpass){
                   4458:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4459:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4460:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4461:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4462:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4463:                printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
                   4464:                exit(1);
                   4465:              }
                   4466:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4467:                /*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]]);*/
                   4468:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4469:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4470:              } /* end valid statuses */ 
                   4471:            } /* end selection of dates */
                   4472:          } /* end selection of waves */
                   4473:        } /* end bool */
                   4474:       } /* end wave */
                   4475:     } /* end individual */
                   4476:     for(i=iagemin; i <= iagemax+3; i++){  
                   4477:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4478:        posprop += prop[jk][i]; 
                   4479:       } 
                   4480:       
                   4481:       for(jk=1; jk <=nlstate ; jk++){      
                   4482:        if( i <=  iagemax){ 
                   4483:          if(posprop>=1.e-5){ 
                   4484:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4485:          } else{
                   4486:            if(first==1){
                   4487:              first=0;
                   4488:              printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,j1,probs[i][jk][j1]);
                   4489:            }
                   4490:          }
                   4491:        } 
                   4492:       }/* end jk */ 
                   4493:     }/* end i */ 
1.222     brouard  4494:      /*} *//* end i1 */
1.227     brouard  4495:   } /* end j1 */
1.222     brouard  4496:   
1.227     brouard  4497:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4498:   /*free_vector(pp,1,nlstate);*/
                   4499:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4500: }  /* End of prevalence */
1.126     brouard  4501: 
                   4502: /************* Waves Concatenation ***************/
                   4503: 
                   4504: 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)
                   4505: {
                   4506:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4507:      Death is a valid wave (if date is known).
                   4508:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4509:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4510:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4511:   */
1.126     brouard  4512: 
1.224     brouard  4513:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4514:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4515:      double sum=0., jmean=0.;*/
1.224     brouard  4516:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4517:   int j, k=0,jk, ju, jl;
                   4518:   double sum=0.;
                   4519:   first=0;
1.214     brouard  4520:   firstwo=0;
1.217     brouard  4521:   firsthree=0;
1.218     brouard  4522:   firstfour=0;
1.164     brouard  4523:   jmin=100000;
1.126     brouard  4524:   jmax=-1;
                   4525:   jmean=0.;
1.224     brouard  4526: 
                   4527: /* Treating live states */
1.214     brouard  4528:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4529:     mi=0;  /* First valid wave */
1.227     brouard  4530:     mli=0; /* Last valid wave */
1.126     brouard  4531:     m=firstpass;
1.214     brouard  4532:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4533:       if(m >firstpass && s[m][i]==s[m-1][i] && mint[m][i]==mint[m-1][i] && anint[m][i]==anint[m-1][i]){/* Two succesive identical information on wave m */
                   4534:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4535:       }else 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 */
                   4536:        mw[++mi][i]=m;
                   4537:        mli=m;
1.224     brouard  4538:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4539:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4540:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4541:       }
1.227     brouard  4542:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4543: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4544:        break;
1.224     brouard  4545: #else
1.227     brouard  4546:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4547:          if(firsthree == 0){
                   4548:            printf("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 as pi. .\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);
                   4549:            firsthree=1;
                   4550:          }
                   4551:          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 as pi. .\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);
                   4552:          mw[++mi][i]=m;
                   4553:          mli=m;
                   4554:        }
                   4555:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4556:          nbwarn++;
                   4557:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4558:            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);
                   4559:            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.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4560:          }
                   4561:          break;
                   4562:        }
                   4563:        break;
1.224     brouard  4564: #endif
1.227     brouard  4565:       }/* End m >= lastpass */
1.126     brouard  4566:     }/* end while */
1.224     brouard  4567: 
1.227     brouard  4568:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
1.216     brouard  4569:     /* After last pass */
1.224     brouard  4570: /* Treating death states */
1.214     brouard  4571:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4572:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4573:       /* } */
1.126     brouard  4574:       mi++;    /* Death is another wave */
                   4575:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4576:       /* Only death is a correct wave */
1.126     brouard  4577:       mw[mi][i]=m;
1.224     brouard  4578:     }
                   4579: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4580:     else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
1.216     brouard  4581:       /* m++; */
                   4582:       /* mi++; */
                   4583:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4584:       /* mw[mi][i]=m; */
1.218     brouard  4585:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4586:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
                   4587:          nbwarn++;
                   4588:          if(firstfiv==0){
                   4589:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing 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], s[m][i], i,m );
                   4590:            firstfiv=1;
                   4591:          }else{
                   4592:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
                   4593:          }
                   4594:        }else{ /* Death occured afer last wave potential bias */
                   4595:          nberr++;
                   4596:          if(firstwo==0){
                   4597:            printf("Error! Death for individual %ld line=%d occurred at %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 );
                   4598:            firstwo=1;
                   4599:          }
                   4600:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4601:        }
1.218     brouard  4602:       }else{ /* end date of interview is known */
1.227     brouard  4603:        /* death is known but not confirmed by death status at any wave */
                   4604:        if(firstfour==0){
                   4605:          printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4606:          firstfour=1;
                   4607:        }
                   4608:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.214     brouard  4609:       }
1.224     brouard  4610:     } /* end if date of death is known */
                   4611: #endif
                   4612:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4613:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4614:     if(mi==0){
                   4615:       nbwarn++;
                   4616:       if(first==0){
1.227     brouard  4617:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4618:        first=1;
1.126     brouard  4619:       }
                   4620:       if(first==1){
1.227     brouard  4621:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4622:       }
                   4623:     } /* end mi==0 */
                   4624:   } /* End individuals */
1.214     brouard  4625:   /* wav and mw are no more changed */
1.223     brouard  4626:        
1.214     brouard  4627:   
1.126     brouard  4628:   for(i=1; i<=imx; i++){
                   4629:     for(mi=1; mi<wav[i];mi++){
                   4630:       if (stepm <=0)
1.227     brouard  4631:        dh[mi][i]=1;
1.126     brouard  4632:       else{
1.227     brouard  4633:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4634:          if (agedc[i] < 2*AGESUP) {
                   4635:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4636:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4637:            else if(j<0){
                   4638:              nberr++;
                   4639:              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]);
                   4640:              j=1; /* Temporary Dangerous patch */
                   4641:              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);
                   4642:              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]);
                   4643:              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);
                   4644:            }
                   4645:            k=k+1;
                   4646:            if (j >= jmax){
                   4647:              jmax=j;
                   4648:              ijmax=i;
                   4649:            }
                   4650:            if (j <= jmin){
                   4651:              jmin=j;
                   4652:              ijmin=i;
                   4653:            }
                   4654:            sum=sum+j;
                   4655:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4656:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4657:          }
                   4658:        }
                   4659:        else{
                   4660:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4661: /*       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]); */
1.223     brouard  4662:                                        
1.227     brouard  4663:          k=k+1;
                   4664:          if (j >= jmax) {
                   4665:            jmax=j;
                   4666:            ijmax=i;
                   4667:          }
                   4668:          else if (j <= jmin){
                   4669:            jmin=j;
                   4670:            ijmin=i;
                   4671:          }
                   4672:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4673:          /*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]);*/
                   4674:          if(j<0){
                   4675:            nberr++;
                   4676:            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]);
                   4677:            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]);
                   4678:          }
                   4679:          sum=sum+j;
                   4680:        }
                   4681:        jk= j/stepm;
                   4682:        jl= j -jk*stepm;
                   4683:        ju= j -(jk+1)*stepm;
                   4684:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4685:          if(jl==0){
                   4686:            dh[mi][i]=jk;
                   4687:            bh[mi][i]=0;
                   4688:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4689:                  * to avoid the price of an extra matrix product in likelihood */
                   4690:            dh[mi][i]=jk+1;
                   4691:            bh[mi][i]=ju;
                   4692:          }
                   4693:        }else{
                   4694:          if(jl <= -ju){
                   4695:            dh[mi][i]=jk;
                   4696:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4697:                                 * is higher than the multiple of stepm and negative otherwise.
                   4698:                                 */
                   4699:          }
                   4700:          else{
                   4701:            dh[mi][i]=jk+1;
                   4702:            bh[mi][i]=ju;
                   4703:          }
                   4704:          if(dh[mi][i]==0){
                   4705:            dh[mi][i]=1; /* At least one step */
                   4706:            bh[mi][i]=ju; /* At least one step */
                   4707:            /*  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);*/
                   4708:          }
                   4709:        } /* end if mle */
1.126     brouard  4710:       }
                   4711:     } /* end wave */
                   4712:   }
                   4713:   jmean=sum/k;
                   4714:   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  4715:   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.227     brouard  4716: }
1.126     brouard  4717: 
                   4718: /*********** Tricode ****************************/
1.220     brouard  4719:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4720: {
1.144     brouard  4721:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4722:   /*     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  4723:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.224     brouard  4724:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4725:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
1.144     brouard  4726:   */
1.130     brouard  4727: 
1.145     brouard  4728:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4729:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4730:   int cptcode=0; /* Modality max of covariates j */
                   4731:   int modmincovj=0; /* Modality min of covariates j */
                   4732: 
                   4733: 
1.220     brouard  4734:   /* cptcoveff=0;  */
1.224     brouard  4735:        /* *cptcov=0; */
1.126     brouard  4736:  
1.144     brouard  4737:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4738: 
1.224     brouard  4739:   /* Loop on covariates without age and products and no quantitative variable */
                   4740:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
1.227     brouard  4741:   for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4742:     for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4743:     if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4744:       switch(Fixed[k]) {
                   4745:       case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.231     brouard  4746:                                for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
                   4747:                                        ij=(int)(covar[Tvar[k]][i]);
                   4748:                                        /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4749:                                         * If product of Vn*Vm, still boolean *:
                   4750:                                         * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4751:                                         * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4752:                                        /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4753:                                                 modality of the nth covariate of individual i. */
                   4754:                                        if (ij > modmaxcovj)
                   4755:                                                modmaxcovj=ij; 
                   4756:                                        else if (ij < modmincovj) 
                   4757:                                                modmincovj=ij; 
                   4758:                                        if ((ij < -1) && (ij > NCOVMAX)){
                   4759:                                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4760:                                                exit(1);
                   4761:                                        }else
                   4762:                                                Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4763:                                        /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4764:                                        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4765:                                        /* getting the maximum value of the modality of the covariate
                   4766:                                                 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4767:                                                 female ies 1, then modmaxcovj=1.
                   4768:                                        */
                   4769:                                } /* end for loop on individuals i */
                   4770:                                printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4771:                                fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4772:                                cptcode=modmaxcovj;
                   4773:                                /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4774:                                /*for (i=0; i<=cptcode; i++) {*/
                   4775:                                for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4776:                                        printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4777:                                        fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4778:                                        if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4779:                                                if( j != -1){
                   4780:                                                        ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4781:                                                                                                                                 covariate for which somebody answered excluding 
                   4782:                                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4783:                                                }
                   4784:                                                ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4785:                                                                                                                                                covariate for which somebody answered including 
                   4786:                                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
                   4787:                                        }       /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4788:                                                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4789:                                } /* Ndum[-1] number of undefined modalities */
                   4790:                        
                   4791:                                /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4792:                                /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4793:                                /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4794:                                /* modmincovj=3; modmaxcovj = 7; */
                   4795:                                /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4796:                                /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4797:                          /*             defining two dummy variables: variables V1_1 and V1_2.*/
                   4798:              /* nbcode[Tvar[j]][ij]=k; */
                   4799:              /* nbcode[Tvar[j]][1]=0; */
                   4800:              /* nbcode[Tvar[j]][2]=1; */
                   4801:              /* nbcode[Tvar[j]][3]=2; */
                   4802:              /* To be continued (not working yet). */
                   4803:              ij=0; /* ij is similar to i but can jump over null modalities */
                   4804:                                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*/
                   4805:          if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4806:                  break;
                   4807:                }
                   4808:                                        ij++;
                   4809:                                        nbcode[Tvar[k]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality. nbcode[1][1]=0 nbcode[1][2]=1*/
                   4810:                                        cptcode = ij; /* New max modality for covar j */
                   4811:                                } /* end of loop on modality i=-1 to 1 or more */
                   4812:                                break;
1.227     brouard  4813:       case 1: /* Testing on varying covariate, could be simple and
                   4814:               * should look at waves or product of fixed *
                   4815:               * varying. No time to test -1, assuming 0 and 1 only */
1.231     brouard  4816:                                ij=0;
                   4817:                                for(i=0; i<=1;i++){
                   4818:                                        nbcode[Tvar[k]][++ij]=i;
                   4819:                                }
                   4820:                                break;
1.227     brouard  4821:       default:
1.231     brouard  4822:                                break;
1.227     brouard  4823:       } /* end switch */
                   4824:     } /* end dummy test */
1.225     brouard  4825:     
1.192     brouard  4826:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4827:     /*         /\*recode from 0 *\/ */
                   4828:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4829:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4830:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4831:     /*         } */
                   4832:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4833:     /*         if (ij > ncodemax[j]) { */
                   4834:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4835:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4836:     /*           break; */
                   4837:     /*         } */
                   4838:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4839:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4840:   
1.225     brouard  4841:   for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.227     brouard  4842:   /* Look at fixed dummy (single or product) covariates to check empty modalities */
1.187     brouard  4843:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.225     brouard  4844:     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
1.227     brouard  4845:     ij=Tvar[i]; /* Tvar 5,4,3,6,5,7,1,4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V4*age */ 
                   4846:     Ndum[ij]++; /* Count the # of 1, 2 etc: {1,1,1,2,2,1,1} because V1 once, V2 once, two V4 and V5 in above */
                   4847:     /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
1.225     brouard  4848:   } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4849:   
                   4850:   ij=0;
1.227     brouard  4851:   /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4852:   for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.225     brouard  4853:     /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.227     brouard  4854:     /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4855:     if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4856:       /* If product not in single variable we don't print results */
1.225     brouard  4857:       /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.230     brouard  4858:       ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   4859:       Tvaraff[ij]=Tvar[k]; /* For printing combination *//* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, Tvar {5, 4, 3, 6, 5, 2, 7, 1, 1} Tvaraff={4, 3, 1} V4, V3, V1*/
                   4860:       Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
1.231     brouard  4861:       TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
1.227     brouard  4862:       if(Fixed[k]!=0)
                   4863:         anyvaryingduminmodel=1;
1.231     brouard  4864:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   4865:                        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4866:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   4867:                        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   4868:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   4869:                        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
1.227     brouard  4870:     } 
1.225     brouard  4871:   } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   4872:   /* ij--; */
                   4873:   /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4874:   *cptcov=ij; /*Number of total real effective covariates: effective
1.231     brouard  4875:                                                         * because they can be excluded from the model and real
                   4876:                                                         * if in the model but excluded because missing values, but how to get k from ij?*/
1.227     brouard  4877:   for(j=ij+1; j<= cptcovt; j++){
                   4878:     Tvaraff[j]=0;
                   4879:     Tmodelind[j]=0;
                   4880:   }
1.228     brouard  4881:   for(j=ntveff+1; j<= cptcovt; j++){
                   4882:     TmodelInvind[j]=0;
                   4883:   }
1.227     brouard  4884:   /* To be sorted */
                   4885:   ;
1.126     brouard  4886: }
                   4887: 
1.145     brouard  4888: 
1.126     brouard  4889: /*********** Health Expectancies ****************/
                   4890: 
1.235     brouard  4891:  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
1.126     brouard  4892: 
                   4893: {
                   4894:   /* Health expectancies, no variances */
1.164     brouard  4895:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4896:   int nhstepma, nstepma; /* Decreasing with age */
                   4897:   double age, agelim, hf;
                   4898:   double ***p3mat;
                   4899:   double eip;
                   4900: 
                   4901:   pstamp(ficreseij);
                   4902:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4903:   fprintf(ficreseij,"# Age");
                   4904:   for(i=1; i<=nlstate;i++){
                   4905:     for(j=1; j<=nlstate;j++){
                   4906:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4907:     }
                   4908:     fprintf(ficreseij," e%1d. ",i);
                   4909:   }
                   4910:   fprintf(ficreseij,"\n");
                   4911: 
                   4912:   
                   4913:   if(estepm < stepm){
                   4914:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4915:   }
                   4916:   else  hstepm=estepm;   
                   4917:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4918:    * This is mainly to measure the difference between two models: for example
                   4919:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4920:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4921:    * progression in between and thus overestimating or underestimating according
                   4922:    * to the curvature of the survival function. If, for the same date, we 
                   4923:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4924:    * to compare the new estimate of Life expectancy with the same linear 
                   4925:    * hypothesis. A more precise result, taking into account a more precise
                   4926:    * curvature will be obtained if estepm is as small as stepm. */
                   4927: 
                   4928:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4929:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4930:      nhstepm is the number of hstepm from age to agelim 
                   4931:      nstepm is the number of stepm from age to agelin. 
                   4932:      Look at hpijx to understand the reason of that which relies in memory size
                   4933:      and note for a fixed period like estepm months */
                   4934:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4935:      survival function given by stepm (the optimization length). Unfortunately it
                   4936:      means that if the survival funtion is printed only each two years of age and if
                   4937:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4938:      results. So we changed our mind and took the option of the best precision.
                   4939:   */
                   4940:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4941: 
                   4942:   agelim=AGESUP;
                   4943:   /* If stepm=6 months */
                   4944:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4945:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4946:     
                   4947: /* nhstepm age range expressed in number of stepm */
                   4948:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4949:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4950:   /* if (stepm >= YEARM) hstepm=1;*/
                   4951:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4952:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4953: 
                   4954:   for (age=bage; age<=fage; age ++){ 
                   4955:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4956:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4957:     /* if (stepm >= YEARM) hstepm=1;*/
                   4958:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4959: 
                   4960:     /* If stepm=6 months */
                   4961:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4962:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4963:     
1.235     brouard  4964:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  4965:     
                   4966:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4967:     
                   4968:     printf("%d|",(int)age);fflush(stdout);
                   4969:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4970:     
                   4971:     /* Computing expectancies */
                   4972:     for(i=1; i<=nlstate;i++)
                   4973:       for(j=1; j<=nlstate;j++)
                   4974:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4975:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4976:          
                   4977:          /* 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]);*/
                   4978: 
                   4979:        }
                   4980: 
                   4981:     fprintf(ficreseij,"%3.0f",age );
                   4982:     for(i=1; i<=nlstate;i++){
                   4983:       eip=0;
                   4984:       for(j=1; j<=nlstate;j++){
                   4985:        eip +=eij[i][j][(int)age];
                   4986:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4987:       }
                   4988:       fprintf(ficreseij,"%9.4f", eip );
                   4989:     }
                   4990:     fprintf(ficreseij,"\n");
                   4991:     
                   4992:   }
                   4993:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4994:   printf("\n");
                   4995:   fprintf(ficlog,"\n");
                   4996:   
                   4997: }
                   4998: 
1.235     brouard  4999:  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[], int nres )
1.126     brouard  5000: 
                   5001: {
                   5002:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5003:      to initial status i, ei. .
1.126     brouard  5004:   */
                   5005:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5006:   int nhstepma, nstepma; /* Decreasing with age */
                   5007:   double age, agelim, hf;
                   5008:   double ***p3matp, ***p3matm, ***varhe;
                   5009:   double **dnewm,**doldm;
                   5010:   double *xp, *xm;
                   5011:   double **gp, **gm;
                   5012:   double ***gradg, ***trgradg;
                   5013:   int theta;
                   5014: 
                   5015:   double eip, vip;
                   5016: 
                   5017:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5018:   xp=vector(1,npar);
                   5019:   xm=vector(1,npar);
                   5020:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5021:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5022:   
                   5023:   pstamp(ficresstdeij);
                   5024:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5025:   fprintf(ficresstdeij,"# Age");
                   5026:   for(i=1; i<=nlstate;i++){
                   5027:     for(j=1; j<=nlstate;j++)
                   5028:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5029:     fprintf(ficresstdeij," e%1d. ",i);
                   5030:   }
                   5031:   fprintf(ficresstdeij,"\n");
                   5032: 
                   5033:   pstamp(ficrescveij);
                   5034:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5035:   fprintf(ficrescveij,"# Age");
                   5036:   for(i=1; i<=nlstate;i++)
                   5037:     for(j=1; j<=nlstate;j++){
                   5038:       cptj= (j-1)*nlstate+i;
                   5039:       for(i2=1; i2<=nlstate;i2++)
                   5040:        for(j2=1; j2<=nlstate;j2++){
                   5041:          cptj2= (j2-1)*nlstate+i2;
                   5042:          if(cptj2 <= cptj)
                   5043:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5044:        }
                   5045:     }
                   5046:   fprintf(ficrescveij,"\n");
                   5047:   
                   5048:   if(estepm < stepm){
                   5049:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5050:   }
                   5051:   else  hstepm=estepm;   
                   5052:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5053:    * This is mainly to measure the difference between two models: for example
                   5054:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5055:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5056:    * progression in between and thus overestimating or underestimating according
                   5057:    * to the curvature of the survival function. If, for the same date, we 
                   5058:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5059:    * to compare the new estimate of Life expectancy with the same linear 
                   5060:    * hypothesis. A more precise result, taking into account a more precise
                   5061:    * curvature will be obtained if estepm is as small as stepm. */
                   5062: 
                   5063:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5064:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5065:      nhstepm is the number of hstepm from age to agelim 
                   5066:      nstepm is the number of stepm from age to agelin. 
                   5067:      Look at hpijx to understand the reason of that which relies in memory size
                   5068:      and note for a fixed period like estepm months */
                   5069:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5070:      survival function given by stepm (the optimization length). Unfortunately it
                   5071:      means that if the survival funtion is printed only each two years of age and if
                   5072:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5073:      results. So we changed our mind and took the option of the best precision.
                   5074:   */
                   5075:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5076: 
                   5077:   /* If stepm=6 months */
                   5078:   /* nhstepm age range expressed in number of stepm */
                   5079:   agelim=AGESUP;
                   5080:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5081:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5082:   /* if (stepm >= YEARM) hstepm=1;*/
                   5083:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5084:   
                   5085:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5086:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5087:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5088:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5089:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5090:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5091: 
                   5092:   for (age=bage; age<=fage; age ++){ 
                   5093:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5094:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5095:     /* if (stepm >= YEARM) hstepm=1;*/
                   5096:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5097:                
1.126     brouard  5098:     /* If stepm=6 months */
                   5099:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5100:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5101:     
                   5102:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5103:                
1.126     brouard  5104:     /* Computing  Variances of health expectancies */
                   5105:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5106:        decrease memory allocation */
                   5107:     for(theta=1; theta <=npar; theta++){
                   5108:       for(i=1; i<=npar; i++){ 
1.222     brouard  5109:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5110:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5111:       }
1.235     brouard  5112:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5113:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5114:                        
1.126     brouard  5115:       for(j=1; j<= nlstate; j++){
1.222     brouard  5116:        for(i=1; i<=nlstate; i++){
                   5117:          for(h=0; h<=nhstepm-1; h++){
                   5118:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5119:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5120:          }
                   5121:        }
1.126     brouard  5122:       }
1.218     brouard  5123:                        
1.126     brouard  5124:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5125:        for(h=0; h<=nhstepm-1; h++){
                   5126:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5127:        }
1.126     brouard  5128:     }/* End theta */
                   5129:     
                   5130:     
                   5131:     for(h=0; h<=nhstepm-1; h++)
                   5132:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5133:        for(theta=1; theta <=npar; theta++)
                   5134:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5135:     
1.218     brouard  5136:                
1.222     brouard  5137:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5138:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5139:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5140:                
1.222     brouard  5141:     printf("%d|",(int)age);fflush(stdout);
                   5142:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5143:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5144:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5145:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5146:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5147:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5148:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5149:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5150:       }
                   5151:     }
1.218     brouard  5152:                
1.126     brouard  5153:     /* Computing expectancies */
1.235     brouard  5154:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5155:     for(i=1; i<=nlstate;i++)
                   5156:       for(j=1; j<=nlstate;j++)
1.222     brouard  5157:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5158:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5159:                                        
1.222     brouard  5160:          /* 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]);*/
1.218     brouard  5161:                                        
1.222     brouard  5162:        }
1.218     brouard  5163:                
1.126     brouard  5164:     fprintf(ficresstdeij,"%3.0f",age );
                   5165:     for(i=1; i<=nlstate;i++){
                   5166:       eip=0.;
                   5167:       vip=0.;
                   5168:       for(j=1; j<=nlstate;j++){
1.222     brouard  5169:        eip += eij[i][j][(int)age];
                   5170:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5171:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5172:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
1.126     brouard  5173:       }
                   5174:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5175:     }
                   5176:     fprintf(ficresstdeij,"\n");
1.218     brouard  5177:                
1.126     brouard  5178:     fprintf(ficrescveij,"%3.0f",age );
                   5179:     for(i=1; i<=nlstate;i++)
                   5180:       for(j=1; j<=nlstate;j++){
1.222     brouard  5181:        cptj= (j-1)*nlstate+i;
                   5182:        for(i2=1; i2<=nlstate;i2++)
                   5183:          for(j2=1; j2<=nlstate;j2++){
                   5184:            cptj2= (j2-1)*nlstate+i2;
                   5185:            if(cptj2 <= cptj)
                   5186:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5187:          }
1.126     brouard  5188:       }
                   5189:     fprintf(ficrescveij,"\n");
1.218     brouard  5190:                
1.126     brouard  5191:   }
                   5192:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5193:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5194:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5195:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5196:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5197:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5198:   printf("\n");
                   5199:   fprintf(ficlog,"\n");
1.218     brouard  5200:        
1.126     brouard  5201:   free_vector(xm,1,npar);
                   5202:   free_vector(xp,1,npar);
                   5203:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5204:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5205:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5206: }
1.218     brouard  5207:  
1.126     brouard  5208: /************ Variance ******************/
1.235     brouard  5209:  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[], int nres)
1.218     brouard  5210:  {
                   5211:    /* Variance of health expectancies */
                   5212:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5213:    /* double **newm;*/
                   5214:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5215:   
                   5216:    /* int movingaverage(); */
                   5217:    double **dnewm,**doldm;
                   5218:    double **dnewmp,**doldmp;
                   5219:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5220:    int k;
                   5221:    double *xp;
                   5222:    double **gp, **gm;  /* for var eij */
                   5223:    double ***gradg, ***trgradg; /*for var eij */
                   5224:    double **gradgp, **trgradgp; /* for var p point j */
                   5225:    double *gpp, *gmp; /* for var p point j */
                   5226:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5227:    double ***p3mat;
                   5228:    double age,agelim, hf;
                   5229:    /* double ***mobaverage; */
                   5230:    int theta;
                   5231:    char digit[4];
                   5232:    char digitp[25];
                   5233: 
                   5234:    char fileresprobmorprev[FILENAMELENGTH];
                   5235: 
                   5236:    if(popbased==1){
                   5237:      if(mobilav!=0)
                   5238:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5239:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5240:    }
                   5241:    else 
                   5242:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5243: 
1.218     brouard  5244:    /* if (mobilav!=0) { */
                   5245:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5246:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5247:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5248:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5249:    /*   } */
                   5250:    /* } */
                   5251: 
                   5252:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5253:    sprintf(digit,"%-d",ij);
                   5254:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5255:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5256:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5257:    strcat(fileresprobmorprev,fileresu);
                   5258:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5259:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5260:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5261:    }
                   5262:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5263:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5264:    pstamp(ficresprobmorprev);
                   5265:    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);
                   5266:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5267:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5268:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5269:      for(i=1; i<=nlstate;i++)
                   5270:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5271:    }  
                   5272:    fprintf(ficresprobmorprev,"\n");
                   5273:   
                   5274:    fprintf(ficgp,"\n# Routine varevsij");
                   5275:    fprintf(ficgp,"\nunset title \n");
                   5276:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5277:    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");
                   5278:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5279:    /*   } */
                   5280:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5281:    pstamp(ficresvij);
                   5282:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5283:    if(popbased==1)
                   5284:      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);
                   5285:    else
                   5286:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5287:    fprintf(ficresvij,"# Age");
                   5288:    for(i=1; i<=nlstate;i++)
                   5289:      for(j=1; j<=nlstate;j++)
                   5290:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5291:    fprintf(ficresvij,"\n");
                   5292: 
                   5293:    xp=vector(1,npar);
                   5294:    dnewm=matrix(1,nlstate,1,npar);
                   5295:    doldm=matrix(1,nlstate,1,nlstate);
                   5296:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5297:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5298: 
                   5299:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5300:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5301:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5302:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5303:   
1.218     brouard  5304:    if(estepm < stepm){
                   5305:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5306:    }
                   5307:    else  hstepm=estepm;   
                   5308:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5309:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5310:       nhstepm is the number of hstepm from age to agelim 
                   5311:       nstepm is the number of stepm from age to agelim. 
                   5312:       Look at function hpijx to understand why because of memory size limitations, 
                   5313:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5314:       survival function given by stepm (the optimization length). Unfortunately it
                   5315:       means that if the survival funtion is printed every two years of age and if
                   5316:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5317:       results. So we changed our mind and took the option of the best precision.
                   5318:    */
                   5319:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5320:    agelim = AGESUP;
                   5321:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5322:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5323:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5324:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5325:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5326:      gp=matrix(0,nhstepm,1,nlstate);
                   5327:      gm=matrix(0,nhstepm,1,nlstate);
                   5328:                
                   5329:                
                   5330:      for(theta=1; theta <=npar; theta++){
                   5331:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5332:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5333:        }
                   5334:                        
1.235     brouard  5335:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
1.218     brouard  5336:                        
                   5337:        if (popbased==1) {
                   5338:         if(mobilav ==0){
                   5339:           for(i=1; i<=nlstate;i++)
                   5340:             prlim[i][i]=probs[(int)age][i][ij];
                   5341:         }else{ /* mobilav */ 
                   5342:           for(i=1; i<=nlstate;i++)
                   5343:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5344:         }
                   5345:        }
                   5346:                        
1.235     brouard  5347:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.218     brouard  5348:        for(j=1; j<= nlstate; j++){
                   5349:         for(h=0; h<=nhstepm; h++){
                   5350:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5351:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5352:         }
                   5353:        }
                   5354:        /* Next for computing probability of death (h=1 means
                   5355:          computed over hstepm matrices product = hstepm*stepm months) 
                   5356:          as a weighted average of prlim.
                   5357:        */
                   5358:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5359:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5360:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5361:        }    
                   5362:        /* end probability of death */
                   5363:                        
                   5364:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5365:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5366:                        
1.235     brouard  5367:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nresult);
1.218     brouard  5368:                        
                   5369:        if (popbased==1) {
                   5370:         if(mobilav ==0){
                   5371:           for(i=1; i<=nlstate;i++)
                   5372:             prlim[i][i]=probs[(int)age][i][ij];
                   5373:         }else{ /* mobilav */ 
                   5374:           for(i=1; i<=nlstate;i++)
                   5375:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5376:         }
                   5377:        }
                   5378:                        
1.235     brouard  5379:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5380:                        
                   5381:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5382:         for(h=0; h<=nhstepm; h++){
                   5383:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5384:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5385:         }
                   5386:        }
                   5387:        /* This for computing probability of death (h=1 means
                   5388:          computed over hstepm matrices product = hstepm*stepm months) 
                   5389:          as a weighted average of prlim.
                   5390:        */
                   5391:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5392:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5393:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5394:        }    
                   5395:        /* end probability of death */
                   5396:                        
                   5397:        for(j=1; j<= nlstate; j++) /* vareij */
                   5398:         for(h=0; h<=nhstepm; h++){
                   5399:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5400:         }
                   5401:                        
                   5402:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5403:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5404:        }
                   5405:                        
                   5406:      } /* End theta */
                   5407:                
                   5408:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5409:                
                   5410:      for(h=0; h<=nhstepm; h++) /* veij */
                   5411:        for(j=1; j<=nlstate;j++)
                   5412:         for(theta=1; theta <=npar; theta++)
                   5413:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5414:                
                   5415:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5416:        for(theta=1; theta <=npar; theta++)
                   5417:         trgradgp[j][theta]=gradgp[theta][j];
                   5418:                
                   5419:                
                   5420:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5421:      for(i=1;i<=nlstate;i++)
                   5422:        for(j=1;j<=nlstate;j++)
                   5423:         vareij[i][j][(int)age] =0.;
                   5424:                
                   5425:      for(h=0;h<=nhstepm;h++){
                   5426:        for(k=0;k<=nhstepm;k++){
                   5427:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5428:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5429:         for(i=1;i<=nlstate;i++)
                   5430:           for(j=1;j<=nlstate;j++)
                   5431:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5432:        }
                   5433:      }
                   5434:                
                   5435:      /* pptj */
                   5436:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5437:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5438:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5439:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5440:         varppt[j][i]=doldmp[j][i];
                   5441:      /* end ppptj */
                   5442:      /*  x centered again */
                   5443:                
1.235     brouard  5444:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
1.218     brouard  5445:                
                   5446:      if (popbased==1) {
                   5447:        if(mobilav ==0){
                   5448:         for(i=1; i<=nlstate;i++)
                   5449:           prlim[i][i]=probs[(int)age][i][ij];
                   5450:        }else{ /* mobilav */ 
                   5451:         for(i=1; i<=nlstate;i++)
                   5452:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5453:        }
                   5454:      }
                   5455:                
                   5456:      /* This for computing probability of death (h=1 means
                   5457:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5458:        as a weighted average of prlim.
                   5459:      */
1.235     brouard  5460:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5461:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5462:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5463:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5464:      }    
                   5465:      /* end probability of death */
                   5466:                
                   5467:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5468:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5469:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5470:        for(i=1; i<=nlstate;i++){
                   5471:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5472:        }
                   5473:      } 
                   5474:      fprintf(ficresprobmorprev,"\n");
                   5475:                
                   5476:      fprintf(ficresvij,"%.0f ",age );
                   5477:      for(i=1; i<=nlstate;i++)
                   5478:        for(j=1; j<=nlstate;j++){
                   5479:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5480:        }
                   5481:      fprintf(ficresvij,"\n");
                   5482:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5483:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5484:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5485:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5486:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5487:    } /* End age */
                   5488:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5489:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5490:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5491:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5492:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5493:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5494:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5495:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5496:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5497:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5498:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5499:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5500:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5501:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5502:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5503:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5504:    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);
                   5505:    /*  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  5506:     */
1.218     brouard  5507:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5508:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5509: 
1.218     brouard  5510:    free_vector(xp,1,npar);
                   5511:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5512:    free_matrix(dnewm,1,nlstate,1,npar);
                   5513:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5514:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5515:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5516:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5517:    fclose(ficresprobmorprev);
                   5518:    fflush(ficgp);
                   5519:    fflush(fichtm); 
                   5520:  }  /* end varevsij */
1.126     brouard  5521: 
                   5522: /************ Variance of prevlim ******************/
1.235     brouard  5523:  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[], int nres)
1.126     brouard  5524: {
1.205     brouard  5525:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5526:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5527: 
1.126     brouard  5528:   double **dnewm,**doldm;
                   5529:   int i, j, nhstepm, hstepm;
                   5530:   double *xp;
                   5531:   double *gp, *gm;
                   5532:   double **gradg, **trgradg;
1.208     brouard  5533:   double **mgm, **mgp;
1.126     brouard  5534:   double age,agelim;
                   5535:   int theta;
                   5536:   
                   5537:   pstamp(ficresvpl);
                   5538:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5539:   fprintf(ficresvpl,"# Age");
                   5540:   for(i=1; i<=nlstate;i++)
                   5541:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5542:   fprintf(ficresvpl,"\n");
                   5543: 
                   5544:   xp=vector(1,npar);
                   5545:   dnewm=matrix(1,nlstate,1,npar);
                   5546:   doldm=matrix(1,nlstate,1,nlstate);
                   5547:   
                   5548:   hstepm=1*YEARM; /* Every year of age */
                   5549:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5550:   agelim = AGESUP;
                   5551:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5552:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5553:     if (stepm >= YEARM) hstepm=1;
                   5554:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5555:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5556:     mgp=matrix(1,npar,1,nlstate);
                   5557:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5558:     gp=vector(1,nlstate);
                   5559:     gm=vector(1,nlstate);
                   5560: 
                   5561:     for(theta=1; theta <=npar; theta++){
                   5562:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5563:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5564:       }
1.209     brouard  5565:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5566:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5567:       else
1.235     brouard  5568:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5569:       for(i=1;i<=nlstate;i++){
1.126     brouard  5570:        gp[i] = prlim[i][i];
1.208     brouard  5571:        mgp[theta][i] = prlim[i][i];
                   5572:       }
1.126     brouard  5573:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5574:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5575:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5576:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5577:       else
1.235     brouard  5578:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5579:       for(i=1;i<=nlstate;i++){
1.126     brouard  5580:        gm[i] = prlim[i][i];
1.208     brouard  5581:        mgm[theta][i] = prlim[i][i];
                   5582:       }
1.126     brouard  5583:       for(i=1;i<=nlstate;i++)
                   5584:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5585:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5586:     } /* End theta */
                   5587: 
                   5588:     trgradg =matrix(1,nlstate,1,npar);
                   5589: 
                   5590:     for(j=1; j<=nlstate;j++)
                   5591:       for(theta=1; theta <=npar; theta++)
                   5592:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5593:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5594:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5595:     /*   for(j=1; j<=nlstate;j++){ */
                   5596:     /*         printf(" %d ",j); */
                   5597:     /*         for(theta=1; theta <=npar; theta++) */
                   5598:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5599:     /*         printf("\n "); */
                   5600:     /*   } */
                   5601:     /* } */
                   5602:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5603:     /*   printf("\n gradg %d ",(int)age); */
                   5604:     /*   for(j=1; j<=nlstate;j++){ */
                   5605:     /*         printf("%d ",j); */
                   5606:     /*         for(theta=1; theta <=npar; theta++) */
                   5607:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5608:     /*         printf("\n "); */
                   5609:     /*   } */
                   5610:     /* } */
1.126     brouard  5611: 
                   5612:     for(i=1;i<=nlstate;i++)
                   5613:       varpl[i][(int)age] =0.;
1.209     brouard  5614:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5615:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5616:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5617:     }else{
1.126     brouard  5618:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5619:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5620:     }
1.126     brouard  5621:     for(i=1;i<=nlstate;i++)
                   5622:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5623: 
                   5624:     fprintf(ficresvpl,"%.0f ",age );
                   5625:     for(i=1; i<=nlstate;i++)
                   5626:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5627:     fprintf(ficresvpl,"\n");
                   5628:     free_vector(gp,1,nlstate);
                   5629:     free_vector(gm,1,nlstate);
1.208     brouard  5630:     free_matrix(mgm,1,npar,1,nlstate);
                   5631:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5632:     free_matrix(gradg,1,npar,1,nlstate);
                   5633:     free_matrix(trgradg,1,nlstate,1,npar);
                   5634:   } /* End age */
                   5635: 
                   5636:   free_vector(xp,1,npar);
                   5637:   free_matrix(doldm,1,nlstate,1,npar);
                   5638:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5639: 
                   5640: }
                   5641: 
                   5642: /************ Variance of one-step probabilities  ******************/
                   5643: 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[])
1.222     brouard  5644:  {
                   5645:    int i, j=0,  k1, l1, tj;
                   5646:    int k2, l2, j1,  z1;
                   5647:    int k=0, l;
                   5648:    int first=1, first1, first2;
                   5649:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5650:    double **dnewm,**doldm;
                   5651:    double *xp;
                   5652:    double *gp, *gm;
                   5653:    double **gradg, **trgradg;
                   5654:    double **mu;
                   5655:    double age, cov[NCOVMAX+1];
                   5656:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5657:    int theta;
                   5658:    char fileresprob[FILENAMELENGTH];
                   5659:    char fileresprobcov[FILENAMELENGTH];
                   5660:    char fileresprobcor[FILENAMELENGTH];
                   5661:    double ***varpij;
                   5662: 
                   5663:    strcpy(fileresprob,"PROB_"); 
                   5664:    strcat(fileresprob,fileres);
                   5665:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5666:      printf("Problem with resultfile: %s\n", fileresprob);
                   5667:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5668:    }
                   5669:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5670:    strcat(fileresprobcov,fileresu);
                   5671:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5672:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5673:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5674:    }
                   5675:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5676:    strcat(fileresprobcor,fileresu);
                   5677:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5678:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5679:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5680:    }
                   5681:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5682:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5683:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5684:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5685:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5686:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5687:    pstamp(ficresprob);
                   5688:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5689:    fprintf(ficresprob,"# Age");
                   5690:    pstamp(ficresprobcov);
                   5691:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5692:    fprintf(ficresprobcov,"# Age");
                   5693:    pstamp(ficresprobcor);
                   5694:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5695:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5696: 
                   5697: 
1.222     brouard  5698:    for(i=1; i<=nlstate;i++)
                   5699:      for(j=1; j<=(nlstate+ndeath);j++){
                   5700:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5701:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5702:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5703:      }  
                   5704:    /* fprintf(ficresprob,"\n");
                   5705:       fprintf(ficresprobcov,"\n");
                   5706:       fprintf(ficresprobcor,"\n");
                   5707:    */
                   5708:    xp=vector(1,npar);
                   5709:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5710:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5711:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5712:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5713:    first=1;
                   5714:    fprintf(ficgp,"\n# Routine varprob");
                   5715:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5716:    fprintf(fichtm,"\n");
                   5717: 
                   5718:    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);
                   5719:    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);
                   5720:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5721: and drawn. It helps understanding how is the covariance between two incidences.\
                   5722:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5723:    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. \
1.126     brouard  5724: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5725: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5726: standard deviations wide on each axis. <br>\
                   5727:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5728:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5729: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5730: 
1.222     brouard  5731:    cov[1]=1;
                   5732:    /* tj=cptcoveff; */
1.225     brouard  5733:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5734:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5735:    j1=0;
1.224     brouard  5736:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5737:      if  (cptcovn>0) {
                   5738:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5739:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5740:        fprintf(ficresprob, "**********\n#\n");
                   5741:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5742:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5743:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5744:                        
1.222     brouard  5745:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5746:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5747:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5748:                        
                   5749:                        
1.222     brouard  5750:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5751:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5752:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5753:                        
1.222     brouard  5754:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5755:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5756:        fprintf(ficresprobcor, "**********\n#");    
                   5757:        if(invalidvarcomb[j1]){
                   5758:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5759:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5760:         continue;
                   5761:        }
                   5762:      }
                   5763:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5764:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5765:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5766:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5767:      for (age=bage; age<=fage; age ++){ 
                   5768:        cov[2]=age;
                   5769:        if(nagesqr==1)
                   5770:         cov[3]= age*age;
                   5771:        for (k=1; k<=cptcovn;k++) {
                   5772:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5773:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5774:                                                                    * 1  1 1 1 1
                   5775:                                                                    * 2  2 1 1 1
                   5776:                                                                    * 3  1 2 1 1
                   5777:                                                                    */
                   5778:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5779:        }
                   5780:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5781:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5782:        for (k=1; k<=cptcovprod;k++)
                   5783:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5784:                        
                   5785:                        
1.222     brouard  5786:        for(theta=1; theta <=npar; theta++){
                   5787:         for(i=1; i<=npar; i++)
                   5788:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5789:                                
1.222     brouard  5790:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5791:                                
1.222     brouard  5792:         k=0;
                   5793:         for(i=1; i<= (nlstate); i++){
                   5794:           for(j=1; j<=(nlstate+ndeath);j++){
                   5795:             k=k+1;
                   5796:             gp[k]=pmmij[i][j];
                   5797:           }
                   5798:         }
1.220     brouard  5799:                                
1.222     brouard  5800:         for(i=1; i<=npar; i++)
                   5801:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5802:                                
1.222     brouard  5803:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5804:         k=0;
                   5805:         for(i=1; i<=(nlstate); i++){
                   5806:           for(j=1; j<=(nlstate+ndeath);j++){
                   5807:             k=k+1;
                   5808:             gm[k]=pmmij[i][j];
                   5809:           }
                   5810:         }
1.220     brouard  5811:                                
1.222     brouard  5812:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5813:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5814:        }
1.126     brouard  5815: 
1.222     brouard  5816:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5817:         for(theta=1; theta <=npar; theta++)
                   5818:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5819:                        
1.222     brouard  5820:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5821:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5822:                        
1.222     brouard  5823:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5824:                        
1.222     brouard  5825:        k=0;
                   5826:        for(i=1; i<=(nlstate); i++){
                   5827:         for(j=1; j<=(nlstate+ndeath);j++){
                   5828:           k=k+1;
                   5829:           mu[k][(int) age]=pmmij[i][j];
                   5830:         }
                   5831:        }
                   5832:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5833:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5834:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5835:                        
1.222     brouard  5836:        /*printf("\n%d ",(int)age);
                   5837:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5838:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5839:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5840:         }*/
1.220     brouard  5841:                        
1.222     brouard  5842:        fprintf(ficresprob,"\n%d ",(int)age);
                   5843:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5844:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5845:                        
1.222     brouard  5846:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5847:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5848:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5849:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5850:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5851:        }
                   5852:        i=0;
                   5853:        for (k=1; k<=(nlstate);k++){
                   5854:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5855:           i++;
                   5856:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5857:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5858:           for (j=1; j<=i;j++){
                   5859:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5860:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5861:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5862:           }
                   5863:         }
                   5864:        }/* end of loop for state */
                   5865:      } /* end of loop for age */
                   5866:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5867:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5868:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5869:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5870:     
                   5871:      /* Confidence intervalle of pij  */
                   5872:      /*
                   5873:        fprintf(ficgp,"\nunset parametric;unset label");
                   5874:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5875:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5876:        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);
                   5877:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5878:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5879:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5880:      */
                   5881:                
                   5882:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5883:      first1=1;first2=2;
                   5884:      for (k2=1; k2<=(nlstate);k2++){
                   5885:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5886:         if(l2==k2) continue;
                   5887:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5888:         for (k1=1; k1<=(nlstate);k1++){
                   5889:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5890:             if(l1==k1) continue;
                   5891:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5892:             if(i<=j) continue;
                   5893:             for (age=bage; age<=fage; age ++){ 
                   5894:               if ((int)age %5==0){
                   5895:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5896:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5897:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5898:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5899:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5900:                 c12=cv12/sqrt(v1*v2);
                   5901:                 /* Computing eigen value of matrix of covariance */
                   5902:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5903:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5904:                 if ((lc2 <0) || (lc1 <0) ){
                   5905:                   if(first2==1){
                   5906:                     first1=0;
                   5907:                     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);
                   5908:                   }
                   5909:                   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);
                   5910:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5911:                   /* lc2=fabs(lc2); */
                   5912:                 }
1.220     brouard  5913:                                                                
1.222     brouard  5914:                 /* Eigen vectors */
                   5915:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5916:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5917:                 v21=(lc1-v1)/cv12*v11;
                   5918:                 v12=-v21;
                   5919:                 v22=v11;
                   5920:                 tnalp=v21/v11;
                   5921:                 if(first1==1){
                   5922:                   first1=0;
                   5923:                   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);
                   5924:                 }
                   5925:                 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);
                   5926:                 /*printf(fignu*/
                   5927:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5928:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5929:                 if(first==1){
                   5930:                   first=0;
                   5931:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5932:                   fprintf(ficgp,"\nset parametric;unset label");
                   5933:                   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);
                   5934:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   5935:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  5936:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5937: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  5938:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   5939:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5940:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5941:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5942:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5943:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5944:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5945:                   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",      \
                   5946:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   5947:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5948:                 }else{
                   5949:                   first=0;
                   5950:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5951:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5952:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5953:                   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", \
                   5954:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   5955:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5956:                 }/* if first */
                   5957:               } /* age mod 5 */
                   5958:             } /* end loop age */
                   5959:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5960:             first=1;
                   5961:           } /*l12 */
                   5962:         } /* k12 */
                   5963:        } /*l1 */
                   5964:      }/* k1 */
                   5965:    }  /* loop on combination of covariates j1 */
                   5966:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5967:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5968:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5969:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5970:    free_vector(xp,1,npar);
                   5971:    fclose(ficresprob);
                   5972:    fclose(ficresprobcov);
                   5973:    fclose(ficresprobcor);
                   5974:    fflush(ficgp);
                   5975:    fflush(fichtmcov);
                   5976:  }
1.126     brouard  5977: 
                   5978: 
                   5979: /******************* Printing html file ***********/
1.201     brouard  5980: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5981:                  int lastpass, int stepm, int weightopt, char model[],\
                   5982:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5983:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5984:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5985:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5986:   int jj1, k1, i1, cpt;
                   5987: 
                   5988:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5989:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5990: </ul>");
1.214     brouard  5991:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5992:    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",
                   5993:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5994:    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  5995:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5996:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5997:    fprintf(fichtm,"\
                   5998:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5999:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6000:    fprintf(fichtm,"\
1.217     brouard  6001:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6002:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6003:    fprintf(fichtm,"\
1.126     brouard  6004:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6005:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6006:    fprintf(fichtm,"\
1.217     brouard  6007:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6008:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6009:    fprintf(fichtm,"\
1.211     brouard  6010:  - (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  6011:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6012:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6013:    if(prevfcast==1){
                   6014:      fprintf(fichtm,"\
                   6015:  - Prevalence projections by age and states:                           \
1.201     brouard  6016:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6017:    }
1.126     brouard  6018: 
1.222     brouard  6019:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6020: 
1.225     brouard  6021:    m=pow(2,cptcoveff);
1.222     brouard  6022:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6023: 
1.222     brouard  6024:    jj1=0;
                   6025:    for(k1=1; k1<=m;k1++){
1.220     brouard  6026: 
1.222     brouard  6027:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6028:      jj1++;
                   6029:      if (cptcovn > 0) {
                   6030:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6031:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.222     brouard  6032:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   6033:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
                   6034:        }
1.230     brouard  6035:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6036:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6037:        if(invalidvarcomb[k1]){
                   6038:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6039:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6040:         continue;
                   6041:        }
                   6042:      }
                   6043:      /* aij, bij */
                   6044:      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> \
1.211     brouard  6045: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222     brouard  6046:      /* Pij */
                   6047:      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  6048: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222     brouard  6049:      /* Quasi-incidences */
                   6050:      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.220     brouard  6051:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6052:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   6053: 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  6054: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222     brouard  6055:      /* Survival functions (period) in state j */
                   6056:      for(cpt=1; cpt<=nlstate;cpt++){
                   6057:        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> \
1.201     brouard  6058: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
1.222     brouard  6059:      }
                   6060:      /* State specific survival functions (period) */
                   6061:      for(cpt=1; cpt<=nlstate;cpt++){
                   6062:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6063:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  6064:  <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);
1.222     brouard  6065:      }
                   6066:      /* Period (stable) prevalence in each health state */
                   6067:      for(cpt=1; cpt<=nlstate;cpt++){
                   6068:        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  6069: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
1.222     brouard  6070:      }
                   6071:      if(backcast==1){
                   6072:        /* Period (stable) back prevalence in each health state */
                   6073:        for(cpt=1; cpt<=nlstate;cpt++){
                   6074:         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> \
1.217     brouard  6075: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
1.222     brouard  6076:        }
1.217     brouard  6077:      }
1.222     brouard  6078:      if(prevfcast==1){
                   6079:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6080:        for(cpt=1; cpt<=nlstate;cpt++){
                   6081:         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  6082: <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.222     brouard  6083:        }
                   6084:      }
1.220     brouard  6085:         
1.222     brouard  6086:      for(cpt=1; cpt<=nlstate;cpt++) {
                   6087:        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  6088: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.222     brouard  6089:      }
                   6090:      /* } /\* end i1 *\/ */
                   6091:    }/* End k1 */
                   6092:    fprintf(fichtm,"</ul>");
1.126     brouard  6093: 
1.222     brouard  6094:    fprintf(fichtm,"\
1.126     brouard  6095: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6096:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6097:  - 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  6098: But because parameters are usually highly correlated (a higher incidence of disability \
                   6099: and a higher incidence of recovery can give very close observed transition) it might \
                   6100: be very useful to look not only at linear confidence intervals estimated from the \
                   6101: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6102: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6103: covariance matrix of the one-step probabilities. \
                   6104: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6105: 
1.222     brouard  6106:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6107:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6108:    fprintf(fichtm,"\
1.126     brouard  6109:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6110:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6111: 
1.222     brouard  6112:    fprintf(fichtm,"\
1.126     brouard  6113:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6114:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6115:    fprintf(fichtm,"\
1.126     brouard  6116:  - 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): \
                   6117:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6118:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6119:    fprintf(fichtm,"\
1.126     brouard  6120:  - (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): \
                   6121:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6122:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6123:    fprintf(fichtm,"\
1.128     brouard  6124:  - 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.222     brouard  6125:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6126:    fprintf(fichtm,"\
1.128     brouard  6127:  - 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.222     brouard  6128:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6129:    fprintf(fichtm,"\
1.126     brouard  6130:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6131:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6132: 
                   6133: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6134: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6135: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6136: /*     <br>",fileres,fileres,fileres,fileres); */
                   6137: /*  else  */
                   6138: /*    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); */
1.222     brouard  6139:    fflush(fichtm);
                   6140:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6141: 
1.225     brouard  6142:    m=pow(2,cptcoveff);
1.222     brouard  6143:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6144: 
1.222     brouard  6145:    jj1=0;
                   6146:    for(k1=1; k1<=m;k1++){
                   6147:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6148:      jj1++;
1.126     brouard  6149:      if (cptcovn > 0) {
                   6150:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6151:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.222     brouard  6152:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  6153:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6154: 
1.222     brouard  6155:        if(invalidvarcomb[k1]){
                   6156:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6157:         continue;
                   6158:        }
1.126     brouard  6159:      }
                   6160:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6161:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   6162: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  6163: <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  6164:      }
                   6165:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6166: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6167: true period expectancies (those weighted with period prevalences are also\
                   6168:  drawn in addition to the population based expectancies computed using\
1.218     brouard  6169:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  6170: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222     brouard  6171:      /* } /\* end i1 *\/ */
                   6172:    }/* End k1 */
                   6173:    fprintf(fichtm,"</ul>");
                   6174:    fflush(fichtm);
1.126     brouard  6175: }
                   6176: 
                   6177: /******************* Gnuplot file **************/
1.223     brouard  6178: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6179: 
                   6180:   char dirfileres[132],optfileres[132];
1.223     brouard  6181:   char gplotcondition[132];
1.235     brouard  6182:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0,l=0;
1.211     brouard  6183:   int lv=0, vlv=0, kl=0;
1.130     brouard  6184:   int ng=0;
1.201     brouard  6185:   int vpopbased;
1.223     brouard  6186:   int ioffset; /* variable offset for columns */
1.235     brouard  6187:   int nres=0; /* Index of resultline */
1.219     brouard  6188: 
1.126     brouard  6189: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6190: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6191: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6192: /*   } */
                   6193: 
                   6194:   /*#ifdef windows */
                   6195:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6196:   /*#endif */
1.225     brouard  6197:   m=pow(2,cptcoveff);
1.126     brouard  6198: 
1.202     brouard  6199:   /* Contribution to likelihood */
                   6200:   /* Plot the probability implied in the likelihood */
1.223     brouard  6201:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6202:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6203:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6204:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6205: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6206:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6207: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6208:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6209:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6210:   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));
                   6211:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6212:   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));
                   6213:   for (i=1; i<= nlstate ; i ++) {
                   6214:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6215:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6216:     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);
                   6217:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6218:       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);
                   6219:     }
                   6220:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6221:   }
                   6222:   /* 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 */               
                   6223:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6224:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6225:   fprintf(ficgp,"\nset out;unset log\n");
                   6226:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6227: 
1.126     brouard  6228:   strcpy(dirfileres,optionfilefiname);
                   6229:   strcpy(optfileres,"vpl");
1.223     brouard  6230:   /* 1eme*/
1.211     brouard  6231:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
1.236   ! brouard  6232:     for (k1=1; k1<= m ; k1 ++) /* For each valid combination of covariate */
        !          6233:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.235     brouard  6234:     /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6235:       if(TKresult[nres]!= k1)
                   6236:        continue;
                   6237:       /* We are interested in selected combination by the resultline */
                   6238:       printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
                   6239:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.225     brouard  6240:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6241:        lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
1.223     brouard  6242:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6243:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6244:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6245:        vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6246:        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.235     brouard  6247:        printf(" V%d=%d ",Tvaraff[k],vlv);
1.223     brouard  6248:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6249:       }
1.235     brouard  6250:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6251:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6252:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6253:       }        
                   6254:       printf("\n#\n");
1.211     brouard  6255:       fprintf(ficgp,"\n#\n");
1.223     brouard  6256:       if(invalidvarcomb[k1]){
                   6257:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6258:        continue;
                   6259:       }
1.235     brouard  6260:       
1.223     brouard  6261:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   6262:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
                   6263:       fprintf(ficgp,"set xlabel \"Age\" \n\
1.235     brouard  6264: set ylabel \"Probability\" \n            \
                   6265: set ter svg size 640, 480\n                                            \
1.201     brouard  6266: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.235     brouard  6267:       
1.223     brouard  6268:       for (i=1; i<= nlstate ; i ++) {
                   6269:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6270:        else        fprintf(ficgp," %%*lf (%%*lf)");
                   6271:       }
                   6272:       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);
                   6273:       for (i=1; i<= nlstate ; i ++) {
                   6274:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6275:        else fprintf(ficgp," %%*lf (%%*lf)");
                   6276:       } 
                   6277:       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); 
                   6278:       for (i=1; i<= nlstate ; i ++) {
                   6279:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6280:        else fprintf(ficgp," %%*lf (%%*lf)");
                   6281:       }  
                   6282:       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));
                   6283:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6284:        /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
                   6285:        fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
1.225     brouard  6286:        if(cptcoveff ==0){
1.223     brouard  6287:          fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",  2+(cpt-1),  cpt );
                   6288:        }else{
                   6289:          kl=0;
1.225     brouard  6290:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6291:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
1.223     brouard  6292:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6293:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6294:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6295:            vlv= nbcode[Tvaraff[k]][lv];
                   6296:            kl++;
                   6297:            /* 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 *\/ */
                   6298:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6299:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6300:            /* ''  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*/
1.225     brouard  6301:            if(k==cptcoveff){
1.227     brouard  6302:              fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   6303:                      4+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.223     brouard  6304:            }else{
                   6305:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6306:              kl++;
                   6307:            }
                   6308:          } /* end covariate */
                   6309:        } /* end if no covariate */
                   6310:       } /* end if backcast */
                   6311:       fprintf(ficgp,"\nset out \n");
1.201     brouard  6312:     } /* k1 */
                   6313:   } /* cpt */
1.235     brouard  6314: 
                   6315:   
1.126     brouard  6316:   /*2 eme*/
1.236   ! brouard  6317:   for (k1=1; k1<= m ; k1 ++)  
        !          6318:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6319:     if(TKresult[nres]!= k1)
        !          6320:       continue;
1.223     brouard  6321:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.225     brouard  6322:     for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6323:       lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6324:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6325:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6326:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6327:       vlv= nbcode[Tvaraff[k]][lv];
                   6328:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.236   ! brouard  6329:     }
        !          6330:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6331:       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6332:       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.223     brouard  6333:     }
                   6334:     fprintf(ficgp,"\n#\n");
                   6335:     if(invalidvarcomb[k1]){
                   6336:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6337:       continue;
                   6338:     }
1.219     brouard  6339:                        
1.223     brouard  6340:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   6341:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6342:       if(vpopbased==0)
                   6343:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6344:       else
                   6345:        fprintf(ficgp,"\nreplot ");
                   6346:       for (i=1; i<= nlstate+1 ; i ++) {
                   6347:        k=2*i;
                   6348:        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);
                   6349:        for (j=1; j<= nlstate+1 ; j ++) {
                   6350:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6351:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6352:        }   
                   6353:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6354:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6355:        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);
                   6356:        for (j=1; j<= nlstate+1 ; j ++) {
                   6357:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6358:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6359:        }   
                   6360:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6361:        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);
                   6362:        for (j=1; j<= nlstate+1 ; j ++) {
                   6363:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6364:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6365:        }   
                   6366:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6367:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6368:       } /* state */
                   6369:     } /* vpopbased */
                   6370:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.235     brouard  6371:   } /* k1 end 2 eme*/
1.219     brouard  6372:        
                   6373:        
1.126     brouard  6374:   /*3eme*/
1.236   ! brouard  6375:   for (k1=1; k1<= m ; k1 ++) 
        !          6376:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6377:     if(TKresult[nres]!= k)
        !          6378:       continue;
1.220     brouard  6379: 
1.126     brouard  6380:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.236   ! brouard  6381:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.225     brouard  6382:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6383:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6384:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6385:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6386:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6387:        vlv= nbcode[Tvaraff[k]][lv];
                   6388:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6389:       }
1.236   ! brouard  6390:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6391:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6392:       }        
1.211     brouard  6393:       fprintf(ficgp,"\n#\n");
1.223     brouard  6394:       if(invalidvarcomb[k1]){
                   6395:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6396:        continue;
                   6397:       }
1.219     brouard  6398:                        
1.126     brouard  6399:       /*       k=2+nlstate*(2*cpt-2); */
                   6400:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  6401:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  6402:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6403: 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  6404:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.223     brouard  6405:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6406:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6407:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6408:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6409:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6410:                                
1.126     brouard  6411:       */
                   6412:       for (i=1; i< nlstate ; i ++) {
1.223     brouard  6413:        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);
                   6414:        /*      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);*/
1.219     brouard  6415:                                
1.126     brouard  6416:       } 
1.201     brouard  6417:       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  6418:     }
                   6419:   }
                   6420:   
1.223     brouard  6421:   /* 4eme */
1.201     brouard  6422:   /* Survival functions (period) from state i in state j by initial state i */
1.236   ! brouard  6423:   for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          6424:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
        !          6425:     if(TKresult[nres]!= k)
        !          6426:       continue;
1.220     brouard  6427: 
1.201     brouard  6428:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  6429:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
1.225     brouard  6430:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6431:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6432:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6433:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6434:        vlv= nbcode[Tvaraff[k]][lv];
                   6435:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6436:       }
1.236   ! brouard  6437:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6438:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6439:       }        
1.211     brouard  6440:       fprintf(ficgp,"\n#\n");
1.223     brouard  6441:       if(invalidvarcomb[k1]){
                   6442:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6443:        continue;
                   6444:       }
1.220     brouard  6445:                        
1.201     brouard  6446:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   6447:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  6448: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6449: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  6450: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6451:       k=3;
1.201     brouard  6452:       for (i=1; i<= nlstate ; i ++){
1.223     brouard  6453:        if(i==1){
                   6454:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6455:        }else{
                   6456:          fprintf(ficgp,", '' ");
                   6457:        }
                   6458:        l=(nlstate+ndeath)*(i-1)+1;
                   6459:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6460:        for (j=2; j<= nlstate+ndeath ; j ++)
                   6461:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6462:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
1.201     brouard  6463:       } /* nlstate */
                   6464:       fprintf(ficgp,"\nset out\n");
                   6465:     } /* end cpt state*/ 
                   6466:   } /* end covariate */  
1.220     brouard  6467:        
                   6468: /* 5eme */
1.201     brouard  6469:   /* Survival functions (period) from state i in state j by final state j */
1.236   ! brouard  6470:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
        !          6471:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6472:     if(TKresult[nres]!= k1)
        !          6473:       continue;
1.201     brouard  6474:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.223     brouard  6475:                        
1.201     brouard  6476:       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.225     brouard  6477:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6478:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6479:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6480:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6481:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6482:        vlv= nbcode[Tvaraff[k]][lv];
                   6483:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6484:       }
1.236   ! brouard  6485:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6486:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6487:       }        
1.211     brouard  6488:       fprintf(ficgp,"\n#\n");
1.223     brouard  6489:       if(invalidvarcomb[k1]){
1.227     brouard  6490:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6491:        continue;
1.223     brouard  6492:       }
1.227     brouard  6493:       
1.201     brouard  6494:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   6495:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.227     brouard  6496: set ter svg size 640, 480\n                                            \
                   6497: unset log y\n                                                          \
1.201     brouard  6498: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6499:       k=3;
1.201     brouard  6500:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.227     brouard  6501:        if(j==1)
                   6502:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6503:        else
                   6504:          fprintf(ficgp,", '' ");
                   6505:        l=(nlstate+ndeath)*(cpt-1) +j;
                   6506:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6507:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6508:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6509:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.201     brouard  6510:       } /* nlstate */
                   6511:       fprintf(ficgp,", '' ");
                   6512:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6513:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.227     brouard  6514:        l=(nlstate+ndeath)*(cpt-1) +j;
                   6515:        if(j < nlstate)
                   6516:          fprintf(ficgp,"$%d +",k+l);
                   6517:        else
                   6518:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.201     brouard  6519:       }
                   6520:       fprintf(ficgp,"\nset out\n");
                   6521:     } /* end cpt state*/ 
                   6522:   } /* end covariate */  
1.227     brouard  6523:   
1.220     brouard  6524: /* 6eme */
1.202     brouard  6525:   /* CV preval stable (period) for each covariate */
1.211     brouard  6526:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  6527:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6528:       
1.211     brouard  6529:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6530:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6531:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6532:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6533:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6534:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6535:        vlv= nbcode[Tvaraff[k]][lv];
                   6536:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6537:       }
                   6538:       fprintf(ficgp,"\n#\n");
1.223     brouard  6539:       if(invalidvarcomb[k1]){
1.227     brouard  6540:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6541:        continue;
1.223     brouard  6542:       }
1.227     brouard  6543:       
1.201     brouard  6544:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6545:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.227     brouard  6546: set ter svg size 640, 480\n                                            \
                   6547: unset log y\n                                                          \
1.153     brouard  6548: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6549:       k=3; /* Offset */
1.153     brouard  6550:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6551:        if(i==1)
                   6552:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6553:        else
                   6554:          fprintf(ficgp,", '' ");
                   6555:        l=(nlstate+ndeath)*(i-1)+1;
                   6556:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6557:        for (j=2; j<= nlstate ; j ++)
                   6558:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6559:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6560:       } /* nlstate */
1.201     brouard  6561:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6562:     } /* end cpt state*/ 
                   6563:   } /* end covariate */  
1.227     brouard  6564:   
                   6565:   
1.220     brouard  6566: /* 7eme */
1.218     brouard  6567:   if(backcast == 1){
1.217     brouard  6568:     /* CV back preval stable (period) for each covariate */
1.218     brouard  6569:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6570:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6571:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6572:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6573:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6574:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6575:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6576:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6577:          vlv= nbcode[Tvaraff[k]][lv];
                   6578:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6579:        }
                   6580:        fprintf(ficgp,"\n#\n");
                   6581:        if(invalidvarcomb[k1]){
                   6582:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6583:          continue;
                   6584:        }
                   6585:        
                   6586:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6587:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   6588: set ter svg size 640, 480\n                                            \
                   6589: unset log y\n                                                          \
1.218     brouard  6590: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6591:        k=3; /* Offset */
                   6592:        for (i=1; i<= nlstate ; i ++){
                   6593:          if(i==1)
                   6594:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6595:          else
                   6596:            fprintf(ficgp,", '' ");
                   6597:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6598:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6599:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6600:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6601:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6602:          /* for (j=2; j<= nlstate ; j ++) */
                   6603:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6604:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6605:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6606:        } /* nlstate */
                   6607:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6608:       } /* end cpt state*/ 
                   6609:     } /* end covariate */  
                   6610:   } /* End if backcast */
                   6611:   
1.223     brouard  6612:   /* 8eme */
1.218     brouard  6613:   if(prevfcast==1){
                   6614:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6615:     
                   6616:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  6617:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6618:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6619:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6620:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6621:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6622:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6623:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6624:          vlv= nbcode[Tvaraff[k]][lv];
                   6625:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6626:        }
                   6627:        fprintf(ficgp,"\n#\n");
                   6628:        if(invalidvarcomb[k1]){
                   6629:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6630:          continue;
                   6631:        }
                   6632:        
                   6633:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6634:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6635:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   6636: set ter svg size 640, 480\n                                            \
                   6637: unset log y\n                                                          \
1.219     brouard  6638: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6639:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6640:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6641:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6642:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6643:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6644:          if(i==1){
                   6645:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6646:          }else{
                   6647:            fprintf(ficgp,",\\\n '' ");
                   6648:          }
                   6649:          if(cptcoveff ==0){ /* No covariate */
                   6650:            ioffset=2; /* Age is in 2 */
                   6651:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6652:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6653:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6654:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6655:            fprintf(ficgp," u %d:(", ioffset); 
                   6656:            if(i==nlstate+1)
                   6657:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6658:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6659:            else
                   6660:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6661:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6662:          }else{ /* more than 2 covariates */
                   6663:            if(cptcoveff ==1){
                   6664:              ioffset=4; /* Age is in 4 */
                   6665:            }else{
                   6666:              ioffset=6; /* Age is in 6 */
                   6667:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6668:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6669:            }   
                   6670:            fprintf(ficgp," u %d:(",ioffset); 
                   6671:            kl=0;
                   6672:            strcpy(gplotcondition,"(");
                   6673:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6674:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6675:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6676:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6677:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6678:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6679:              kl++;
                   6680:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6681:              kl++;
                   6682:              if(k <cptcoveff && cptcoveff>1)
                   6683:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6684:            }
                   6685:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6686:            /* 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 *\/ */
                   6687:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6688:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6689:            /* ''  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*/
                   6690:            if(i==nlstate+1){
                   6691:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6692:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6693:            }else{
                   6694:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6695:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6696:            }
                   6697:          } /* end if covariate */
                   6698:        } /* nlstate */
                   6699:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6700:       } /* end cpt state*/
                   6701:     } /* end covariate */
                   6702:   } /* End if prevfcast */
1.227     brouard  6703:   
                   6704:   
1.223     brouard  6705:   /* proba elementaires */
                   6706:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6707:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6708:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6709:     for(k=1; k <=(nlstate+ndeath); k++){
                   6710:       if (k != i) {
1.227     brouard  6711:        fprintf(ficgp,"#   current state %d\n",k);
                   6712:        for(j=1; j <=ncovmodel; j++){
                   6713:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6714:          jk++; 
                   6715:        }
                   6716:        fprintf(ficgp,"\n");
1.126     brouard  6717:       }
                   6718:     }
1.223     brouard  6719:   }
1.187     brouard  6720:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6721:   
1.145     brouard  6722:   /*goto avoid;*/
1.200     brouard  6723:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6724:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6725:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6726:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6727:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6728:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6729:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6730:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6731:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6732:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6733:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6734:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6735:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6736:   fprintf(ficgp,"#\n");
1.223     brouard  6737:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
                   6738:     fprintf(ficgp,"# ng=%d\n",ng);
1.225     brouard  6739:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.223     brouard  6740:     for(jk=1; jk <=m; jk++) {
                   6741:       fprintf(ficgp,"#    jk=%d\n",jk);
                   6742:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6743:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6744:       if (ng==1){
                   6745:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6746:        fprintf(ficgp,"\nunset log y");
                   6747:       }else if (ng==2){
                   6748:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6749:        fprintf(ficgp,"\nset log y");
                   6750:       }else if (ng==3){
                   6751:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6752:        fprintf(ficgp,"\nset log y");
                   6753:       }else
                   6754:        fprintf(ficgp,"\nunset title ");
                   6755:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6756:       i=1;
                   6757:       for(k2=1; k2<=nlstate; k2++) {
                   6758:        k3=i;
                   6759:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6760:          if (k != k2){
                   6761:            switch( ng) {
                   6762:            case 1:
                   6763:              if(nagesqr==0)
                   6764:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6765:              else /* nagesqr =1 */
                   6766:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6767:              break;
                   6768:            case 2: /* ng=2 */
                   6769:              if(nagesqr==0)
                   6770:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6771:              else /* nagesqr =1 */
                   6772:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6773:              break;
                   6774:            case 3:
                   6775:              if(nagesqr==0)
                   6776:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6777:              else /* nagesqr =1 */
                   6778:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6779:              break;
                   6780:            }
                   6781:            ij=1;/* To be checked else nbcode[0][0] wrong */
                   6782:            for(j=3; j <=ncovmodel-nagesqr; j++) {
                   6783:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6784:              if(ij <=cptcovage) { /* Bug valgrind */
                   6785:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6786:                  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6787:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6788:                  ij++;
                   6789:                }
                   6790:              }
                   6791:              else
1.227     brouard  6792:                fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]); /* Valgrind bug nbcode */
1.223     brouard  6793:            }
                   6794:          }else{
                   6795:            i=i-ncovmodel;
                   6796:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6797:              fprintf(ficgp," (1.");
                   6798:          }
1.227     brouard  6799:          
1.223     brouard  6800:          if(ng != 1){
                   6801:            fprintf(ficgp,")/(1");
1.227     brouard  6802:            
1.223     brouard  6803:            for(k1=1; k1 <=nlstate; k1++){ 
                   6804:              if(nagesqr==0)
                   6805:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6806:              else /* nagesqr =1 */
                   6807:                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);
1.217     brouard  6808:               
1.223     brouard  6809:              ij=1;
                   6810:              for(j=3; j <=ncovmodel-nagesqr; j++){
                   6811:                if(ij <=cptcovage) { /* Bug valgrind */
                   6812:                  if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6813:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6814:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6815:                    ij++;
                   6816:                  }
                   6817:                }
                   6818:                else
1.225     brouard  6819:                  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
1.223     brouard  6820:              }
                   6821:              fprintf(ficgp,")");
                   6822:            }
                   6823:            fprintf(ficgp,")");
                   6824:            if(ng ==2)
                   6825:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6826:            else /* ng= 3 */
                   6827:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6828:          }else{ /* end ng <> 1 */
                   6829:            if( k !=k2) /* logit p11 is hard to draw */
                   6830:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   6831:          }
                   6832:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6833:            fprintf(ficgp,",");
                   6834:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6835:            fprintf(ficgp,",");
                   6836:          i=i+ncovmodel;
                   6837:        } /* end k */
                   6838:       } /* end k2 */
                   6839:       fprintf(ficgp,"\n set out\n");
                   6840:     } /* end jk */
                   6841:   } /* end ng */
                   6842:   /* avoid: */
                   6843:   fflush(ficgp); 
1.126     brouard  6844: }  /* end gnuplot */
                   6845: 
                   6846: 
                   6847: /*************** Moving average **************/
1.219     brouard  6848: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  6849:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  6850:    
1.222     brouard  6851:    int i, cpt, cptcod;
                   6852:    int modcovmax =1;
                   6853:    int mobilavrange, mob;
                   6854:    int iage=0;
                   6855: 
                   6856:    double sum=0.;
                   6857:    double age;
                   6858:    double *sumnewp, *sumnewm;
                   6859:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6860:   
                   6861:   
1.225     brouard  6862:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  6863:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   6864: 
                   6865:    sumnewp = vector(1,ncovcombmax);
                   6866:    sumnewm = vector(1,ncovcombmax);
                   6867:    agemingood = vector(1,ncovcombmax); 
                   6868:    agemaxgood = vector(1,ncovcombmax);
                   6869: 
                   6870:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6871:      sumnewm[cptcod]=0.;
                   6872:      sumnewp[cptcod]=0.;
                   6873:      agemingood[cptcod]=0;
                   6874:      agemaxgood[cptcod]=0;
                   6875:    }
                   6876:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   6877:   
                   6878:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6879:      if(mobilav==1) mobilavrange=5; /* default */
                   6880:      else mobilavrange=mobilav;
                   6881:      for (age=bage; age<=fage; age++)
                   6882:        for (i=1; i<=nlstate;i++)
                   6883:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   6884:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6885:      /* We keep the original values on the extreme ages bage, fage and for 
                   6886:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6887:        we use a 5 terms etc. until the borders are no more concerned. 
                   6888:      */ 
                   6889:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6890:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6891:         for (i=1; i<=nlstate;i++){
                   6892:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6893:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6894:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6895:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6896:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6897:             }
                   6898:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6899:           }
                   6900:         }
                   6901:        }/* end age */
                   6902:      }/* end mob */
                   6903:    }else
                   6904:      return -1;
                   6905:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6906:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   6907:      if(invalidvarcomb[cptcod]){
                   6908:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   6909:        continue;
                   6910:      }
1.219     brouard  6911: 
1.222     brouard  6912:      agemingood[cptcod]=fage-(mob-1)/2;
                   6913:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6914:        sumnewm[cptcod]=0.;
                   6915:        for (i=1; i<=nlstate;i++){
                   6916:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6917:        }
                   6918:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6919:         agemingood[cptcod]=age;
                   6920:        }else{ /* bad */
                   6921:         for (i=1; i<=nlstate;i++){
                   6922:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6923:         } /* i */
                   6924:        } /* end bad */
                   6925:      }/* age */
                   6926:      sum=0.;
                   6927:      for (i=1; i<=nlstate;i++){
                   6928:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6929:      }
                   6930:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6931:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
                   6932:        /* for (i=1; i<=nlstate;i++){ */
                   6933:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6934:        /* } /\* i *\/ */
                   6935:      } /* end bad */
                   6936:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   6937:      /* From youngest, finding the oldest wrong */
                   6938:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   6939:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   6940:        sumnewm[cptcod]=0.;
                   6941:        for (i=1; i<=nlstate;i++){
                   6942:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6943:        }
                   6944:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6945:         agemaxgood[cptcod]=age;
                   6946:        }else{ /* bad */
                   6947:         for (i=1; i<=nlstate;i++){
                   6948:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6949:         } /* i */
                   6950:        } /* end bad */
                   6951:      }/* age */
                   6952:      sum=0.;
                   6953:      for (i=1; i<=nlstate;i++){
                   6954:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6955:      }
                   6956:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6957:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
                   6958:        /* for (i=1; i<=nlstate;i++){ */
                   6959:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6960:        /* } /\* i *\/ */
                   6961:      } /* end bad */
                   6962:                
                   6963:      for (age=bage; age<=fage; age++){
1.235     brouard  6964:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  6965:        sumnewp[cptcod]=0.;
                   6966:        sumnewm[cptcod]=0.;
                   6967:        for (i=1; i<=nlstate;i++){
                   6968:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   6969:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6970:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   6971:        }
                   6972:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   6973:      }
                   6974:      /* printf("\n"); */
                   6975:      /* } */
                   6976:      /* brutal averaging */
                   6977:      for (i=1; i<=nlstate;i++){
                   6978:        for (age=1; age<=bage; age++){
                   6979:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6980:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6981:        }       
                   6982:        for (age=fage; age<=AGESUP; age++){
                   6983:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6984:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6985:        }
                   6986:      } /* end i status */
                   6987:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6988:        for (age=1; age<=AGESUP; age++){
                   6989:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   6990:         mobaverage[(int)age][i][cptcod]=0.;
                   6991:        }
                   6992:      }
                   6993:    }/* end cptcod */
                   6994:    free_vector(sumnewm,1, ncovcombmax);
                   6995:    free_vector(sumnewp,1, ncovcombmax);
                   6996:    free_vector(agemaxgood,1, ncovcombmax);
                   6997:    free_vector(agemingood,1, ncovcombmax);
                   6998:    return 0;
                   6999:  }/* End movingaverage */
1.218     brouard  7000:  
1.126     brouard  7001: 
                   7002: /************** Forecasting ******************/
1.235     brouard  7003:  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  7004:   /* proj1, year, month, day of starting projection 
                   7005:      agemin, agemax range of age
                   7006:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7007:      anproj2 year of en of projection (same day and month as proj1).
                   7008:   */
1.235     brouard  7009:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7010:   double agec; /* generic age */
                   7011:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7012:   double *popeffectif,*popcount;
                   7013:   double ***p3mat;
1.218     brouard  7014:   /* double ***mobaverage; */
1.126     brouard  7015:   char fileresf[FILENAMELENGTH];
                   7016: 
                   7017:   agelim=AGESUP;
1.211     brouard  7018:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7019:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7020:      We still use firstpass and lastpass as another selection.
                   7021:   */
1.214     brouard  7022:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7023:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7024:  
1.201     brouard  7025:   strcpy(fileresf,"F_"); 
                   7026:   strcat(fileresf,fileresu);
1.126     brouard  7027:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7028:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7029:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7030:   }
1.235     brouard  7031:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7032:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7033: 
1.225     brouard  7034:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7035: 
                   7036: 
                   7037:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7038:   if (stepm<=12) stepsize=1;
                   7039:   if(estepm < stepm){
                   7040:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7041:   }
                   7042:   else  hstepm=estepm;   
                   7043: 
                   7044:   hstepm=hstepm/stepm; 
                   7045:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7046:                                fractional in yp1 */
                   7047:   anprojmean=yp;
                   7048:   yp2=modf((yp1*12),&yp);
                   7049:   mprojmean=yp;
                   7050:   yp1=modf((yp2*30.5),&yp);
                   7051:   jprojmean=yp;
                   7052:   if(jprojmean==0) jprojmean=1;
                   7053:   if(mprojmean==0) jprojmean=1;
                   7054: 
1.227     brouard  7055:   i1=pow(2,cptcoveff);
1.126     brouard  7056:   if (cptcovn < 1){i1=1;}
                   7057:   
                   7058:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7059:   
                   7060:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7061:   
1.126     brouard  7062: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7063:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7064:   for(k=1; k<=i1;k++){
                   7065:     if(TKresult[nres]!= k)
                   7066:       continue;
1.227     brouard  7067:     if(invalidvarcomb[k]){
                   7068:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7069:       continue;
                   7070:     }
                   7071:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7072:     for(j=1;j<=cptcoveff;j++) {
                   7073:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7074:     }
1.235     brouard  7075:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7076:       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7077:       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7078:     }
1.227     brouard  7079:     fprintf(ficresf," yearproj age");
                   7080:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7081:       for(i=1; i<=nlstate;i++)               
                   7082:        fprintf(ficresf," p%d%d",i,j);
                   7083:       fprintf(ficresf," wp.%d",j);
                   7084:     }
                   7085:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7086:       fprintf(ficresf,"\n");
                   7087:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7088:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7089:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7090:        nhstepm = nhstepm/hstepm; 
                   7091:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7092:        oldm=oldms;savm=savms;
1.235     brouard  7093:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7094:        
                   7095:        for (h=0; h<=nhstepm; h++){
                   7096:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7097:            fprintf(ficresf,"\n");
                   7098:            for(j=1;j<=cptcoveff;j++) 
                   7099:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7100:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7101:          } 
                   7102:          for(j=1; j<=nlstate+ndeath;j++) {
                   7103:            ppij=0.;
                   7104:            for(i=1; i<=nlstate;i++) {
                   7105:              if (mobilav==1) 
                   7106:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7107:              else {
                   7108:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7109:              }
                   7110:              if (h*hstepm/YEARM*stepm== yearp) {
                   7111:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7112:              }
                   7113:            } /* end i */
                   7114:            if (h*hstepm/YEARM*stepm==yearp) {
                   7115:              fprintf(ficresf," %.3f", ppij);
                   7116:            }
                   7117:          }/* end j */
                   7118:        } /* end h */
                   7119:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7120:       } /* end agec */
                   7121:     } /* end yearp */
                   7122:   } /* end  k */
1.219     brouard  7123:        
1.126     brouard  7124:   fclose(ficresf);
1.215     brouard  7125:   printf("End of Computing forecasting \n");
                   7126:   fprintf(ficlog,"End of Computing forecasting\n");
                   7127: 
1.126     brouard  7128: }
                   7129: 
1.218     brouard  7130: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7131: /* 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){ */
1.218     brouard  7132: /*   /\* back1, year, month, day of starting backection  */
                   7133: /*      agemin, agemax range of age */
                   7134: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7135: /*      anback2 year of en of backection (same day and month as back1). */
                   7136: /*   *\/ */
                   7137: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7138: /*   double agec; /\* generic age *\/ */
                   7139: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7140: /*   double *popeffectif,*popcount; */
                   7141: /*   double ***p3mat; */
                   7142: /*   /\* double ***mobaverage; *\/ */
                   7143: /*   char fileresfb[FILENAMELENGTH]; */
                   7144:        
                   7145: /*   agelim=AGESUP; */
                   7146: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7147: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7148: /*      We still use firstpass and lastpass as another selection. */
                   7149: /*   *\/ */
                   7150: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7151: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7152: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7153:        
                   7154: /*   strcpy(fileresfb,"FB_");  */
                   7155: /*   strcat(fileresfb,fileresu); */
                   7156: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7157: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7158: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7159: /*   } */
                   7160: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7161: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7162:        
1.225     brouard  7163: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7164:        
                   7165: /*   /\* if (mobilav!=0) { *\/ */
                   7166: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7167: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7168: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7169: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7170: /*   /\*   } *\/ */
                   7171: /*   /\* } *\/ */
                   7172:        
                   7173: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7174: /*   if (stepm<=12) stepsize=1; */
                   7175: /*   if(estepm < stepm){ */
                   7176: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7177: /*   } */
                   7178: /*   else  hstepm=estepm;    */
                   7179:        
                   7180: /*   hstepm=hstepm/stepm;  */
                   7181: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7182: /*                                fractional in yp1 *\/ */
                   7183: /*   anprojmean=yp; */
                   7184: /*   yp2=modf((yp1*12),&yp); */
                   7185: /*   mprojmean=yp; */
                   7186: /*   yp1=modf((yp2*30.5),&yp); */
                   7187: /*   jprojmean=yp; */
                   7188: /*   if(jprojmean==0) jprojmean=1; */
                   7189: /*   if(mprojmean==0) jprojmean=1; */
                   7190:        
1.225     brouard  7191: /*   i1=cptcoveff; */
1.218     brouard  7192: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7193:   
1.218     brouard  7194: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7195:   
1.218     brouard  7196: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7197:        
                   7198: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7199: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7200: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7201: /*       k=k+1; */
                   7202: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7203: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7204: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7205: /*       } */
                   7206: /*       fprintf(ficresfb," yearbproj age"); */
                   7207: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7208: /*                             for(i=1; i<=nlstate;i++)               */
                   7209: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7210: /*                             fprintf(ficresfb," p.%d",j); */
                   7211: /*       } */
                   7212: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7213: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7214: /*                             fprintf(ficresfb,"\n"); */
                   7215: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7216: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7217: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7218: /*                                     nhstepm = nhstepm/hstepm;  */
                   7219: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7220: /*                                     oldm=oldms;savm=savms; */
                   7221: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7222: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7223: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7224: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7225: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7226: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7227: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7228: /*                                             }  */
                   7229: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7230: /*                                                     ppij=0.; */
                   7231: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7232: /*                                                             if (mobilav==1)  */
                   7233: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7234: /*                                                             else { */
                   7235: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7236: /*                                                             } */
                   7237: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7238: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7239: /*                                                             } */
                   7240: /*                                                     } /\* end i *\/ */
                   7241: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7242: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7243: /*                                                     } */
                   7244: /*                                             }/\* end j *\/ */
                   7245: /*                                     } /\* end h *\/ */
                   7246: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7247: /*                             } /\* end agec *\/ */
                   7248: /*       } /\* end yearp *\/ */
                   7249: /*     } /\* end cptcod *\/ */
                   7250: /*   } /\* end  cptcov *\/ */
                   7251:        
                   7252: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7253:        
                   7254: /*   fclose(ficresfb); */
                   7255: /*   printf("End of Computing Back forecasting \n"); */
                   7256: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7257:        
1.218     brouard  7258: /* } */
1.217     brouard  7259: 
1.126     brouard  7260: /************** Forecasting *****not tested NB*************/
1.227     brouard  7261: /* void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2s, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){ */
1.126     brouard  7262:   
1.227     brouard  7263: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7264: /*   int *popage; */
                   7265: /*   double calagedatem, agelim, kk1, kk2; */
                   7266: /*   double *popeffectif,*popcount; */
                   7267: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7268: /*   /\* double ***mobaverage; *\/ */
                   7269: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7270: 
1.227     brouard  7271: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7272: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7273: /*   agelim=AGESUP; */
                   7274: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7275:   
1.227     brouard  7276: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7277:   
                   7278:   
1.227     brouard  7279: /*   strcpy(filerespop,"POP_");  */
                   7280: /*   strcat(filerespop,fileresu); */
                   7281: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7282: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7283: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7284: /*   } */
                   7285: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7286: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7287: 
1.227     brouard  7288: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7289: 
1.227     brouard  7290: /*   /\* if (mobilav!=0) { *\/ */
                   7291: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7292: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7293: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7294: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7295: /*   /\*   } *\/ */
                   7296: /*   /\* } *\/ */
1.126     brouard  7297: 
1.227     brouard  7298: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7299: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7300:   
1.227     brouard  7301: /*   agelim=AGESUP; */
1.126     brouard  7302:   
1.227     brouard  7303: /*   hstepm=1; */
                   7304: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7305:        
1.227     brouard  7306: /*   if (popforecast==1) { */
                   7307: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7308: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7309: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7310: /*     }  */
                   7311: /*     popage=ivector(0,AGESUP); */
                   7312: /*     popeffectif=vector(0,AGESUP); */
                   7313: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7314:     
1.227     brouard  7315: /*     i=1;    */
                   7316: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7317:     
1.227     brouard  7318: /*     imx=i; */
                   7319: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7320: /*   } */
1.218     brouard  7321:   
1.227     brouard  7322: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7323: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7324: /*       k=k+1; */
                   7325: /*       fprintf(ficrespop,"\n#******"); */
                   7326: /*       for(j=1;j<=cptcoveff;j++) { */
                   7327: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7328: /*       } */
                   7329: /*       fprintf(ficrespop,"******\n"); */
                   7330: /*       fprintf(ficrespop,"# Age"); */
                   7331: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7332: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7333:       
1.227     brouard  7334: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7335: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7336:        
1.227     brouard  7337: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7338: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7339: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7340:          
1.227     brouard  7341: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7342: /*       oldm=oldms;savm=savms; */
                   7343: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7344:          
1.227     brouard  7345: /*       for (h=0; h<=nhstepm; h++){ */
                   7346: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7347: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7348: /*         }  */
                   7349: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7350: /*           kk1=0.;kk2=0; */
                   7351: /*           for(i=1; i<=nlstate;i++) {               */
                   7352: /*             if (mobilav==1)  */
                   7353: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7354: /*             else { */
                   7355: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7356: /*             } */
                   7357: /*           } */
                   7358: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7359: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7360: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7361: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7362: /*           } */
                   7363: /*         } */
                   7364: /*         for(i=1; i<=nlstate;i++){ */
                   7365: /*           kk1=0.; */
                   7366: /*           for(j=1; j<=nlstate;j++){ */
                   7367: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7368: /*           } */
                   7369: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7370: /*         } */
1.218     brouard  7371:            
1.227     brouard  7372: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7373: /*           for(j=1; j<=nlstate;j++)  */
                   7374: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7375: /*       } */
                   7376: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7377: /*     } */
                   7378: /*       } */
1.218     brouard  7379:       
1.227     brouard  7380: /*       /\******\/ */
1.218     brouard  7381:       
1.227     brouard  7382: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7383: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7384: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7385: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7386: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7387:          
1.227     brouard  7388: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7389: /*       oldm=oldms;savm=savms; */
                   7390: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7391: /*       for (h=0; h<=nhstepm; h++){ */
                   7392: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7393: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7394: /*         }  */
                   7395: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7396: /*           kk1=0.;kk2=0; */
                   7397: /*           for(i=1; i<=nlstate;i++) {               */
                   7398: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7399: /*           } */
                   7400: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7401: /*         } */
                   7402: /*       } */
                   7403: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7404: /*     } */
                   7405: /*       } */
                   7406: /*     }  */
                   7407: /*   } */
1.218     brouard  7408:   
1.227     brouard  7409: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7410:   
1.227     brouard  7411: /*   if (popforecast==1) { */
                   7412: /*     free_ivector(popage,0,AGESUP); */
                   7413: /*     free_vector(popeffectif,0,AGESUP); */
                   7414: /*     free_vector(popcount,0,AGESUP); */
                   7415: /*   } */
                   7416: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7417: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7418: /*   fclose(ficrespop); */
                   7419: /* } /\* End of popforecast *\/ */
1.218     brouard  7420:  
1.126     brouard  7421: int fileappend(FILE *fichier, char *optionfich)
                   7422: {
                   7423:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7424:     printf("Problem with file: %s\n", optionfich);
                   7425:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7426:     return (0);
                   7427:   }
                   7428:   fflush(fichier);
                   7429:   return (1);
                   7430: }
                   7431: 
                   7432: 
                   7433: /**************** function prwizard **********************/
                   7434: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7435: {
                   7436: 
                   7437:   /* Wizard to print covariance matrix template */
                   7438: 
1.164     brouard  7439:   char ca[32], cb[32];
                   7440:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7441:   int numlinepar;
                   7442: 
                   7443:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7444:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7445:   for(i=1; i <=nlstate; i++){
                   7446:     jj=0;
                   7447:     for(j=1; j <=nlstate+ndeath; j++){
                   7448:       if(j==i) continue;
                   7449:       jj++;
                   7450:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7451:       printf("%1d%1d",i,j);
                   7452:       fprintf(ficparo,"%1d%1d",i,j);
                   7453:       for(k=1; k<=ncovmodel;k++){
                   7454:        /*        printf(" %lf",param[i][j][k]); */
                   7455:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7456:        printf(" 0.");
                   7457:        fprintf(ficparo," 0.");
                   7458:       }
                   7459:       printf("\n");
                   7460:       fprintf(ficparo,"\n");
                   7461:     }
                   7462:   }
                   7463:   printf("# Scales (for hessian or gradient estimation)\n");
                   7464:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7465:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7466:   for(i=1; i <=nlstate; i++){
                   7467:     jj=0;
                   7468:     for(j=1; j <=nlstate+ndeath; j++){
                   7469:       if(j==i) continue;
                   7470:       jj++;
                   7471:       fprintf(ficparo,"%1d%1d",i,j);
                   7472:       printf("%1d%1d",i,j);
                   7473:       fflush(stdout);
                   7474:       for(k=1; k<=ncovmodel;k++){
                   7475:        /*      printf(" %le",delti3[i][j][k]); */
                   7476:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7477:        printf(" 0.");
                   7478:        fprintf(ficparo," 0.");
                   7479:       }
                   7480:       numlinepar++;
                   7481:       printf("\n");
                   7482:       fprintf(ficparo,"\n");
                   7483:     }
                   7484:   }
                   7485:   printf("# Covariance matrix\n");
                   7486: /* # 121 Var(a12)\n\ */
                   7487: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7488: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7489: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7490: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7491: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7492: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7493: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7494:   fflush(stdout);
                   7495:   fprintf(ficparo,"# Covariance matrix\n");
                   7496:   /* # 121 Var(a12)\n\ */
                   7497:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7498:   /* #   ...\n\ */
                   7499:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7500:   
                   7501:   for(itimes=1;itimes<=2;itimes++){
                   7502:     jj=0;
                   7503:     for(i=1; i <=nlstate; i++){
                   7504:       for(j=1; j <=nlstate+ndeath; j++){
                   7505:        if(j==i) continue;
                   7506:        for(k=1; k<=ncovmodel;k++){
                   7507:          jj++;
                   7508:          ca[0]= k+'a'-1;ca[1]='\0';
                   7509:          if(itimes==1){
                   7510:            printf("#%1d%1d%d",i,j,k);
                   7511:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7512:          }else{
                   7513:            printf("%1d%1d%d",i,j,k);
                   7514:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7515:            /*  printf(" %.5le",matcov[i][j]); */
                   7516:          }
                   7517:          ll=0;
                   7518:          for(li=1;li <=nlstate; li++){
                   7519:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7520:              if(lj==li) continue;
                   7521:              for(lk=1;lk<=ncovmodel;lk++){
                   7522:                ll++;
                   7523:                if(ll<=jj){
                   7524:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7525:                  if(ll<jj){
                   7526:                    if(itimes==1){
                   7527:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7528:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7529:                    }else{
                   7530:                      printf(" 0.");
                   7531:                      fprintf(ficparo," 0.");
                   7532:                    }
                   7533:                  }else{
                   7534:                    if(itimes==1){
                   7535:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7536:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7537:                    }else{
                   7538:                      printf(" 0.");
                   7539:                      fprintf(ficparo," 0.");
                   7540:                    }
                   7541:                  }
                   7542:                }
                   7543:              } /* end lk */
                   7544:            } /* end lj */
                   7545:          } /* end li */
                   7546:          printf("\n");
                   7547:          fprintf(ficparo,"\n");
                   7548:          numlinepar++;
                   7549:        } /* end k*/
                   7550:       } /*end j */
                   7551:     } /* end i */
                   7552:   } /* end itimes */
                   7553: 
                   7554: } /* end of prwizard */
                   7555: /******************* Gompertz Likelihood ******************************/
                   7556: double gompertz(double x[])
                   7557: { 
                   7558:   double A,B,L=0.0,sump=0.,num=0.;
                   7559:   int i,n=0; /* n is the size of the sample */
                   7560: 
1.220     brouard  7561:   for (i=1;i<=imx ; i++) {
1.126     brouard  7562:     sump=sump+weight[i];
                   7563:     /*    sump=sump+1;*/
                   7564:     num=num+1;
                   7565:   }
                   7566:  
                   7567:  
                   7568:   /* for (i=0; i<=imx; i++) 
                   7569:      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]);*/
                   7570: 
                   7571:   for (i=1;i<=imx ; i++)
                   7572:     {
                   7573:       if (cens[i] == 1 && wav[i]>1)
                   7574:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7575:       
                   7576:       if (cens[i] == 0 && wav[i]>1)
                   7577:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7578:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7579:       
                   7580:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7581:       if (wav[i] > 1 ) { /* ??? */
                   7582:        L=L+A*weight[i];
                   7583:        /*      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]);*/
                   7584:       }
                   7585:     }
                   7586: 
                   7587:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7588:  
                   7589:   return -2*L*num/sump;
                   7590: }
                   7591: 
1.136     brouard  7592: #ifdef GSL
                   7593: /******************* Gompertz_f Likelihood ******************************/
                   7594: double gompertz_f(const gsl_vector *v, void *params)
                   7595: { 
                   7596:   double A,B,LL=0.0,sump=0.,num=0.;
                   7597:   double *x= (double *) v->data;
                   7598:   int i,n=0; /* n is the size of the sample */
                   7599: 
                   7600:   for (i=0;i<=imx-1 ; i++) {
                   7601:     sump=sump+weight[i];
                   7602:     /*    sump=sump+1;*/
                   7603:     num=num+1;
                   7604:   }
                   7605:  
                   7606:  
                   7607:   /* for (i=0; i<=imx; i++) 
                   7608:      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]);*/
                   7609:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7610:   for (i=1;i<=imx ; i++)
                   7611:     {
                   7612:       if (cens[i] == 1 && wav[i]>1)
                   7613:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7614:       
                   7615:       if (cens[i] == 0 && wav[i]>1)
                   7616:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7617:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7618:       
                   7619:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7620:       if (wav[i] > 1 ) { /* ??? */
                   7621:        LL=LL+A*weight[i];
                   7622:        /*      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]);*/
                   7623:       }
                   7624:     }
                   7625: 
                   7626:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7627:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7628:  
                   7629:   return -2*LL*num/sump;
                   7630: }
                   7631: #endif
                   7632: 
1.126     brouard  7633: /******************* Printing html file ***********/
1.201     brouard  7634: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7635:                  int lastpass, int stepm, int weightopt, char model[],\
                   7636:                  int imx,  double p[],double **matcov,double agemortsup){
                   7637:   int i,k;
                   7638: 
                   7639:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7640:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7641:   for (i=1;i<=2;i++) 
                   7642:     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  7643:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7644:   fprintf(fichtm,"</ul>");
                   7645: 
                   7646: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7647: 
                   7648:  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>");
                   7649: 
                   7650:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7651:    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]);
                   7652: 
                   7653:  
                   7654:   fflush(fichtm);
                   7655: }
                   7656: 
                   7657: /******************* Gnuplot file **************/
1.201     brouard  7658: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7659: 
                   7660:   char dirfileres[132],optfileres[132];
1.164     brouard  7661: 
1.126     brouard  7662:   int ng;
                   7663: 
                   7664: 
                   7665:   /*#ifdef windows */
                   7666:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7667:     /*#endif */
                   7668: 
                   7669: 
                   7670:   strcpy(dirfileres,optionfilefiname);
                   7671:   strcpy(optfileres,"vpl");
1.199     brouard  7672:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7673:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7674:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7675:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7676:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7677: 
                   7678: } 
                   7679: 
1.136     brouard  7680: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7681: {
1.126     brouard  7682: 
1.136     brouard  7683:   /*-------- data file ----------*/
                   7684:   FILE *fic;
                   7685:   char dummy[]="                         ";
1.223     brouard  7686:   int i=0, j=0, n=0, iv=0;
                   7687:   int lstra;
1.136     brouard  7688:   int linei, month, year,iout;
                   7689:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7690:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7691:   char *stratrunc;
1.223     brouard  7692: 
1.126     brouard  7693: 
                   7694: 
1.136     brouard  7695:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7696:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7697:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7698:   }
1.126     brouard  7699: 
1.136     brouard  7700:   i=1;
                   7701:   linei=0;
                   7702:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7703:     linei=linei+1;
                   7704:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7705:       if(line[j] == '\t')
                   7706:        line[j] = ' ';
                   7707:     }
                   7708:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7709:       ;
                   7710:     };
                   7711:     line[j+1]=0;  /* Trims blanks at end of line */
                   7712:     if(line[0]=='#'){
                   7713:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7714:       printf("Comment line\n%s\n",line);
                   7715:       continue;
                   7716:     }
                   7717:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7718:     strcpy(line, linetmp);
1.223     brouard  7719:     
                   7720:     /* Loops on waves */
                   7721:     for (j=maxwav;j>=1;j--){
                   7722:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.232     brouard  7723:                                cutv(stra, strb, line, ' '); 
                   7724:                                if(strb[0]=='.') { /* Missing value */
                   7725:                                        lval=-1;
                   7726:                                        cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   7727:                                        cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   7728:                                        if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   7729:                                                printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);
                   7730:                                                fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
                   7731:                                                return 1;
                   7732:                                        }
                   7733:                                }else{
                   7734:                                        errno=0;
                   7735:                                        /* what_kind_of_number(strb); */
                   7736:                                        dval=strtod(strb,&endptr); 
                   7737:                                        /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7738:                                        /* if(strb != endptr && *endptr == '\0') */
                   7739:                                        /*    dval=dlval; */
                   7740:                                        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7741:                                        if( strb[0]=='\0' || (*endptr != '\0')){
                   7742:                                                printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
                   7743:                                                fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
                   7744:                                                return 1;
                   7745:                                        }
                   7746:                                        cotqvar[j][iv][i]=dval; 
                   7747:                                        cotvar[j][ntv+iv][i]=dval; 
                   7748:                                }
                   7749:                                strcpy(line,stra);
1.223     brouard  7750:       }/* end loop ntqv */
1.225     brouard  7751:       
1.223     brouard  7752:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.232     brouard  7753:                                cutv(stra, strb, line, ' '); 
                   7754:                                if(strb[0]=='.') { /* Missing value */
                   7755:                                        lval=-1;
                   7756:                                }else{
                   7757:                                        errno=0;
                   7758:                                        lval=strtol(strb,&endptr,10); 
                   7759:                                        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7760:                                        if( strb[0]=='\0' || (*endptr != '\0')){
                   7761:                                                printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th dummy covariate out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv, j,maxwav);
                   7762:                                                fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d dummy covariate out of %d measured wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv,j,maxwav);fflush(ficlog);
                   7763:                                                return 1;
                   7764:                                        }
                   7765:                                }
                   7766:                                if(lval <-1 || lval >1){
                   7767:                                        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7768:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7769:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.232     brouard  7770:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
                   7771:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
                   7772:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
1.223     brouard  7773:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.232     brouard  7774:  output of IMaCh is often meaningless.\n                                                                                                                               \
1.223     brouard  7775:  Exiting.\n",lval,linei, i,line,j);
1.232     brouard  7776:                                        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7777:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7778:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.232     brouard  7779:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
                   7780:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
                   7781:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
1.223     brouard  7782:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.232     brouard  7783:  output of IMaCh is often meaningless.\n                                                                                                                               \
1.223     brouard  7784:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.232     brouard  7785:                                        return 1;
                   7786:                                }
                   7787:                                cotvar[j][iv][i]=(double)(lval);
                   7788:                                strcpy(line,stra);
1.223     brouard  7789:       }/* end loop ntv */
1.225     brouard  7790:       
1.223     brouard  7791:       /* Statuses  at wave */
1.137     brouard  7792:       cutv(stra, strb, line, ' '); 
1.223     brouard  7793:       if(strb[0]=='.') { /* Missing value */
1.232     brouard  7794:                                lval=-1;
1.136     brouard  7795:       }else{
1.232     brouard  7796:                                errno=0;
                   7797:                                lval=strtol(strb,&endptr,10); 
                   7798:                                /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7799:                                if( strb[0]=='\0' || (*endptr != '\0')){
                   7800:                                        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);
                   7801:                                        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);
                   7802:                                        return 1;
                   7803:                                }
1.136     brouard  7804:       }
1.225     brouard  7805:       
1.136     brouard  7806:       s[j][i]=lval;
1.225     brouard  7807:       
1.223     brouard  7808:       /* Date of Interview */
1.136     brouard  7809:       strcpy(line,stra);
                   7810:       cutv(stra, strb,line,' ');
1.169     brouard  7811:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7812:       }
1.169     brouard  7813:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  7814:        month=99;
                   7815:        year=9999;
1.136     brouard  7816:       }else{
1.225     brouard  7817:        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);
                   7818:        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);
                   7819:        return 1;
1.136     brouard  7820:       }
                   7821:       anint[j][i]= (double) year; 
                   7822:       mint[j][i]= (double)month; 
                   7823:       strcpy(line,stra);
1.223     brouard  7824:     } /* End loop on waves */
1.225     brouard  7825:     
1.223     brouard  7826:     /* Date of death */
1.136     brouard  7827:     cutv(stra, strb,line,' '); 
1.169     brouard  7828:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7829:     }
1.169     brouard  7830:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7831:       month=99;
                   7832:       year=9999;
                   7833:     }else{
1.141     brouard  7834:       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);
1.225     brouard  7835:       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);
                   7836:       return 1;
1.136     brouard  7837:     }
                   7838:     andc[i]=(double) year; 
                   7839:     moisdc[i]=(double) month; 
                   7840:     strcpy(line,stra);
                   7841:     
1.223     brouard  7842:     /* Date of birth */
1.136     brouard  7843:     cutv(stra, strb,line,' '); 
1.169     brouard  7844:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7845:     }
1.169     brouard  7846:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7847:       month=99;
                   7848:       year=9999;
                   7849:     }else{
1.141     brouard  7850:       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);
                   7851:       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.225     brouard  7852:       return 1;
1.136     brouard  7853:     }
                   7854:     if (year==9999) {
1.141     brouard  7855:       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);
                   7856:       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.225     brouard  7857:       return 1;
                   7858:       
1.136     brouard  7859:     }
                   7860:     annais[i]=(double)(year);
                   7861:     moisnais[i]=(double)(month); 
                   7862:     strcpy(line,stra);
1.225     brouard  7863:     
1.223     brouard  7864:     /* Sample weight */
1.136     brouard  7865:     cutv(stra, strb,line,' '); 
                   7866:     errno=0;
                   7867:     dval=strtod(strb,&endptr); 
                   7868:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7869:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7870:       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  7871:       fflush(ficlog);
                   7872:       return 1;
                   7873:     }
                   7874:     weight[i]=dval; 
                   7875:     strcpy(line,stra);
1.225     brouard  7876:     
1.223     brouard  7877:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   7878:       cutv(stra, strb, line, ' '); 
                   7879:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  7880:        lval=-1;
1.223     brouard  7881:       }else{
1.225     brouard  7882:        errno=0;
                   7883:        /* what_kind_of_number(strb); */
                   7884:        dval=strtod(strb,&endptr);
                   7885:        /* if(strb != endptr && *endptr == '\0') */
                   7886:        /*   dval=dlval; */
                   7887:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7888:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7889:          printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);
                   7890:          fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);fflush(ficlog);
                   7891:          return 1;
                   7892:        }
                   7893:        coqvar[iv][i]=dval; 
1.226     brouard  7894:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  7895:       }
                   7896:       strcpy(line,stra);
                   7897:     }/* end loop nqv */
1.136     brouard  7898:     
1.223     brouard  7899:     /* Covariate values */
1.136     brouard  7900:     for (j=ncovcol;j>=1;j--){
                   7901:       cutv(stra, strb,line,' '); 
1.223     brouard  7902:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  7903:        lval=-1;
1.136     brouard  7904:       }else{
1.225     brouard  7905:        errno=0;
                   7906:        lval=strtol(strb,&endptr,10); 
                   7907:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7908:          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);
                   7909:          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);
                   7910:          return 1;
                   7911:        }
1.136     brouard  7912:       }
                   7913:       if(lval <-1 || lval >1){
1.225     brouard  7914:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7915:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7916:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  7917:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7918:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7919:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  7920:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  7921:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  7922:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  7923:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7924:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7925:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  7926:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7927:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7928:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  7929:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  7930:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  7931:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  7932:        return 1;
1.136     brouard  7933:       }
                   7934:       covar[j][i]=(double)(lval);
                   7935:       strcpy(line,stra);
                   7936:     }  
                   7937:     lstra=strlen(stra);
1.225     brouard  7938:     
1.136     brouard  7939:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7940:       stratrunc = &(stra[lstra-9]);
                   7941:       num[i]=atol(stratrunc);
                   7942:     }
                   7943:     else
                   7944:       num[i]=atol(stra);
                   7945:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7946:       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;}*/
                   7947:     
                   7948:     i=i+1;
                   7949:   } /* End loop reading  data */
1.225     brouard  7950:   
1.136     brouard  7951:   *imax=i-1; /* Number of individuals */
                   7952:   fclose(fic);
1.225     brouard  7953:   
1.136     brouard  7954:   return (0);
1.164     brouard  7955:   /* endread: */
1.225     brouard  7956:   printf("Exiting readdata: ");
                   7957:   fclose(fic);
                   7958:   return (1);
1.223     brouard  7959: }
1.126     brouard  7960: 
1.234     brouard  7961: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  7962:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  7963:   while (*p2 == ' ')
1.234     brouard  7964:     p2++; 
                   7965:   /* while ((*p1++ = *p2++) !=0) */
                   7966:   /*   ; */
                   7967:   /* do */
                   7968:   /*   while (*p2 == ' ') */
                   7969:   /*     p2++; */
                   7970:   /* while (*p1++ == *p2++); */
                   7971:   *stri=p2; 
1.145     brouard  7972: }
                   7973: 
1.235     brouard  7974: int decoderesult ( char resultline[], int nres)
1.230     brouard  7975: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   7976: {
1.235     brouard  7977:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  7978:   char resultsav[MAXLINE];
1.234     brouard  7979:   int resultmodel[MAXLINE];
                   7980:   int modelresult[MAXLINE];
1.230     brouard  7981:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   7982: 
1.234     brouard  7983:   removefirstspace(&resultline);
1.233     brouard  7984:   printf("decoderesult:%s\n",resultline);
1.230     brouard  7985: 
                   7986:   if (strstr(resultline,"v") !=0){
                   7987:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   7988:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   7989:     return 1;
                   7990:   }
                   7991:   trimbb(resultsav, resultline);
                   7992:   if (strlen(resultsav) >1){
                   7993:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   7994:   }
1.234     brouard  7995:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   7996:     printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   7997:     fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   7998:   }
                   7999:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8000:     if(nbocc(resultsav,'=') >1){
                   8001:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8002:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8003:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8004:     }else
                   8005:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8006:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8007:     
1.230     brouard  8008:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8009:     Tvarsel[k]=atoi(strc);
                   8010:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8011:     /* cptcovsel++;     */
                   8012:     if (nbocc(stra,'=') >0)
                   8013:       strcpy(resultsav,stra); /* and analyzes it */
                   8014:   }
1.235     brouard  8015:   /* Checking for missing or useless values in comparison of current model needs */
1.236   ! brouard  8016:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
        !          8017:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8018:       match=0;
1.236   ! brouard  8019:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
        !          8020:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[2]=5 == Tvarsel[1]=4   */
        !          8021:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8022:          match=1;
                   8023:          break;
                   8024:        }
                   8025:       }
                   8026:       if(match == 0){
                   8027:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8028:       }
                   8029:     }
                   8030:   }
1.235     brouard  8031:   /* Checking for missing or useless values in comparison of current model needs */
                   8032:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8033:     match=0;
1.235     brouard  8034:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8035:       if(Typevar[k1]==0){ /* Single */
                   8036:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=5 == Tvarsel[1]=4   */
                   8037:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8038:          ++match;
                   8039:        }
                   8040:       }
                   8041:     }
                   8042:     if(match == 0){
                   8043:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8044:     }else if(match > 1){
                   8045:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8046:     }
                   8047:   }
1.235     brouard  8048:       
1.234     brouard  8049:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8050:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8051:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8052:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8053:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8054:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8055:   /*    1 0 0 0 */
                   8056:   /*    2 1 0 0 */
                   8057:   /*    3 0 1 0 */ 
                   8058:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8059:   /*    5 0 0 1 */
                   8060:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8061:   /*    7 0 1 1 */
                   8062:   /*    8 1 1 1 */
                   8063:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8064:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
                   8065:       k3= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8066:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8067:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
                   8068:       Tresult[nres][k4+1]=Tvalsel[k3];
                   8069:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];
                   8070:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8071:       k4++;;
                   8072:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8073:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8074:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8075:       Tqresult[nres][k4q+1]=Tvalsel[k3q];
                   8076:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q];
                   8077:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8078:       k4q++;;
                   8079:     }
                   8080:   }
1.234     brouard  8081:   
1.235     brouard  8082:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8083:   return (0);
                   8084: }
1.235     brouard  8085: 
1.230     brouard  8086: int decodemodel( char model[], int lastobs)
                   8087:  /**< This routine decodes the model and returns:
1.224     brouard  8088:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8089:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8090:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8091:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8092:        * - cptcovage number of covariates with age*products =2
                   8093:        * - cptcovs number of simple covariates
                   8094:        * - 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
                   8095:        *     which is a new column after the 9 (ncovcol) variables. 
                   8096:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8097:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8098:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8099:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8100:        */
1.136     brouard  8101: {
1.145     brouard  8102:   int i, j, k, ks;
1.227     brouard  8103:   int  j1, k1, k2, k3, k4;
1.136     brouard  8104:   char modelsav[80];
1.145     brouard  8105:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8106:   char *strpt;
1.136     brouard  8107: 
1.145     brouard  8108:   /*removespace(model);*/
1.136     brouard  8109:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8110:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8111:     if (strstr(model,"AGE") !=0){
1.192     brouard  8112:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8113:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8114:       return 1;
                   8115:     }
1.141     brouard  8116:     if (strstr(model,"v") !=0){
                   8117:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8118:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8119:       return 1;
                   8120:     }
1.187     brouard  8121:     strcpy(modelsav,model); 
                   8122:     if ((strpt=strstr(model,"age*age")) !=0){
                   8123:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8124:       if(strpt != model){
1.234     brouard  8125:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8126:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8127:  corresponding column of parameters.\n",model);
1.234     brouard  8128:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8129:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8130:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8131:        return 1;
1.225     brouard  8132:       }
1.187     brouard  8133:       nagesqr=1;
                   8134:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8135:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8136:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8137:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8138:       else 
1.234     brouard  8139:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8140:     }else
                   8141:       nagesqr=0;
                   8142:     if (strlen(modelsav) >1){
                   8143:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8144:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8145:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8146:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8147:                     * cst, age and age*age 
                   8148:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8149:       /* including age products which are counted in cptcovage.
                   8150:        * but the covariates which are products must be treated 
                   8151:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8152:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8153:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8154:       
                   8155:       
1.187     brouard  8156:       /*   Design
                   8157:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8158:        *  <          ncovcol=8                >
                   8159:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8160:        *   k=  1    2      3       4     5       6      7        8
                   8161:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8162:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8163:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8164:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8165:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8166:        *  Tage[++cptcovage]=k
                   8167:        *       if products, new covar are created after ncovcol with k1
                   8168:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8169:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8170:        *  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
                   8171:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8172:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8173:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8174:        *  <          ncovcol=8                >
                   8175:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8176:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8177:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8178:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8179:        * p Tprod[1]@2={                         6, 5}
                   8180:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8181:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8182:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8183:        *How to reorganize?
                   8184:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8185:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8186:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8187:        * Struct []
                   8188:        */
1.225     brouard  8189:       
1.187     brouard  8190:       /* This loop fills the array Tvar from the string 'model'.*/
                   8191:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8192:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8193:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8194:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8195:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8196:       /*       k=1 Tvar[1]=2 (from V2) */
                   8197:       /*       k=5 Tvar[5] */
                   8198:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8199:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8200:       /*       } */
1.198     brouard  8201:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8202:       /*
                   8203:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8204:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8205:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8206:       }
1.187     brouard  8207:       cptcovage=0;
                   8208:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8209:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8210:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8211:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8212:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8213:        /*scanf("%d",i);*/
                   8214:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8215:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8216:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8217:            /* covar is not filled and then is empty */
                   8218:            cptcovprod--;
                   8219:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8220:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8221:            Typevar[k]=1;  /* 1 for age product */
                   8222:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8223:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8224:            /*printf("stre=%s ", stre);*/
                   8225:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8226:            cptcovprod--;
                   8227:            cutl(stre,strb,strc,'V');
                   8228:            Tvar[k]=atoi(stre);
                   8229:            Typevar[k]=1;  /* 1 for age product */
                   8230:            cptcovage++;
                   8231:            Tage[cptcovage]=k;
                   8232:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8233:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8234:            cptcovn++;
                   8235:            cptcovprodnoage++;k1++;
                   8236:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8237:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8238:                                                because this model-covariate is a construction we invent a new column
                   8239:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8240:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8241:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8242:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8243:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8244:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8245:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8246:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8247:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8248:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8249:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8250:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8251:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8252:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8253:            for (i=1; i<=lastobs;i++){
                   8254:              /* Computes the new covariate which is a product of
                   8255:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8256:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8257:            }
                   8258:          } /* End age is not in the model */
                   8259:        } /* End if model includes a product */
                   8260:        else { /* no more sum */
                   8261:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8262:          /*  scanf("%d",i);*/
                   8263:          cutl(strd,strc,strb,'V');
                   8264:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8265:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8266:          Tvar[k]=atoi(strd);
                   8267:          Typevar[k]=0;  /* 0 for simple covariates */
                   8268:        }
                   8269:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8270:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8271:                                  scanf("%d",i);*/
1.187     brouard  8272:       } /* end of loop + on total covariates */
                   8273:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8274:   } /* end if strlen(model == 0) */
1.136     brouard  8275:   
                   8276:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8277:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8278:   
1.136     brouard  8279:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8280:      printf("cptcovprod=%d ", cptcovprod);
                   8281:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8282:      scanf("%d ",i);*/
                   8283: 
                   8284: 
1.230     brouard  8285: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8286:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8287: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8288:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8289:    k =           1    2   3     4       5       6      7      8        9
                   8290:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8291:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8292:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8293:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8294:          Tmodelind[combination of covar]=k;
1.225     brouard  8295: */  
                   8296: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8297:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8298:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
1.226     brouard  8299:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8300:   printf("Model=%s\n\
                   8301: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8302: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8303: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
                   8304:   fprintf(ficlog,"Model=%s\n\
                   8305: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8306: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8307: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
                   8308: 
1.234     brouard  8309:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
                   8310:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8311:       Fixed[k]= 0;
                   8312:       Dummy[k]= 0;
1.225     brouard  8313:       ncoveff++;
1.232     brouard  8314:       ncovf++;
1.234     brouard  8315:       nsd++;
                   8316:       modell[k].maintype= FTYPE;
                   8317:       TvarsD[nsd]=Tvar[k];
                   8318:       TvarsDind[nsd]=k;
                   8319:       TvarF[ncovf]=Tvar[k];
                   8320:       TvarFind[ncovf]=k;
                   8321:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8322:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8323:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8324:       Fixed[k]= 0;
                   8325:       Dummy[k]= 0;
                   8326:       ncoveff++;
                   8327:       ncovf++;
                   8328:       modell[k].maintype= FTYPE;
                   8329:       TvarF[ncovf]=Tvar[k];
                   8330:       TvarFind[ncovf]=k;
1.230     brouard  8331:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8332:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8333:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){ /* Remind that product Vn*Vm are added in k*/ /* Only simple fixed quantitative variable */
1.227     brouard  8334:       Fixed[k]= 0;
                   8335:       Dummy[k]= 1;
1.230     brouard  8336:       nqfveff++;
1.234     brouard  8337:       modell[k].maintype= FTYPE;
                   8338:       modell[k].subtype= FQ;
                   8339:       nsq++;
                   8340:       TvarsQ[nsq]=Tvar[k];
                   8341:       TvarsQind[nsq]=k;
1.232     brouard  8342:       ncovf++;
1.234     brouard  8343:       TvarF[ncovf]=Tvar[k];
                   8344:       TvarFind[ncovf]=k;
1.231     brouard  8345:       TvarFQ[nqfveff]=Tvar[k]-ncovcol; /* TvarFQ[1]=V2-1=1st in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.230     brouard  8346:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.234     brouard  8347:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying variables */
1.227     brouard  8348:       Fixed[k]= 1;
                   8349:       Dummy[k]= 0;
1.225     brouard  8350:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8351:       modell[k].maintype= VTYPE;
                   8352:       modell[k].subtype= VD;
                   8353:       nsd++;
                   8354:       TvarsD[nsd]=Tvar[k];
                   8355:       TvarsDind[nsd]=k;
                   8356:       ncovv++; /* Only simple time varying variables */
                   8357:       TvarV[ncovv]=Tvar[k];
                   8358:       TvarVind[ncovv]=k;
1.231     brouard  8359:       TvarVD[ntveff]=Tvar[k]; /* TvarVD[1]=V4  TvarVD[2]=V3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
                   8360:       TvarVDind[ntveff]=k; /* TvarVDind[1]=2 TvarVDind[2]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
1.228     brouard  8361:       printf("Quasi Tmodelind[%d]=%d,Tvar[Tmodelind[%d]]=V%d, ncovcol=%d, nqv=%d,Tvar[k]- ncovcol-nqv=%d\n",ntveff,k,ntveff,Tvar[k], ncovcol, nqv,Tvar[k]- ncovcol-nqv);
                   8362:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8363:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8364:       Fixed[k]= 1;
                   8365:       Dummy[k]= 1;
                   8366:       nqtveff++;
                   8367:       modell[k].maintype= VTYPE;
                   8368:       modell[k].subtype= VQ;
                   8369:       ncovv++; /* Only simple time varying variables */
                   8370:       nsq++;
                   8371:       TvarsQ[nsq]=Tvar[k];
                   8372:       TvarsQind[nsq]=k;
                   8373:       TvarV[ncovv]=Tvar[k];
                   8374:       TvarVind[ncovv]=k;
1.231     brouard  8375:       TvarVQ[nqtveff]=Tvar[k]; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   8376:       TvarVQind[nqtveff]=k; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
1.234     brouard  8377:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8378:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8379:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
1.228     brouard  8380:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8381:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8382:       ncova++;
                   8383:       TvarA[ncova]=Tvar[k];
                   8384:       TvarAind[ncova]=k;
1.231     brouard  8385:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.234     brouard  8386:        Fixed[k]= 2;
                   8387:        Dummy[k]= 2;
                   8388:        modell[k].maintype= ATYPE;
                   8389:        modell[k].subtype= APFD;
                   8390:        /* ncoveff++; */
1.227     brouard  8391:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.234     brouard  8392:        Fixed[k]= 2;
                   8393:        Dummy[k]= 3;
                   8394:        modell[k].maintype= ATYPE;
                   8395:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8396:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8397:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.234     brouard  8398:        Fixed[k]= 3;
                   8399:        Dummy[k]= 2;
                   8400:        modell[k].maintype= ATYPE;
                   8401:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8402:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8403:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.234     brouard  8404:        Fixed[k]= 3;
                   8405:        Dummy[k]= 3;
                   8406:        modell[k].maintype= ATYPE;
                   8407:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8408:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8409:       }
                   8410:     }else if (Typevar[k] == 2) {  /* product without age */
                   8411:       k1=Tposprod[k];
                   8412:       if(Tvard[k1][1] <=ncovcol){
1.234     brouard  8413:        if(Tvard[k1][2] <=ncovcol){
                   8414:          Fixed[k]= 1;
                   8415:          Dummy[k]= 0;
                   8416:          modell[k].maintype= FTYPE;
                   8417:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8418:          ncovf++; /* Fixed variables without age */
                   8419:          TvarF[ncovf]=Tvar[k];
                   8420:          TvarFind[ncovf]=k;
                   8421:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8422:          Fixed[k]= 0;  /* or 2 ?*/
                   8423:          Dummy[k]= 1;
                   8424:          modell[k].maintype= FTYPE;
                   8425:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8426:          ncovf++; /* Varying variables without age */
                   8427:          TvarF[ncovf]=Tvar[k];
                   8428:          TvarFind[ncovf]=k;
                   8429:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8430:          Fixed[k]= 1;
                   8431:          Dummy[k]= 0;
                   8432:          modell[k].maintype= VTYPE;
                   8433:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8434:          ncovv++; /* Varying variables without age */
                   8435:          TvarV[ncovv]=Tvar[k];
                   8436:          TvarVind[ncovv]=k;
                   8437:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8438:          Fixed[k]= 1;
                   8439:          Dummy[k]= 1;
                   8440:          modell[k].maintype= VTYPE;
                   8441:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8442:          ncovv++; /* Varying variables without age */
                   8443:          TvarV[ncovv]=Tvar[k];
                   8444:          TvarVind[ncovv]=k;
                   8445:        } 
1.227     brouard  8446:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.234     brouard  8447:        if(Tvard[k1][2] <=ncovcol){
                   8448:          Fixed[k]= 0;  /* or 2 ?*/
                   8449:          Dummy[k]= 1;
                   8450:          modell[k].maintype= FTYPE;
                   8451:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8452:          ncovf++; /* Fixed variables without age */
                   8453:          TvarF[ncovf]=Tvar[k];
                   8454:          TvarFind[ncovf]=k;
                   8455:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8456:          Fixed[k]= 1;
                   8457:          Dummy[k]= 1;
                   8458:          modell[k].maintype= VTYPE;
                   8459:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8460:          ncovv++; /* Varying variables without age */
                   8461:          TvarV[ncovv]=Tvar[k];
                   8462:          TvarVind[ncovv]=k;
                   8463:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8464:          Fixed[k]= 1;
                   8465:          Dummy[k]= 1;
                   8466:          modell[k].maintype= VTYPE;
                   8467:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8468:          ncovv++; /* Varying variables without age */
                   8469:          TvarV[ncovv]=Tvar[k];
                   8470:          TvarVind[ncovv]=k;
                   8471:          ncovv++; /* Varying variables without age */
                   8472:          TvarV[ncovv]=Tvar[k];
                   8473:          TvarVind[ncovv]=k;
                   8474:        } 
1.227     brouard  8475:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.234     brouard  8476:        if(Tvard[k1][2] <=ncovcol){
                   8477:          Fixed[k]= 1;
                   8478:          Dummy[k]= 1;
                   8479:          modell[k].maintype= VTYPE;
                   8480:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8481:          ncovv++; /* Varying variables without age */
                   8482:          TvarV[ncovv]=Tvar[k];
                   8483:          TvarVind[ncovv]=k;
                   8484:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8485:          Fixed[k]= 1;
                   8486:          Dummy[k]= 1;
                   8487:          modell[k].maintype= VTYPE;
                   8488:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8489:          ncovv++; /* Varying variables without age */
                   8490:          TvarV[ncovv]=Tvar[k];
                   8491:          TvarVind[ncovv]=k;
                   8492:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8493:          Fixed[k]= 1;
                   8494:          Dummy[k]= 0;
                   8495:          modell[k].maintype= VTYPE;
                   8496:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8497:          ncovv++; /* Varying variables without age */
                   8498:          TvarV[ncovv]=Tvar[k];
                   8499:          TvarVind[ncovv]=k;
                   8500:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8501:          Fixed[k]= 1;
                   8502:          Dummy[k]= 1;
                   8503:          modell[k].maintype= VTYPE;
                   8504:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8505:          ncovv++; /* Varying variables without age */
                   8506:          TvarV[ncovv]=Tvar[k];
                   8507:          TvarVind[ncovv]=k;
                   8508:        } 
1.227     brouard  8509:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.234     brouard  8510:        if(Tvard[k1][2] <=ncovcol){
                   8511:          Fixed[k]= 1;
                   8512:          Dummy[k]= 1;
                   8513:          modell[k].maintype= VTYPE;
                   8514:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8515:          ncovv++; /* Varying variables without age */
                   8516:          TvarV[ncovv]=Tvar[k];
                   8517:          TvarVind[ncovv]=k;
                   8518:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8519:          Fixed[k]= 1;
                   8520:          Dummy[k]= 1;
                   8521:          modell[k].maintype= VTYPE;
                   8522:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8523:          ncovv++; /* Varying variables without age */
                   8524:          TvarV[ncovv]=Tvar[k];
                   8525:          TvarVind[ncovv]=k;
                   8526:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8527:          Fixed[k]= 1;
                   8528:          Dummy[k]= 1;
                   8529:          modell[k].maintype= VTYPE;
                   8530:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8531:          ncovv++; /* Varying variables without age */
                   8532:          TvarV[ncovv]=Tvar[k];
                   8533:          TvarVind[ncovv]=k;
                   8534:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8535:          Fixed[k]= 1;
                   8536:          Dummy[k]= 1;
                   8537:          modell[k].maintype= VTYPE;
                   8538:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8539:          ncovv++; /* Varying variables without age */
                   8540:          TvarV[ncovv]=Tvar[k];
                   8541:          TvarVind[ncovv]=k;
                   8542:        } 
1.227     brouard  8543:       }else{
1.234     brouard  8544:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8545:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
1.226     brouard  8546:       } /* end k1 */
1.225     brouard  8547:     }else{
1.226     brouard  8548:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8549:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
1.225     brouard  8550:     }
1.227     brouard  8551:     printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
1.231     brouard  8552:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8553:     fprintf(ficlog,"Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
                   8554:   }
                   8555:   /* Searching for doublons in the model */
                   8556:   for(k1=1; k1<= cptcovt;k1++){
                   8557:     for(k2=1; k2 <k1;k2++){
                   8558:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8559:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8560:          if(Tvar[k1]==Tvar[k2]){
                   8561:            printf("Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
                   8562:            fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
                   8563:            return(1);
                   8564:          }
                   8565:        }else if (Typevar[k1] ==2){
                   8566:          k3=Tposprod[k1];
                   8567:          k4=Tposprod[k2];
                   8568:          if( ((Tvard[k3][1]== Tvard[k4][1])&&(Tvard[k3][2]== Tvard[k4][2])) || ((Tvard[k3][1]== Tvard[k4][2])&&(Tvard[k3][2]== Tvard[k4][1])) ){
                   8569:            printf("Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
                   8570:            fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
                   8571:            return(1);
                   8572:          }
                   8573:        }
1.227     brouard  8574:       }
                   8575:     }
1.225     brouard  8576:   }
                   8577:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8578:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8579:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8580:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8581:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8582:   /*endread:*/
1.225     brouard  8583:   printf("Exiting decodemodel: ");
                   8584:   return (1);
1.136     brouard  8585: }
                   8586: 
1.169     brouard  8587: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8588: {
                   8589:   int i, m;
1.218     brouard  8590:   int firstone=0;
                   8591:   
1.136     brouard  8592:   for (i=1; i<=imx; i++) {
                   8593:     for(m=2; (m<= maxwav); m++) {
                   8594:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8595:        anint[m][i]=9999;
1.216     brouard  8596:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8597:          s[m][i]=-1;
1.136     brouard  8598:       }
                   8599:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8600:        *nberr = *nberr + 1;
1.218     brouard  8601:        if(firstone == 0){
                   8602:          firstone=1;
                   8603:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   8604:        }
                   8605:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
1.136     brouard  8606:        s[m][i]=-1;
                   8607:       }
                   8608:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8609:        (*nberr)++;
1.136     brouard  8610:        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]); 
                   8611:        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]); 
                   8612:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8613:       }
                   8614:     }
                   8615:   }
                   8616: 
                   8617:   for (i=1; i<=imx; i++)  {
                   8618:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8619:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8620:       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  8621:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8622:          if(agedc[i]>0){
                   8623:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8624:              agev[m][i]=agedc[i];
1.214     brouard  8625:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8626:            }else {
1.136     brouard  8627:              if ((int)andc[i]!=9999){
                   8628:                nbwarn++;
                   8629:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8630:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8631:                agev[m][i]=-1;
                   8632:              }
                   8633:            }
1.169     brouard  8634:          } /* agedc > 0 */
1.214     brouard  8635:        } /* end if */
1.136     brouard  8636:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8637:                                 years but with the precision of a month */
                   8638:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8639:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8640:            agev[m][i]=1;
                   8641:          else if(agev[m][i] < *agemin){ 
                   8642:            *agemin=agev[m][i];
                   8643:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8644:          }
                   8645:          else if(agev[m][i] >*agemax){
                   8646:            *agemax=agev[m][i];
1.156     brouard  8647:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8648:          }
                   8649:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8650:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8651:        } /* en if 9*/
1.136     brouard  8652:        else { /* =9 */
1.214     brouard  8653:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8654:          agev[m][i]=1;
                   8655:          s[m][i]=-1;
                   8656:        }
                   8657:       }
1.214     brouard  8658:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8659:        agev[m][i]=1;
1.214     brouard  8660:       else{
                   8661:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8662:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8663:        agev[m][i]=0;
                   8664:       }
                   8665:     } /* End for lastpass */
                   8666:   }
1.136     brouard  8667:     
                   8668:   for (i=1; i<=imx; i++)  {
                   8669:     for(m=firstpass; (m<=lastpass); m++){
                   8670:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8671:        (*nberr)++;
1.136     brouard  8672:        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);     
                   8673:        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);     
                   8674:        return 1;
                   8675:       }
                   8676:     }
                   8677:   }
                   8678: 
                   8679:   /*for (i=1; i<=imx; i++){
                   8680:   for (m=firstpass; (m<lastpass); m++){
                   8681:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8682: }
                   8683: 
                   8684: }*/
                   8685: 
                   8686: 
1.139     brouard  8687:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8688:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8689: 
                   8690:   return (0);
1.164     brouard  8691:  /* endread:*/
1.136     brouard  8692:     printf("Exiting calandcheckages: ");
                   8693:     return (1);
                   8694: }
                   8695: 
1.172     brouard  8696: #if defined(_MSC_VER)
                   8697: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8698: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8699: //#include "stdafx.h"
                   8700: //#include <stdio.h>
                   8701: //#include <tchar.h>
                   8702: //#include <windows.h>
                   8703: //#include <iostream>
                   8704: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8705: 
                   8706: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8707: 
                   8708: BOOL IsWow64()
                   8709: {
                   8710:        BOOL bIsWow64 = FALSE;
                   8711: 
                   8712:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8713:        //  (HANDLE, PBOOL);
                   8714: 
                   8715:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8716: 
                   8717:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8718:        const char funcName[] = "IsWow64Process";
                   8719:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8720:                GetProcAddress(module, funcName);
                   8721: 
                   8722:        if (NULL != fnIsWow64Process)
                   8723:        {
                   8724:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8725:                        &bIsWow64))
                   8726:                        //throw std::exception("Unknown error");
                   8727:                        printf("Unknown error\n");
                   8728:        }
                   8729:        return bIsWow64 != FALSE;
                   8730: }
                   8731: #endif
1.177     brouard  8732: 
1.191     brouard  8733: void syscompilerinfo(int logged)
1.167     brouard  8734:  {
                   8735:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8736:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8737:    /* /GS /W3 /Gy
                   8738:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8739:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8740:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8741:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8742:    */ 
                   8743:    /* 64 bits */
1.185     brouard  8744:    /*
                   8745:      /GS /W3 /Gy
                   8746:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8747:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8748:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8749:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8750:    /* Optimization are useless and O3 is slower than O2 */
                   8751:    /*
                   8752:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8753:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8754:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8755:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8756:    */
1.186     brouard  8757:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8758:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8759:       /PDB:"visual studio
                   8760:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8761:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8762:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8763:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   8764:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   8765:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   8766:       uiAccess='false'"
                   8767:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   8768:       /NOLOGO /TLBID:1
                   8769:    */
1.177     brouard  8770: #if defined __INTEL_COMPILER
1.178     brouard  8771: #if defined(__GNUC__)
                   8772:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   8773: #endif
1.177     brouard  8774: #elif defined(__GNUC__) 
1.179     brouard  8775: #ifndef  __APPLE__
1.174     brouard  8776: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  8777: #endif
1.177     brouard  8778:    struct utsname sysInfo;
1.178     brouard  8779:    int cross = CROSS;
                   8780:    if (cross){
                   8781:           printf("Cross-");
1.191     brouard  8782:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  8783:    }
1.174     brouard  8784: #endif
                   8785: 
1.171     brouard  8786: #include <stdint.h>
1.178     brouard  8787: 
1.191     brouard  8788:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  8789: #if defined(__clang__)
1.191     brouard  8790:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  8791: #endif
                   8792: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  8793:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  8794: #endif
                   8795: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  8796:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  8797: #endif
                   8798: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  8799:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  8800: #endif
                   8801: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  8802:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  8803: #endif
                   8804: #if defined(_MSC_VER)
1.191     brouard  8805:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  8806: #endif
                   8807: #if defined(__PGI)
1.191     brouard  8808:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  8809: #endif
                   8810: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  8811:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  8812: #endif
1.191     brouard  8813:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  8814:    
1.167     brouard  8815: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   8816: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   8817:     // Windows (x64 and x86)
1.191     brouard  8818:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  8819: #elif __unix__ // all unices, not all compilers
                   8820:     // Unix
1.191     brouard  8821:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  8822: #elif __linux__
                   8823:     // linux
1.191     brouard  8824:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  8825: #elif __APPLE__
1.174     brouard  8826:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  8827:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  8828: #endif
                   8829: 
                   8830: /*  __MINGW32__          */
                   8831: /*  __CYGWIN__  */
                   8832: /* __MINGW64__  */
                   8833: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   8834: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   8835: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   8836: /* _WIN64  // Defined for applications for Win64. */
                   8837: /* _M_X64 // Defined for compilations that target x64 processors. */
                   8838: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  8839: 
1.167     brouard  8840: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  8841:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  8842: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  8843:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  8844: #else
1.191     brouard  8845:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  8846: #endif
                   8847: 
1.169     brouard  8848: #if defined(__GNUC__)
                   8849: # if defined(__GNUC_PATCHLEVEL__)
                   8850: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8851:                             + __GNUC_MINOR__ * 100 \
                   8852:                             + __GNUC_PATCHLEVEL__)
                   8853: # else
                   8854: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8855:                             + __GNUC_MINOR__ * 100)
                   8856: # endif
1.174     brouard  8857:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  8858:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  8859: 
                   8860:    if (uname(&sysInfo) != -1) {
                   8861:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  8862:         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  8863:    }
                   8864:    else
                   8865:       perror("uname() error");
1.179     brouard  8866:    //#ifndef __INTEL_COMPILER 
                   8867: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  8868:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  8869:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  8870: #endif
1.169     brouard  8871: #endif
1.172     brouard  8872: 
                   8873:    //   void main()
                   8874:    //   {
1.169     brouard  8875: #if defined(_MSC_VER)
1.174     brouard  8876:    if (IsWow64()){
1.191     brouard  8877:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   8878:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  8879:    }
                   8880:    else{
1.191     brouard  8881:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   8882:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  8883:    }
1.172     brouard  8884:    //     printf("\nPress Enter to continue...");
                   8885:    //     getchar();
                   8886:    //   }
                   8887: 
1.169     brouard  8888: #endif
                   8889:    
1.167     brouard  8890: 
1.219     brouard  8891: }
1.136     brouard  8892: 
1.219     brouard  8893: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  8894:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  8895:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  8896:   /* double ftolpl = 1.e-10; */
1.180     brouard  8897:   double age, agebase, agelim;
1.203     brouard  8898:   double tot;
1.180     brouard  8899: 
1.202     brouard  8900:   strcpy(filerespl,"PL_");
                   8901:   strcat(filerespl,fileresu);
                   8902:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   8903:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   8904:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   8905:   }
1.227     brouard  8906:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   8907:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  8908:   pstamp(ficrespl);
1.203     brouard  8909:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  8910:   fprintf(ficrespl,"#Age ");
                   8911:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   8912:   fprintf(ficrespl,"\n");
1.180     brouard  8913:   
1.219     brouard  8914:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  8915: 
1.219     brouard  8916:   agebase=ageminpar;
                   8917:   agelim=agemaxpar;
1.180     brouard  8918: 
1.227     brouard  8919:   /* i1=pow(2,ncoveff); */
1.234     brouard  8920:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  8921:   if (cptcovn < 1){i1=1;}
1.180     brouard  8922: 
1.235     brouard  8923:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.220     brouard  8924:   for(k=1; k<=i1;k++){
1.235     brouard  8925:     if(TKresult[nres]!= k)
                   8926:       continue;
                   8927: 
1.220     brouard  8928:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.180     brouard  8929:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219     brouard  8930:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  8931:     /* k=k+1; */
1.219     brouard  8932:     /* to clean */
                   8933:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8934:     fprintf(ficrespl,"#******");
                   8935:     printf("#******");
                   8936:     fprintf(ficlog,"#******");
1.227     brouard  8937:     for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   8938:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
1.219     brouard  8939:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8940:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8941:     }
1.235     brouard  8942:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8943:       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8944:       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8945:     }
1.219     brouard  8946:     fprintf(ficrespl,"******\n");
                   8947:     printf("******\n");
                   8948:     fprintf(ficlog,"******\n");
1.227     brouard  8949:     if(invalidvarcomb[k]){
                   8950:       printf("\nCombination (%d) ignored because no case \n",k); 
                   8951:       fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   8952:       fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
1.220     brouard  8953:                                                continue;
1.227     brouard  8954:     }
1.219     brouard  8955: 
                   8956:     fprintf(ficrespl,"#Age ");
1.227     brouard  8957:     for(j=1;j<=cptcoveff;j++) {
1.219     brouard  8958:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8959:     }
                   8960:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   8961:     fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  8962:     
1.219     brouard  8963:     for (age=agebase; age<=agelim; age++){
                   8964:       /* for (age=agebase; age<=agebase; age++){ */
1.235     brouard  8965:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
1.219     brouard  8966:       fprintf(ficrespl,"%.0f ",age );
1.227     brouard  8967:       for(j=1;j<=cptcoveff;j++)
                   8968:        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  8969:       tot=0.;
                   8970:       for(i=1; i<=nlstate;i++){
1.227     brouard  8971:        tot +=  prlim[i][i];
                   8972:        fprintf(ficrespl," %.5f", prlim[i][i]);
1.219     brouard  8973:       }
                   8974:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   8975:     } /* Age */
                   8976:     /* was end of cptcod */
                   8977:   } /* cptcov */
                   8978:   return 0;
1.180     brouard  8979: }
                   8980: 
1.218     brouard  8981: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
                   8982:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   8983:        
                   8984:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   8985:    * at any age between ageminpar and agemaxpar
                   8986:         */
1.235     brouard  8987:   int i, j, k, i1, nres=0 ;
1.217     brouard  8988:   /* double ftolpl = 1.e-10; */
                   8989:   double age, agebase, agelim;
                   8990:   double tot;
1.218     brouard  8991:   /* double ***mobaverage; */
                   8992:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  8993: 
                   8994:   strcpy(fileresplb,"PLB_");
                   8995:   strcat(fileresplb,fileresu);
                   8996:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   8997:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8998:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8999:   }
                   9000:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9001:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9002:   pstamp(ficresplb);
                   9003:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9004:   fprintf(ficresplb,"#Age ");
                   9005:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9006:   fprintf(ficresplb,"\n");
                   9007:   
1.218     brouard  9008:   
                   9009:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9010:   
                   9011:   agebase=ageminpar;
                   9012:   agelim=agemaxpar;
                   9013:   
                   9014:   
1.227     brouard  9015:   i1=pow(2,cptcoveff);
1.218     brouard  9016:   if (cptcovn < 1){i1=1;}
1.227     brouard  9017:   
1.235     brouard  9018:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9019:   for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9020:     if(TKresult[nres]!= k)
                   9021:       continue;
1.218     brouard  9022:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9023:     fprintf(ficresplb,"#******");
                   9024:     printf("#******");
                   9025:     fprintf(ficlog,"#******");
1.227     brouard  9026:     for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.218     brouard  9027:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9028:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9029:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9030:     }
1.235     brouard  9031:     for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9032:       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9033:       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9034:       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9035:     }
1.218     brouard  9036:     fprintf(ficresplb,"******\n");
                   9037:     printf("******\n");
                   9038:     fprintf(ficlog,"******\n");
1.227     brouard  9039:     if(invalidvarcomb[k]){
                   9040:       printf("\nCombination (%d) ignored because no cases \n",k); 
                   9041:       fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9042:       fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9043:       continue;
                   9044:     }
1.218     brouard  9045:     
                   9046:     fprintf(ficresplb,"#Age ");
1.227     brouard  9047:     for(j=1;j<=cptcoveff;j++) {
1.218     brouard  9048:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9049:     }
                   9050:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9051:     fprintf(ficresplb,"Total Years_to_converge\n");
                   9052:     
                   9053:     
                   9054:     for (age=agebase; age<=agelim; age++){
                   9055:       /* for (age=agebase; age<=agebase; age++){ */
                   9056:       if(mobilavproj > 0){
                   9057:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9058:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.227     brouard  9059:        bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  9060:       }else if (mobilavproj == 0){
1.227     brouard  9061:        printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   9062:        fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   9063:        exit(1);
1.218     brouard  9064:       }else{
1.227     brouard  9065:        /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9066:        bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  9067:       }
                   9068:       fprintf(ficresplb,"%.0f ",age );
1.227     brouard  9069:       for(j=1;j<=cptcoveff;j++)
                   9070:        fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  9071:       tot=0.;
                   9072:       for(i=1; i<=nlstate;i++){
1.227     brouard  9073:        tot +=  bprlim[i][i];
                   9074:        fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  9075:       }
                   9076:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9077:     } /* Age */
                   9078:     /* was end of cptcod */
                   9079:   } /* cptcov */
                   9080:   
                   9081:   /* hBijx(p, bage, fage); */
                   9082:   /* fclose(ficrespijb); */
                   9083:   
                   9084:   return 0;
1.217     brouard  9085: }
1.218     brouard  9086:  
1.180     brouard  9087: int hPijx(double *p, int bage, int fage){
                   9088:     /*------------- h Pij x at various ages ------------*/
                   9089: 
                   9090:   int stepsize;
                   9091:   int agelim;
                   9092:   int hstepm;
                   9093:   int nhstepm;
1.235     brouard  9094:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9095: 
                   9096:   double agedeb;
                   9097:   double ***p3mat;
                   9098: 
1.201     brouard  9099:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9100:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9101:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9102:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9103:     }
                   9104:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9105:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9106:   
                   9107:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9108:     /*if (stepm<=24) stepsize=2;*/
                   9109: 
                   9110:     agelim=AGESUP;
                   9111:     hstepm=stepsize*YEARM; /* Every year of age */
                   9112:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9113:                
1.180     brouard  9114:     /* hstepm=1;   aff par mois*/
                   9115:     pstamp(ficrespij);
                   9116:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9117:     i1= pow(2,cptcoveff);
1.218     brouard  9118:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9119:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9120:                /*      k=k+1;  */
1.235     brouard  9121:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9122:     for(k=1; k<=i1;k++){
                   9123:       if(TKresult[nres]!= k)
                   9124:        continue;
1.183     brouard  9125:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9126:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9127:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9128:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9129:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9130:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9131:       }
1.183     brouard  9132:       fprintf(ficrespij,"******\n");
                   9133:       
                   9134:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9135:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9136:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9137:        
                   9138:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9139:        
1.183     brouard  9140:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9141:        oldm=oldms;savm=savms;
1.235     brouard  9142:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9143:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9144:        for(i=1; i<=nlstate;i++)
                   9145:          for(j=1; j<=nlstate+ndeath;j++)
                   9146:            fprintf(ficrespij," %1d-%1d",i,j);
                   9147:        fprintf(ficrespij,"\n");
                   9148:        for (h=0; h<=nhstepm; h++){
                   9149:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9150:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9151:          for(i=1; i<=nlstate;i++)
                   9152:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9153:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9154:          fprintf(ficrespij,"\n");
                   9155:        }
1.183     brouard  9156:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9157:        fprintf(ficrespij,"\n");
                   9158:       }
1.180     brouard  9159:       /*}*/
                   9160:     }
1.218     brouard  9161:     return 0;
1.180     brouard  9162: }
1.218     brouard  9163:  
                   9164:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9165:     /*------------- h Bij x at various ages ------------*/
                   9166: 
                   9167:   int stepsize;
1.218     brouard  9168:   /* int agelim; */
                   9169:        int ageminl;
1.217     brouard  9170:   int hstepm;
                   9171:   int nhstepm;
                   9172:   int h, i, i1, j, k;
1.218     brouard  9173:        
1.217     brouard  9174:   double agedeb;
                   9175:   double ***p3mat;
1.218     brouard  9176:        
                   9177:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9178:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9179:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9180:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9181:   }
                   9182:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9183:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9184:   
                   9185:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9186:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9187:   
1.218     brouard  9188:   /* agelim=AGESUP; */
                   9189:   ageminl=30;
                   9190:   hstepm=stepsize*YEARM; /* Every year of age */
                   9191:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9192:   
                   9193:   /* hstepm=1;   aff par mois*/
                   9194:   pstamp(ficrespijb);
                   9195:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9196:   i1= pow(2,cptcoveff);
1.218     brouard  9197:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9198:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9199:   /*   k=k+1;  */
1.227     brouard  9200:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.218     brouard  9201:     fprintf(ficrespijb,"\n#****** ");
1.227     brouard  9202:     for(j=1;j<=cptcoveff;j++)
1.218     brouard  9203:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9204:     fprintf(ficrespijb,"******\n");
1.222     brouard  9205:     if(invalidvarcomb[k]){
                   9206:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9207:       continue;
                   9208:     }
1.218     brouard  9209:     
                   9210:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9211:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9212:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9213:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9214:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9215:       
                   9216:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   9217:       
                   9218:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9219:       /* oldm=oldms;savm=savms; */
                   9220:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9221:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9222:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9223:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   9224:       for(i=1; i<=nlstate;i++)
                   9225:        for(j=1; j<=nlstate+ndeath;j++)
                   9226:          fprintf(ficrespijb," %1d-%1d",i,j);
                   9227:       fprintf(ficrespijb,"\n");
                   9228:       for (h=0; h<=nhstepm; h++){
                   9229:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9230:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9231:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  9232:        for(i=1; i<=nlstate;i++)
                   9233:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  9234:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  9235:        fprintf(ficrespijb,"\n");
                   9236:       }
1.218     brouard  9237:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9238:       fprintf(ficrespijb,"\n");
1.217     brouard  9239:     }
1.218     brouard  9240:     /*}*/
                   9241:   }
                   9242:   return 0;
                   9243:  } /*  hBijx */
1.217     brouard  9244: 
1.180     brouard  9245: 
1.136     brouard  9246: /***********************************************/
                   9247: /**************** Main Program *****************/
                   9248: /***********************************************/
                   9249: 
                   9250: int main(int argc, char *argv[])
                   9251: {
                   9252: #ifdef GSL
                   9253:   const gsl_multimin_fminimizer_type *T;
                   9254:   size_t iteri = 0, it;
                   9255:   int rval = GSL_CONTINUE;
                   9256:   int status = GSL_SUCCESS;
                   9257:   double ssval;
                   9258: #endif
                   9259:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9260:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9261:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9262:   int jj, ll, li, lj, lk;
1.136     brouard  9263:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9264:   int num_filled;
1.136     brouard  9265:   int itimes;
                   9266:   int NDIM=2;
                   9267:   int vpopbased=0;
1.235     brouard  9268:   int nres=0;
1.136     brouard  9269: 
1.164     brouard  9270:   char ca[32], cb[32];
1.136     brouard  9271:   /*  FILE *fichtm; *//* Html File */
                   9272:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9273:   struct stat info;
1.191     brouard  9274:   double agedeb=0.;
1.194     brouard  9275: 
                   9276:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9277:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9278: 
1.165     brouard  9279:   double fret;
1.191     brouard  9280:   double dum=0.; /* Dummy variable */
1.136     brouard  9281:   double ***p3mat;
1.218     brouard  9282:   /* double ***mobaverage; */
1.164     brouard  9283: 
                   9284:   char line[MAXLINE];
1.197     brouard  9285:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9286: 
1.234     brouard  9287:   char  modeltemp[MAXLINE];
1.230     brouard  9288:   char resultline[MAXLINE];
                   9289:   
1.136     brouard  9290:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9291:   char *tok, *val; /* pathtot */
1.136     brouard  9292:   int firstobs=1, lastobs=10;
1.195     brouard  9293:   int c,  h , cpt, c2;
1.191     brouard  9294:   int jl=0;
                   9295:   int i1, j1, jk, stepsize=0;
1.194     brouard  9296:   int count=0;
                   9297: 
1.164     brouard  9298:   int *tab; 
1.136     brouard  9299:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9300:   int backcast=0;
1.136     brouard  9301:   int mobilav=0,popforecast=0;
1.191     brouard  9302:   int hstepm=0, nhstepm=0;
1.136     brouard  9303:   int agemortsup;
                   9304:   float  sumlpop=0.;
                   9305:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9306:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9307: 
1.191     brouard  9308:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9309:   double ftolpl=FTOL;
                   9310:   double **prlim;
1.217     brouard  9311:   double **bprlim;
1.136     brouard  9312:   double ***param; /* Matrix of parameters */
                   9313:   double  *p;
                   9314:   double **matcov; /* Matrix of covariance */
1.203     brouard  9315:   double **hess; /* Hessian matrix */
1.136     brouard  9316:   double ***delti3; /* Scale */
                   9317:   double *delti; /* Scale */
                   9318:   double ***eij, ***vareij;
                   9319:   double **varpl; /* Variances of prevalence limits by age */
                   9320:   double *epj, vepp;
1.164     brouard  9321: 
1.136     brouard  9322:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9323:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9324: 
1.136     brouard  9325:   double **ximort;
1.145     brouard  9326:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9327:   int *dcwave;
                   9328: 
1.164     brouard  9329:   char z[1]="c";
1.136     brouard  9330: 
                   9331:   /*char  *strt;*/
                   9332:   char strtend[80];
1.126     brouard  9333: 
1.164     brouard  9334: 
1.126     brouard  9335: /*   setlocale (LC_ALL, ""); */
                   9336: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9337: /*   textdomain (PACKAGE); */
                   9338: /*   setlocale (LC_CTYPE, ""); */
                   9339: /*   setlocale (LC_MESSAGES, ""); */
                   9340: 
                   9341:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9342:   rstart_time = time(NULL);  
                   9343:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9344:   start_time = *localtime(&rstart_time);
1.126     brouard  9345:   curr_time=start_time;
1.157     brouard  9346:   /*tml = *localtime(&start_time.tm_sec);*/
                   9347:   /* strcpy(strstart,asctime(&tml)); */
                   9348:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9349: 
                   9350: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9351: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9352: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9353: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9354: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9355: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9356: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9357: /*   strt=asctime(&tmg); */
                   9358: /*   printf("Time(after) =%s",strstart);  */
                   9359: /*  (void) time (&time_value);
                   9360: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9361: *  tm = *localtime(&time_value);
                   9362: *  strstart=asctime(&tm);
                   9363: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9364: */
                   9365: 
                   9366:   nberr=0; /* Number of errors and warnings */
                   9367:   nbwarn=0;
1.184     brouard  9368: #ifdef WIN32
                   9369:   _getcwd(pathcd, size);
                   9370: #else
1.126     brouard  9371:   getcwd(pathcd, size);
1.184     brouard  9372: #endif
1.191     brouard  9373:   syscompilerinfo(0);
1.196     brouard  9374:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9375:   if(argc <=1){
                   9376:     printf("\nEnter the parameter file name: ");
1.205     brouard  9377:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9378:       printf("ERROR Empty parameter file name\n");
                   9379:       goto end;
                   9380:     }
1.126     brouard  9381:     i=strlen(pathr);
                   9382:     if(pathr[i-1]=='\n')
                   9383:       pathr[i-1]='\0';
1.156     brouard  9384:     i=strlen(pathr);
1.205     brouard  9385:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9386:       pathr[i-1]='\0';
1.205     brouard  9387:     }
                   9388:     i=strlen(pathr);
                   9389:     if( i==0 ){
                   9390:       printf("ERROR Empty parameter file name\n");
                   9391:       goto end;
                   9392:     }
                   9393:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9394:       printf("Pathr |%s|\n",pathr);
                   9395:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9396:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9397:       strcpy (pathtot, val);
                   9398:       if(pathr[0] == '\0') break; /* Dirty */
                   9399:     }
                   9400:   }
                   9401:   else{
                   9402:     strcpy(pathtot,argv[1]);
                   9403:   }
                   9404:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9405:   /*cygwin_split_path(pathtot,path,optionfile);
                   9406:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9407:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9408: 
                   9409:   /* Split argv[0], imach program to get pathimach */
                   9410:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9411:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9412:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9413:  /*   strcpy(pathimach,argv[0]); */
                   9414:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9415:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9416:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9417: #ifdef WIN32
                   9418:   _chdir(path); /* Can be a relative path */
                   9419:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9420: #else
1.126     brouard  9421:   chdir(path); /* Can be a relative path */
1.184     brouard  9422:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9423: #endif
                   9424:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9425:   strcpy(command,"mkdir ");
                   9426:   strcat(command,optionfilefiname);
                   9427:   if((outcmd=system(command)) != 0){
1.169     brouard  9428:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9429:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9430:     /* fclose(ficlog); */
                   9431: /*     exit(1); */
                   9432:   }
                   9433: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9434: /*     perror("mkdir"); */
                   9435: /*   } */
                   9436: 
                   9437:   /*-------- arguments in the command line --------*/
                   9438: 
1.186     brouard  9439:   /* Main Log file */
1.126     brouard  9440:   strcat(filelog, optionfilefiname);
                   9441:   strcat(filelog,".log");    /* */
                   9442:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9443:     printf("Problem with logfile %s\n",filelog);
                   9444:     goto end;
                   9445:   }
                   9446:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9447:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9448:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9449:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9450:  path=%s \n\
                   9451:  optionfile=%s\n\
                   9452:  optionfilext=%s\n\
1.156     brouard  9453:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9454: 
1.197     brouard  9455:   syscompilerinfo(1);
1.167     brouard  9456: 
1.126     brouard  9457:   printf("Local time (at start):%s",strstart);
                   9458:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9459:   fflush(ficlog);
                   9460: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9461: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9462: 
                   9463:   /* */
                   9464:   strcpy(fileres,"r");
                   9465:   strcat(fileres, optionfilefiname);
1.201     brouard  9466:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9467:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9468:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9469: 
1.186     brouard  9470:   /* Main ---------arguments file --------*/
1.126     brouard  9471: 
                   9472:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9473:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9474:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9475:     fflush(ficlog);
1.149     brouard  9476:     /* goto end; */
                   9477:     exit(70); 
1.126     brouard  9478:   }
                   9479: 
                   9480: 
                   9481: 
                   9482:   strcpy(filereso,"o");
1.201     brouard  9483:   strcat(filereso,fileresu);
1.126     brouard  9484:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9485:     printf("Problem with Output resultfile: %s\n", filereso);
                   9486:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9487:     fflush(ficlog);
                   9488:     goto end;
                   9489:   }
                   9490: 
                   9491:   /* Reads comments: lines beginning with '#' */
                   9492:   numlinepar=0;
1.197     brouard  9493: 
                   9494:     /* First parameter line */
                   9495:   while(fgets(line, MAXLINE, ficpar)) {
                   9496:     /* If line starts with a # it is a comment */
                   9497:     if (line[0] == '#') {
                   9498:       numlinepar++;
                   9499:       fputs(line,stdout);
                   9500:       fputs(line,ficparo);
                   9501:       fputs(line,ficlog);
                   9502:       continue;
                   9503:     }else
                   9504:       break;
                   9505:   }
                   9506:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9507:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9508:     if (num_filled != 5) {
                   9509:       printf("Should be 5 parameters\n");
                   9510:     }
1.126     brouard  9511:     numlinepar++;
1.197     brouard  9512:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9513:   }
                   9514:   /* Second parameter line */
                   9515:   while(fgets(line, MAXLINE, ficpar)) {
                   9516:     /* If line starts with a # it is a comment */
                   9517:     if (line[0] == '#') {
                   9518:       numlinepar++;
                   9519:       fputs(line,stdout);
                   9520:       fputs(line,ficparo);
                   9521:       fputs(line,ficlog);
                   9522:       continue;
                   9523:     }else
                   9524:       break;
                   9525:   }
1.223     brouard  9526:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   9527:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9528:     if (num_filled != 11) {
                   9529:       printf("Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1  nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
1.209     brouard  9530:       printf("but line=%s\n",line);
1.197     brouard  9531:     }
1.223     brouard  9532:     printf("ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
1.126     brouard  9533:   }
1.203     brouard  9534:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9535:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9536:   /* Third parameter line */
                   9537:   while(fgets(line, MAXLINE, ficpar)) {
                   9538:     /* If line starts with a # it is a comment */
                   9539:     if (line[0] == '#') {
                   9540:       numlinepar++;
                   9541:       fputs(line,stdout);
                   9542:       fputs(line,ficparo);
                   9543:       fputs(line,ficlog);
                   9544:       continue;
                   9545:     }else
                   9546:       break;
                   9547:   }
1.201     brouard  9548:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9549:     if (num_filled == 0)
                   9550:             model[0]='\0';
                   9551:     else if (num_filled != 1){
1.197     brouard  9552:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9553:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9554:       model[0]='\0';
                   9555:       goto end;
                   9556:     }
                   9557:     else{
                   9558:       if (model[0]=='+'){
                   9559:        for(i=1; i<=strlen(model);i++)
                   9560:          modeltemp[i-1]=model[i];
1.201     brouard  9561:        strcpy(model,modeltemp); 
1.197     brouard  9562:       }
                   9563:     }
1.199     brouard  9564:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9565:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9566:   }
                   9567:   /* 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); */
                   9568:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9569:   /* 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.223     brouard  9570:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
                   9571:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
1.126     brouard  9572:   fflush(ficlog);
1.190     brouard  9573:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9574:   if(model[0]=='#'){
1.187     brouard  9575:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9576:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9577:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9578:     if(mle != -1){
                   9579:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9580:       exit(1);
                   9581:     }
                   9582:   }
1.126     brouard  9583:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9584:     ungetc(c,ficpar);
                   9585:     fgets(line, MAXLINE, ficpar);
                   9586:     numlinepar++;
1.195     brouard  9587:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9588:       z[0]=line[1];
                   9589:     }
                   9590:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9591:     fputs(line, stdout);
                   9592:     //puts(line);
1.126     brouard  9593:     fputs(line,ficparo);
                   9594:     fputs(line,ficlog);
                   9595:   }
                   9596:   ungetc(c,ficpar);
                   9597: 
                   9598:    
1.145     brouard  9599:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9600:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9601:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9602:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9603:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9604:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9605:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9606:   */
                   9607:   if (strlen(model)>1) 
1.187     brouard  9608:     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  9609:   else
1.187     brouard  9610:     ncovmodel=2; /* Constant and age */
1.133     brouard  9611:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9612:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9613:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9614:     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);
                   9615:     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);
                   9616:     fflush(stdout);
                   9617:     fclose (ficlog);
                   9618:     goto end;
                   9619:   }
1.126     brouard  9620:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9621:   delti=delti3[1][1];
                   9622:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9623:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9624:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9625:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9626:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9627:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9628:     fclose (ficparo);
                   9629:     fclose (ficlog);
                   9630:     goto end;
                   9631:     exit(0);
1.220     brouard  9632:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9633:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9634:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9635:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9636:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9637:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9638:     hess=matrix(1,npar,1,npar);
1.220     brouard  9639:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9640:     /* Read guessed parameters */
1.126     brouard  9641:     /* Reads comments: lines beginning with '#' */
                   9642:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9643:       ungetc(c,ficpar);
                   9644:       fgets(line, MAXLINE, ficpar);
                   9645:       numlinepar++;
1.141     brouard  9646:       fputs(line,stdout);
1.126     brouard  9647:       fputs(line,ficparo);
                   9648:       fputs(line,ficlog);
                   9649:     }
                   9650:     ungetc(c,ficpar);
                   9651:     
                   9652:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9653:     for(i=1; i <=nlstate; i++){
1.234     brouard  9654:       j=0;
1.126     brouard  9655:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9656:        if(jj==i) continue;
                   9657:        j++;
                   9658:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9659:        if ((i1 != i) || (j1 != jj)){
                   9660:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9661: It might be a problem of design; if ncovcol and the model are correct\n \
                   9662: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9663:          exit(1);
                   9664:        }
                   9665:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9666:        if(mle==1)
                   9667:          printf("%1d%1d",i,jj);
                   9668:        fprintf(ficlog,"%1d%1d",i,jj);
                   9669:        for(k=1; k<=ncovmodel;k++){
                   9670:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9671:          if(mle==1){
                   9672:            printf(" %lf",param[i][j][k]);
                   9673:            fprintf(ficlog," %lf",param[i][j][k]);
                   9674:          }
                   9675:          else
                   9676:            fprintf(ficlog," %lf",param[i][j][k]);
                   9677:          fprintf(ficparo," %lf",param[i][j][k]);
                   9678:        }
                   9679:        fscanf(ficpar,"\n");
                   9680:        numlinepar++;
                   9681:        if(mle==1)
                   9682:          printf("\n");
                   9683:        fprintf(ficlog,"\n");
                   9684:        fprintf(ficparo,"\n");
1.126     brouard  9685:       }
                   9686:     }  
                   9687:     fflush(ficlog);
1.234     brouard  9688:     
1.145     brouard  9689:     /* Reads scales values */
1.126     brouard  9690:     p=param[1][1];
                   9691:     
                   9692:     /* Reads comments: lines beginning with '#' */
                   9693:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9694:       ungetc(c,ficpar);
                   9695:       fgets(line, MAXLINE, ficpar);
                   9696:       numlinepar++;
1.141     brouard  9697:       fputs(line,stdout);
1.126     brouard  9698:       fputs(line,ficparo);
                   9699:       fputs(line,ficlog);
                   9700:     }
                   9701:     ungetc(c,ficpar);
                   9702: 
                   9703:     for(i=1; i <=nlstate; i++){
                   9704:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9705:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9706:        if ( (i1-i) * (j1-j) != 0){
                   9707:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9708:          exit(1);
                   9709:        }
                   9710:        printf("%1d%1d",i,j);
                   9711:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9712:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9713:        for(k=1; k<=ncovmodel;k++){
                   9714:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9715:          printf(" %le",delti3[i][j][k]);
                   9716:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9717:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9718:        }
                   9719:        fscanf(ficpar,"\n");
                   9720:        numlinepar++;
                   9721:        printf("\n");
                   9722:        fprintf(ficparo,"\n");
                   9723:        fprintf(ficlog,"\n");
1.126     brouard  9724:       }
                   9725:     }
                   9726:     fflush(ficlog);
1.234     brouard  9727:     
1.145     brouard  9728:     /* Reads covariance matrix */
1.126     brouard  9729:     delti=delti3[1][1];
1.220     brouard  9730:                
                   9731:                
1.126     brouard  9732:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
1.220     brouard  9733:                
1.126     brouard  9734:     /* Reads comments: lines beginning with '#' */
                   9735:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9736:       ungetc(c,ficpar);
                   9737:       fgets(line, MAXLINE, ficpar);
                   9738:       numlinepar++;
1.141     brouard  9739:       fputs(line,stdout);
1.126     brouard  9740:       fputs(line,ficparo);
                   9741:       fputs(line,ficlog);
                   9742:     }
                   9743:     ungetc(c,ficpar);
1.220     brouard  9744:                
1.126     brouard  9745:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9746:     hess=matrix(1,npar,1,npar);
1.131     brouard  9747:     for(i=1; i <=npar; i++)
                   9748:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9749:                
1.194     brouard  9750:     /* Scans npar lines */
1.126     brouard  9751:     for(i=1; i <=npar; i++){
1.226     brouard  9752:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  9753:       if(count != 3){
1.226     brouard  9754:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9755: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9756: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9757:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9758: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9759: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9760:        exit(1);
1.220     brouard  9761:       }else{
1.226     brouard  9762:        if(mle==1)
                   9763:          printf("%1d%1d%d",i1,j1,jk);
                   9764:       }
                   9765:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   9766:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  9767:       for(j=1; j <=i; j++){
1.226     brouard  9768:        fscanf(ficpar," %le",&matcov[i][j]);
                   9769:        if(mle==1){
                   9770:          printf(" %.5le",matcov[i][j]);
                   9771:        }
                   9772:        fprintf(ficlog," %.5le",matcov[i][j]);
                   9773:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  9774:       }
                   9775:       fscanf(ficpar,"\n");
                   9776:       numlinepar++;
                   9777:       if(mle==1)
1.220     brouard  9778:                                printf("\n");
1.126     brouard  9779:       fprintf(ficlog,"\n");
                   9780:       fprintf(ficparo,"\n");
                   9781:     }
1.194     brouard  9782:     /* End of read covariance matrix npar lines */
1.126     brouard  9783:     for(i=1; i <=npar; i++)
                   9784:       for(j=i+1;j<=npar;j++)
1.226     brouard  9785:        matcov[i][j]=matcov[j][i];
1.126     brouard  9786:     
                   9787:     if(mle==1)
                   9788:       printf("\n");
                   9789:     fprintf(ficlog,"\n");
                   9790:     
                   9791:     fflush(ficlog);
                   9792:     
                   9793:     /*-------- Rewriting parameter file ----------*/
                   9794:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   9795:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   9796:     strcat(rfileres,".");    /* */
                   9797:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   9798:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  9799:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   9800:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  9801:     }
                   9802:     fprintf(ficres,"#%s\n",version);
                   9803:   }    /* End of mle != -3 */
1.218     brouard  9804:   
1.186     brouard  9805:   /*  Main data
                   9806:    */
1.126     brouard  9807:   n= lastobs;
                   9808:   num=lvector(1,n);
                   9809:   moisnais=vector(1,n);
                   9810:   annais=vector(1,n);
                   9811:   moisdc=vector(1,n);
                   9812:   andc=vector(1,n);
1.220     brouard  9813:   weight=vector(1,n);
1.126     brouard  9814:   agedc=vector(1,n);
                   9815:   cod=ivector(1,n);
1.220     brouard  9816:   for(i=1;i<=n;i++){
1.234     brouard  9817:     num[i]=0;
                   9818:     moisnais[i]=0;
                   9819:     annais[i]=0;
                   9820:     moisdc[i]=0;
                   9821:     andc[i]=0;
                   9822:     agedc[i]=0;
                   9823:     cod[i]=0;
                   9824:     weight[i]=1.0; /* Equal weights, 1 by default */
                   9825:   }
1.126     brouard  9826:   mint=matrix(1,maxwav,1,n);
                   9827:   anint=matrix(1,maxwav,1,n);
1.131     brouard  9828:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  9829:   tab=ivector(1,NCOVMAX);
1.144     brouard  9830:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  9831:   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  9832: 
1.136     brouard  9833:   /* Reads data from file datafile */
                   9834:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   9835:     goto end;
                   9836: 
                   9837:   /* Calculation of the number of parameters from char model */
1.234     brouard  9838:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  9839:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   9840:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   9841:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   9842:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  9843:   */
                   9844:   
                   9845:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   9846:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   9847:   TvarsD=ivector(1,NCOVMAX); /*  */
                   9848:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   9849:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  9850:   TvarF=ivector(1,NCOVMAX); /*  */
                   9851:   TvarFind=ivector(1,NCOVMAX); /*  */
                   9852:   TvarV=ivector(1,NCOVMAX); /*  */
                   9853:   TvarVind=ivector(1,NCOVMAX); /*  */
                   9854:   TvarA=ivector(1,NCOVMAX); /*  */
                   9855:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  9856:   TvarFD=ivector(1,NCOVMAX); /*  */
                   9857:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   9858:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   9859:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   9860:   TvarVD=ivector(1,NCOVMAX); /*  */
                   9861:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   9862:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   9863:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   9864: 
1.230     brouard  9865:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  9866:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  9867:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   9868:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   9869:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  9870:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   9871:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   9872:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   9873:   */
                   9874:   /* For model-covariate k tells which data-covariate to use but
                   9875:     because this model-covariate is a construction we invent a new column
                   9876:     ncovcol + k1
                   9877:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   9878:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  9879:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   9880:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  9881:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   9882:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  9883:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  9884:   */
1.145     brouard  9885:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   9886:   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  9887:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   9888:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  9889:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  9890:                         4 covariates (3 plus signs)
                   9891:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   9892:                      */  
1.230     brouard  9893:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  9894:                                * individual dummy, fixed or varying:
                   9895:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   9896:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  9897:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   9898:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   9899:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   9900:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   9901:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  9902:                                * individual quantitative, fixed or varying:
                   9903:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   9904:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   9905:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  9906: /* Main decodemodel */
                   9907: 
1.187     brouard  9908: 
1.223     brouard  9909:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  9910:     goto end;
                   9911: 
1.137     brouard  9912:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   9913:     nbwarn++;
                   9914:     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); 
                   9915:     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); 
                   9916:   }
1.136     brouard  9917:     /*  if(mle==1){*/
1.137     brouard  9918:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   9919:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  9920:   }
                   9921: 
                   9922:     /*-calculation of age at interview from date of interview and age at death -*/
                   9923:   agev=matrix(1,maxwav,1,imx);
                   9924: 
                   9925:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   9926:     goto end;
                   9927: 
1.126     brouard  9928: 
1.136     brouard  9929:   agegomp=(int)agemin;
                   9930:   free_vector(moisnais,1,n);
                   9931:   free_vector(annais,1,n);
1.126     brouard  9932:   /* free_matrix(mint,1,maxwav,1,n);
                   9933:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  9934:   /* free_vector(moisdc,1,n); */
                   9935:   /* free_vector(andc,1,n); */
1.145     brouard  9936:   /* */
                   9937:   
1.126     brouard  9938:   wav=ivector(1,imx);
1.214     brouard  9939:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9940:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9941:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9942:   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.*/
                   9943:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   9944:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  9945:    
                   9946:   /* Concatenates waves */
1.214     brouard  9947:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   9948:      Death is a valid wave (if date is known).
                   9949:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   9950:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   9951:      and mw[mi+1][i]. dh depends on stepm.
                   9952:   */
                   9953: 
1.126     brouard  9954:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  9955:   /* */
                   9956:  
1.215     brouard  9957:   free_vector(moisdc,1,n);
                   9958:   free_vector(andc,1,n);
                   9959: 
1.126     brouard  9960:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   9961:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   9962:   ncodemax[1]=1;
1.145     brouard  9963:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  9964:   cptcoveff=0;
1.220     brouard  9965:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   9966:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  9967:   }
                   9968:   
                   9969:   ncovcombmax=pow(2,cptcoveff);
                   9970:   invalidvarcomb=ivector(1, ncovcombmax); 
                   9971:   for(i=1;i<ncovcombmax;i++)
                   9972:     invalidvarcomb[i]=0;
                   9973:   
1.211     brouard  9974:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  9975:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  9976:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  9977:   
1.200     brouard  9978:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  9979:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  9980:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  9981:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   9982:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   9983:    * (currently 0 or 1) in the data.
                   9984:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   9985:    * corresponding modality (h,j).
                   9986:    */
                   9987: 
1.145     brouard  9988:   h=0;
                   9989:   /*if (cptcovn > 0) */
1.126     brouard  9990:   m=pow(2,cptcoveff);
                   9991:  
1.144     brouard  9992:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  9993:           * For k=4 covariates, h goes from 1 to m=2**k
                   9994:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   9995:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  9996:           *     h\k   1     2     3     4
1.143     brouard  9997:           *______________________________  
                   9998:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   9999:           *     2     2     1     1     1
                   10000:           *     3 i=2 1     2     1     1
                   10001:           *     4     2     2     1     1
                   10002:           *     5 i=3 1 i=2 1     2     1
                   10003:           *     6     2     1     2     1
                   10004:           *     7 i=4 1     2     2     1
                   10005:           *     8     2     2     2     1
1.197     brouard  10006:           *     9 i=5 1 i=3 1 i=2 1     2
                   10007:           *    10     2     1     1     2
                   10008:           *    11 i=6 1     2     1     2
                   10009:           *    12     2     2     1     2
                   10010:           *    13 i=7 1 i=4 1     2     2    
                   10011:           *    14     2     1     2     2
                   10012:           *    15 i=8 1     2     2     2
                   10013:           *    16     2     2     2     2
1.143     brouard  10014:           */
1.212     brouard  10015:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10016:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10017:      * and the value of each covariate?
                   10018:      * V1=1, V2=1, V3=2, V4=1 ?
                   10019:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10020:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10021:      * In order to get the real value in the data, we use nbcode
                   10022:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10023:      * We are keeping this crazy system in order to be able (in the future?) 
                   10024:      * to have more than 2 values (0 or 1) for a covariate.
                   10025:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10026:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10027:      *              bbbbbbbb
                   10028:      *              76543210     
                   10029:      *   h-1        00000101 (6-1=5)
1.219     brouard  10030:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10031:      *           &
                   10032:      *     1        00000001 (1)
1.219     brouard  10033:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10034:      *          +1= 00000001 =1 
1.211     brouard  10035:      *
                   10036:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10037:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10038:      *    >>k'            11
                   10039:      *          &   00000001
                   10040:      *            = 00000001
                   10041:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10042:      * Reverse h=6 and m=16?
                   10043:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10044:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10045:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10046:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10047:      * V3=decodtabm(14,3,2**4)=2
                   10048:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10049:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10050:      *          &1 000000001
                   10051:      *           = 000000001
                   10052:      *         +1= 000000010 =2
                   10053:      *                  2211
                   10054:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10055:      *                  V3=2
1.220     brouard  10056:                 * codtabm and decodtabm are identical
1.211     brouard  10057:      */
                   10058: 
1.145     brouard  10059: 
                   10060:  free_ivector(Ndum,-1,NCOVMAX);
                   10061: 
                   10062: 
1.126     brouard  10063:     
1.186     brouard  10064:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10065:   strcpy(optionfilegnuplot,optionfilefiname);
                   10066:   if(mle==-3)
1.201     brouard  10067:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10068:   strcat(optionfilegnuplot,".gp");
                   10069: 
                   10070:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10071:     printf("Problem with file %s",optionfilegnuplot);
                   10072:   }
                   10073:   else{
1.204     brouard  10074:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10075:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10076:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10077:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10078:   }
                   10079:   /*  fclose(ficgp);*/
1.186     brouard  10080: 
                   10081: 
                   10082:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10083: 
                   10084:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10085:   if(mle==-3)
1.201     brouard  10086:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10087:   strcat(optionfilehtm,".htm");
                   10088:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10089:     printf("Problem with %s \n",optionfilehtm);
                   10090:     exit(0);
1.126     brouard  10091:   }
                   10092: 
                   10093:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10094:   strcat(optionfilehtmcov,"-cov.htm");
                   10095:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10096:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10097:   }
                   10098:   else{
                   10099:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10100: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10101: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10102:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10103:   }
                   10104: 
1.213     brouard  10105:   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  10106: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10107: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10108: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10109: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10110: \n\
                   10111: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10112:  <ul><li><h4>Parameter files</h4>\n\
                   10113:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10114:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10115:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10116:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10117:  - Date and time at start: %s</ul>\n",\
                   10118:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10119:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10120:          fileres,fileres,\
                   10121:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10122:   fflush(fichtm);
                   10123: 
                   10124:   strcpy(pathr,path);
                   10125:   strcat(pathr,optionfilefiname);
1.184     brouard  10126: #ifdef WIN32
                   10127:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10128: #else
1.126     brouard  10129:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10130: #endif
                   10131:          
1.126     brouard  10132:   
1.220     brouard  10133:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10134:                 and for any valid combination of covariates
1.126     brouard  10135:      and prints on file fileres'p'. */
1.227     brouard  10136:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10137:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10138: 
                   10139:   fprintf(fichtm,"\n");
                   10140:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10141: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10142: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10143:          imx,agemin,agemax,jmin,jmax,jmean);
                   10144:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10145:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10146:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10147:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10148:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10149: 
1.126     brouard  10150:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10151:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10152:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10153: 
                   10154:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10155:   /* For mortality only */
1.126     brouard  10156:   if (mle==-3){
1.136     brouard  10157:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10158:                for(i=1;i<=NDIM;i++)
                   10159:                        for(j=1;j<=NDIM;j++)
                   10160:                                ximort[i][j]=0.;
1.186     brouard  10161:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10162:     cens=ivector(1,n);
                   10163:     ageexmed=vector(1,n);
                   10164:     agecens=vector(1,n);
                   10165:     dcwave=ivector(1,n);
1.223     brouard  10166:                
1.126     brouard  10167:     for (i=1; i<=imx; i++){
                   10168:       dcwave[i]=-1;
                   10169:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10170:        if (s[m][i]>nlstate) {
                   10171:          dcwave[i]=m;
                   10172:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10173:          break;
                   10174:        }
1.126     brouard  10175:     }
1.226     brouard  10176:     
1.126     brouard  10177:     for (i=1; i<=imx; i++) {
                   10178:       if (wav[i]>0){
1.226     brouard  10179:        ageexmed[i]=agev[mw[1][i]][i];
                   10180:        j=wav[i];
                   10181:        agecens[i]=1.; 
                   10182:        
                   10183:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10184:          agecens[i]=agev[mw[j][i]][i];
                   10185:          cens[i]= 1;
                   10186:        }else if (ageexmed[i]< 1) 
                   10187:          cens[i]= -1;
                   10188:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10189:          cens[i]=0 ;
1.126     brouard  10190:       }
                   10191:       else cens[i]=-1;
                   10192:     }
                   10193:     
                   10194:     for (i=1;i<=NDIM;i++) {
                   10195:       for (j=1;j<=NDIM;j++)
1.226     brouard  10196:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10197:     }
                   10198:     
1.145     brouard  10199:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10200:     /*printf("%lf %lf", p[1], p[2]);*/
                   10201:     
                   10202:     
1.136     brouard  10203: #ifdef GSL
                   10204:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10205: #else
1.126     brouard  10206:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10207: #endif
1.201     brouard  10208:     strcpy(filerespow,"POW-MORT_"); 
                   10209:     strcat(filerespow,fileresu);
1.126     brouard  10210:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10211:       printf("Problem with resultfile: %s\n", filerespow);
                   10212:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10213:     }
1.136     brouard  10214: #ifdef GSL
                   10215:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10216: #else
1.126     brouard  10217:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10218: #endif
1.126     brouard  10219:     /*  for (i=1;i<=nlstate;i++)
                   10220:        for(j=1;j<=nlstate+ndeath;j++)
                   10221:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10222:     */
                   10223:     fprintf(ficrespow,"\n");
1.136     brouard  10224: #ifdef GSL
                   10225:     /* gsl starts here */ 
                   10226:     T = gsl_multimin_fminimizer_nmsimplex;
                   10227:     gsl_multimin_fminimizer *sfm = NULL;
                   10228:     gsl_vector *ss, *x;
                   10229:     gsl_multimin_function minex_func;
                   10230: 
                   10231:     /* Initial vertex size vector */
                   10232:     ss = gsl_vector_alloc (NDIM);
                   10233:     
                   10234:     if (ss == NULL){
                   10235:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10236:     }
                   10237:     /* Set all step sizes to 1 */
                   10238:     gsl_vector_set_all (ss, 0.001);
                   10239: 
                   10240:     /* Starting point */
1.126     brouard  10241:     
1.136     brouard  10242:     x = gsl_vector_alloc (NDIM);
                   10243:     
                   10244:     if (x == NULL){
                   10245:       gsl_vector_free(ss);
                   10246:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10247:     }
                   10248:   
                   10249:     /* Initialize method and iterate */
                   10250:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10251:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10252:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10253:     gsl_vector_set(x, 0, p[1]);
                   10254:     gsl_vector_set(x, 1, p[2]);
                   10255: 
                   10256:     minex_func.f = &gompertz_f;
                   10257:     minex_func.n = NDIM;
                   10258:     minex_func.params = (void *)&p; /* ??? */
                   10259:     
                   10260:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10261:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10262:     
                   10263:     printf("Iterations beginning .....\n\n");
                   10264:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10265: 
                   10266:     iteri=0;
                   10267:     while (rval == GSL_CONTINUE){
                   10268:       iteri++;
                   10269:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10270:       
                   10271:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10272:       fflush(0);
                   10273:       
                   10274:       if (status) 
                   10275:         break;
                   10276:       
                   10277:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10278:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10279:       
                   10280:       if (rval == GSL_SUCCESS)
                   10281:         printf ("converged to a local maximum at\n");
                   10282:       
                   10283:       printf("%5d ", iteri);
                   10284:       for (it = 0; it < NDIM; it++){
                   10285:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10286:       }
                   10287:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10288:     }
                   10289:     
                   10290:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10291:     
                   10292:     gsl_vector_free(x); /* initial values */
                   10293:     gsl_vector_free(ss); /* inital step size */
                   10294:     for (it=0; it<NDIM; it++){
                   10295:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10296:       fprintf(ficrespow," %.12lf", p[it]);
                   10297:     }
                   10298:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10299: #endif
                   10300: #ifdef POWELL
                   10301:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10302: #endif  
1.126     brouard  10303:     fclose(ficrespow);
                   10304:     
1.203     brouard  10305:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10306: 
                   10307:     for(i=1; i <=NDIM; i++)
                   10308:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10309:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10310:     
                   10311:     printf("\nCovariance matrix\n ");
1.203     brouard  10312:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10313:     for(i=1; i <=NDIM; i++) {
                   10314:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10315:                                printf("%f ",matcov[i][j]);
                   10316:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10317:       }
1.203     brouard  10318:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10319:     }
                   10320:     
                   10321:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10322:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10323:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10324:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10325:     }
1.126     brouard  10326:     lsurv=vector(1,AGESUP);
                   10327:     lpop=vector(1,AGESUP);
                   10328:     tpop=vector(1,AGESUP);
                   10329:     lsurv[agegomp]=100000;
                   10330:     
                   10331:     for (k=agegomp;k<=AGESUP;k++) {
                   10332:       agemortsup=k;
                   10333:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10334:     }
                   10335:     
                   10336:     for (k=agegomp;k<agemortsup;k++)
                   10337:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10338:     
                   10339:     for (k=agegomp;k<agemortsup;k++){
                   10340:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10341:       sumlpop=sumlpop+lpop[k];
                   10342:     }
                   10343:     
                   10344:     tpop[agegomp]=sumlpop;
                   10345:     for (k=agegomp;k<(agemortsup-3);k++){
                   10346:       /*  tpop[k+1]=2;*/
                   10347:       tpop[k+1]=tpop[k]-lpop[k];
                   10348:     }
                   10349:     
                   10350:     
                   10351:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10352:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10353:       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]);
                   10354:     
                   10355:     
                   10356:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10357:                ageminpar=50;
                   10358:                agemaxpar=100;
1.194     brouard  10359:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10360:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10361: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10362: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10363:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10364: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10365: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10366:     }else{
                   10367:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10368:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
1.201     brouard  10369:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10370:                }
1.201     brouard  10371:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10372:                     stepm, weightopt,\
                   10373:                     model,imx,p,matcov,agemortsup);
                   10374:     
                   10375:     free_vector(lsurv,1,AGESUP);
                   10376:     free_vector(lpop,1,AGESUP);
                   10377:     free_vector(tpop,1,AGESUP);
1.220     brouard  10378:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10379:     free_ivector(cens,1,n);
                   10380:     free_vector(agecens,1,n);
                   10381:     free_ivector(dcwave,1,n);
1.220     brouard  10382: #ifdef GSL
1.136     brouard  10383: #endif
1.186     brouard  10384:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10385:   /* Standard  */
                   10386:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10387:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10388:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10389:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10390:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10391:     for (k=1; k<=npar;k++)
                   10392:       printf(" %d %8.5f",k,p[k]);
                   10393:     printf("\n");
1.205     brouard  10394:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10395:       /* mlikeli uses func not funcone */
                   10396:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10397:     }
                   10398:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10399:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10400:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10401:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10402:     }
                   10403:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10404:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10405:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10406:     for (k=1; k<=npar;k++)
                   10407:       printf(" %d %8.5f",k,p[k]);
                   10408:     printf("\n");
                   10409:     
                   10410:     /*--------- results files --------------*/
1.224     brouard  10411:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, weightopt,model);
1.126     brouard  10412:     
                   10413:     
                   10414:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10415:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10416:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10417:     for(i=1,jk=1; i <=nlstate; i++){
                   10418:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10419:        if (k != i) {
                   10420:          printf("%d%d ",i,k);
                   10421:          fprintf(ficlog,"%d%d ",i,k);
                   10422:          fprintf(ficres,"%1d%1d ",i,k);
                   10423:          for(j=1; j <=ncovmodel; j++){
                   10424:            printf("%12.7f ",p[jk]);
                   10425:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10426:            fprintf(ficres,"%12.7f ",p[jk]);
                   10427:            jk++; 
                   10428:          }
                   10429:          printf("\n");
                   10430:          fprintf(ficlog,"\n");
                   10431:          fprintf(ficres,"\n");
                   10432:        }
1.126     brouard  10433:       }
                   10434:     }
1.203     brouard  10435:     if(mle != 0){
                   10436:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10437:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10438:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10439:       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");
                   10440:       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");
                   10441:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10442:        for(k=1; k <=(nlstate+ndeath); k++){
                   10443:          if (k != i) {
                   10444:            printf("%d%d ",i,k);
                   10445:            fprintf(ficlog,"%d%d ",i,k);
                   10446:            for(j=1; j <=ncovmodel; j++){
                   10447:              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]));
                   10448:              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]));
                   10449:              jk++; 
                   10450:            }
                   10451:            printf("\n");
                   10452:            fprintf(ficlog,"\n");
                   10453:          }
                   10454:        }
1.193     brouard  10455:       }
1.203     brouard  10456:     } /* end of hesscov and Wald tests */
1.225     brouard  10457:     
1.203     brouard  10458:     /*  */
1.126     brouard  10459:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10460:     printf("# Scales (for hessian or gradient estimation)\n");
                   10461:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10462:     for(i=1,jk=1; i <=nlstate; i++){
                   10463:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10464:        if (j!=i) {
                   10465:          fprintf(ficres,"%1d%1d",i,j);
                   10466:          printf("%1d%1d",i,j);
                   10467:          fprintf(ficlog,"%1d%1d",i,j);
                   10468:          for(k=1; k<=ncovmodel;k++){
                   10469:            printf(" %.5e",delti[jk]);
                   10470:            fprintf(ficlog," %.5e",delti[jk]);
                   10471:            fprintf(ficres," %.5e",delti[jk]);
                   10472:            jk++;
                   10473:          }
                   10474:          printf("\n");
                   10475:          fprintf(ficlog,"\n");
                   10476:          fprintf(ficres,"\n");
                   10477:        }
1.126     brouard  10478:       }
                   10479:     }
                   10480:     
                   10481:     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  10482:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10483:       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");
                   10484:     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");
                   10485:     /* # 121 Var(a12)\n\ */
                   10486:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10487:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10488:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10489:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10490:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10491:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10492:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10493:     
                   10494:     
                   10495:     /* Just to have a covariance matrix which will be more understandable
                   10496:        even is we still don't want to manage dictionary of variables
                   10497:     */
                   10498:     for(itimes=1;itimes<=2;itimes++){
                   10499:       jj=0;
                   10500:       for(i=1; i <=nlstate; i++){
1.225     brouard  10501:        for(j=1; j <=nlstate+ndeath; j++){
                   10502:          if(j==i) continue;
                   10503:          for(k=1; k<=ncovmodel;k++){
                   10504:            jj++;
                   10505:            ca[0]= k+'a'-1;ca[1]='\0';
                   10506:            if(itimes==1){
                   10507:              if(mle>=1)
                   10508:                printf("#%1d%1d%d",i,j,k);
                   10509:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10510:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10511:            }else{
                   10512:              if(mle>=1)
                   10513:                printf("%1d%1d%d",i,j,k);
                   10514:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10515:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10516:            }
                   10517:            ll=0;
                   10518:            for(li=1;li <=nlstate; li++){
                   10519:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10520:                if(lj==li) continue;
                   10521:                for(lk=1;lk<=ncovmodel;lk++){
                   10522:                  ll++;
                   10523:                  if(ll<=jj){
                   10524:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10525:                    if(ll<jj){
                   10526:                      if(itimes==1){
                   10527:                        if(mle>=1)
                   10528:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10529:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10530:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10531:                      }else{
                   10532:                        if(mle>=1)
                   10533:                          printf(" %.5e",matcov[jj][ll]); 
                   10534:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10535:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10536:                      }
                   10537:                    }else{
                   10538:                      if(itimes==1){
                   10539:                        if(mle>=1)
                   10540:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10541:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10542:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10543:                      }else{
                   10544:                        if(mle>=1)
                   10545:                          printf(" %.7e",matcov[jj][ll]); 
                   10546:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10547:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10548:                      }
                   10549:                    }
                   10550:                  }
                   10551:                } /* end lk */
                   10552:              } /* end lj */
                   10553:            } /* end li */
                   10554:            if(mle>=1)
                   10555:              printf("\n");
                   10556:            fprintf(ficlog,"\n");
                   10557:            fprintf(ficres,"\n");
                   10558:            numlinepar++;
                   10559:          } /* end k*/
                   10560:        } /*end j */
1.126     brouard  10561:       } /* end i */
                   10562:     } /* end itimes */
                   10563:     
                   10564:     fflush(ficlog);
                   10565:     fflush(ficres);
1.225     brouard  10566:     while(fgets(line, MAXLINE, ficpar)) {
                   10567:       /* If line starts with a # it is a comment */
                   10568:       if (line[0] == '#') {
                   10569:        numlinepar++;
                   10570:        fputs(line,stdout);
                   10571:        fputs(line,ficparo);
                   10572:        fputs(line,ficlog);
                   10573:        continue;
                   10574:       }else
                   10575:        break;
                   10576:     }
                   10577:     
1.209     brouard  10578:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10579:     /*   ungetc(c,ficpar); */
                   10580:     /*   fgets(line, MAXLINE, ficpar); */
                   10581:     /*   fputs(line,stdout); */
                   10582:     /*   fputs(line,ficparo); */
                   10583:     /* } */
                   10584:     /* ungetc(c,ficpar); */
1.126     brouard  10585:     
                   10586:     estepm=0;
1.209     brouard  10587:     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){
1.225     brouard  10588:       
                   10589:       if (num_filled != 6) {
                   10590:        printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   10591:        fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   10592:        goto end;
                   10593:       }
                   10594:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10595:     }
                   10596:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10597:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10598:     
1.209     brouard  10599:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10600:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10601:     if (fage <= 2) {
                   10602:       bage = ageminpar;
                   10603:       fage = agemaxpar;
                   10604:     }
                   10605:     
                   10606:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10607:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10608:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10609:                
1.186     brouard  10610:     /* Other stuffs, more or less useful */    
1.126     brouard  10611:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10612:       ungetc(c,ficpar);
                   10613:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10614:       fputs(line,stdout);
1.126     brouard  10615:       fputs(line,ficparo);
                   10616:     }
                   10617:     ungetc(c,ficpar);
                   10618:     
                   10619:     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);
                   10620:     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);
                   10621:     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);
                   10622:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10623:     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);
                   10624:     
                   10625:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10626:       ungetc(c,ficpar);
                   10627:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10628:       fputs(line,stdout);
1.126     brouard  10629:       fputs(line,ficparo);
                   10630:     }
                   10631:     ungetc(c,ficpar);
                   10632:     
                   10633:     
                   10634:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10635:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10636:     
                   10637:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10638:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10639:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10640:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10641:     
                   10642:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10643:       ungetc(c,ficpar);
                   10644:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10645:       fputs(line,stdout);
1.126     brouard  10646:       fputs(line,ficparo);
                   10647:     }
                   10648:     ungetc(c,ficpar);
                   10649:     
                   10650:     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);
                   10651:     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);
                   10652:     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);
                   10653:     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);
                   10654:     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);
                   10655:     /* day and month of proj2 are not used but only year anproj2.*/
                   10656:     
1.217     brouard  10657:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10658:       ungetc(c,ficpar);
                   10659:       fgets(line, MAXLINE, ficpar);
                   10660:       fputs(line,stdout);
                   10661:       fputs(line,ficparo);
                   10662:     }
                   10663:     ungetc(c,ficpar);
                   10664:     
                   10665:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.223     brouard  10666:     fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   10667:     fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   10668:     fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
1.217     brouard  10669:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10670:     
1.230     brouard  10671:     /* Results */
1.235     brouard  10672:     nresult=0;
1.230     brouard  10673:     while(fgets(line, MAXLINE, ficpar)) {
                   10674:       /* If line starts with a # it is a comment */
                   10675:       if (line[0] == '#') {
                   10676:        numlinepar++;
                   10677:        fputs(line,stdout);
                   10678:        fputs(line,ficparo);
                   10679:        fputs(line,ficlog);
                   10680:        continue;
                   10681:       }else
                   10682:        break;
                   10683:     }
                   10684:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   10685:       if (num_filled == 0)
                   10686:        resultline[0]='\0';
                   10687:       else if (num_filled != 1){
                   10688:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10689:       }
1.235     brouard  10690:       nresult++; /* Sum of resultlines */
                   10691:       printf("Result %d: result=%s\n",nresult, resultline);
                   10692:       if(nresult > MAXRESULTLINES){
                   10693:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10694:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10695:        goto end;
                   10696:       }
                   10697:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.230     brouard  10698:       while(fgets(line, MAXLINE, ficpar)) {
                   10699:        /* If line starts with a # it is a comment */
                   10700:        if (line[0] == '#') {
                   10701:          numlinepar++;
                   10702:          fputs(line,stdout);
                   10703:          fputs(line,ficparo);
                   10704:          fputs(line,ficlog);
                   10705:          continue;
                   10706:        }else
                   10707:          break;
                   10708:       }
                   10709:       if (feof(ficpar))
                   10710:        break;
                   10711:       else{ /* Processess output results for this combination of covariate values */
                   10712:       }                                   
                   10713:     }
                   10714: 
                   10715: 
1.126     brouard  10716:     
1.230     brouard  10717:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10718:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10719:     
                   10720:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10721:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10722:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10723: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10724: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10725:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10726: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10727: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10728:     }else{
1.218     brouard  10729:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10730:     }
                   10731:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10732:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10733:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10734:                
1.225     brouard  10735:     /*------------ free_vector  -------------*/
                   10736:     /*  chdir(path); */
1.220     brouard  10737:                
1.215     brouard  10738:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10739:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10740:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   10741:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  10742:     free_lvector(num,1,n);
                   10743:     free_vector(agedc,1,n);
                   10744:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   10745:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   10746:     fclose(ficparo);
                   10747:     fclose(ficres);
1.220     brouard  10748:                
                   10749:                
1.186     brouard  10750:     /* Other results (useful)*/
1.220     brouard  10751:                
                   10752:                
1.126     brouard  10753:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  10754:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   10755:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  10756:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  10757:     fclose(ficrespl);
                   10758: 
                   10759:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  10760:     /*#include "hpijx.h"*/
                   10761:     hPijx(p, bage, fage);
1.145     brouard  10762:     fclose(ficrespij);
1.227     brouard  10763:     
1.220     brouard  10764:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  10765:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  10766:     k=1;
1.126     brouard  10767:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  10768:     
1.219     brouard  10769:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  10770:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  10771:     for(i=1;i<=AGESUP;i++)
1.219     brouard  10772:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  10773:        for(k=1;k<=ncovcombmax;k++)
                   10774:          probs[i][j][k]=0.;
1.219     brouard  10775:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   10776:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   10777:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  10778:       for(i=1;i<=AGESUP;i++)
                   10779:        for(j=1;j<=nlstate;j++)
                   10780:          for(k=1;k<=ncovcombmax;k++)
                   10781:            mobaverages[i][j][k]=0.;
1.219     brouard  10782:       mobaverage=mobaverages;
                   10783:       if (mobilav!=0) {
1.235     brouard  10784:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  10785:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   10786:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   10787:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   10788:        }
1.219     brouard  10789:       }
                   10790:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   10791:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10792:       else if (mobilavproj !=0) {
1.235     brouard  10793:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  10794:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   10795:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10796:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10797:        }
1.219     brouard  10798:       }
                   10799:     }/* end if moving average */
1.227     brouard  10800:     
1.126     brouard  10801:     /*---------- Forecasting ------------------*/
                   10802:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   10803:     if(prevfcast==1){
                   10804:       /*    if(stepm ==1){*/
1.225     brouard  10805:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  10806:     }
1.217     brouard  10807:     if(backcast==1){
1.219     brouard  10808:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   10809:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   10810:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   10811: 
                   10812:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   10813: 
                   10814:       bprlim=matrix(1,nlstate,1,nlstate);
                   10815:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   10816:       fclose(ficresplb);
                   10817: 
1.222     brouard  10818:       hBijx(p, bage, fage, mobaverage);
                   10819:       fclose(ficrespijb);
1.219     brouard  10820:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10821: 
                   10822:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  10823:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  10824:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10825:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10826:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10827:     }
1.217     brouard  10828:     
1.186     brouard  10829:  
                   10830:     /* ------ Other prevalence ratios------------ */
1.126     brouard  10831: 
1.215     brouard  10832:     free_ivector(wav,1,imx);
                   10833:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   10834:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   10835:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  10836:                
                   10837:                
1.127     brouard  10838:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  10839:                
1.201     brouard  10840:     strcpy(filerese,"E_");
                   10841:     strcat(filerese,fileresu);
1.126     brouard  10842:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   10843:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   10844:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   10845:     }
1.208     brouard  10846:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   10847:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219     brouard  10848:                
1.235     brouard  10849:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   10850:     if (cptcovn < 1){i1=1;}
                   10851:     
                   10852:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10853:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   10854:       if(TKresult[nres]!= k)
                   10855:        continue;
1.219     brouard  10856:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  10857:       printf("\n#****** ");
1.225     brouard  10858:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  10859:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10860:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10861:       }
                   10862:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10863:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10864:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  10865:       }
                   10866:       fprintf(ficreseij,"******\n");
1.235     brouard  10867:       printf("******\n");
1.219     brouard  10868:       
                   10869:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10870:       oldm=oldms;savm=savms;
1.235     brouard  10871:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  10872:       
1.219     brouard  10873:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  10874:     }
                   10875:     fclose(ficreseij);
1.208     brouard  10876:     printf("done evsij\n");fflush(stdout);
                   10877:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  10878:                
1.227     brouard  10879:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  10880:                
                   10881:                
1.201     brouard  10882:     strcpy(filerest,"T_");
                   10883:     strcat(filerest,fileresu);
1.127     brouard  10884:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   10885:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   10886:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   10887:     }
1.208     brouard  10888:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   10889:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  10890:                
1.126     brouard  10891: 
1.201     brouard  10892:     strcpy(fileresstde,"STDE_");
                   10893:     strcat(fileresstde,fileresu);
1.126     brouard  10894:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  10895:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   10896:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  10897:     }
1.227     brouard  10898:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   10899:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  10900: 
1.201     brouard  10901:     strcpy(filerescve,"CVE_");
                   10902:     strcat(filerescve,fileresu);
1.126     brouard  10903:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  10904:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   10905:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  10906:     }
1.227     brouard  10907:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   10908:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  10909: 
1.201     brouard  10910:     strcpy(fileresv,"V_");
                   10911:     strcat(fileresv,fileresu);
1.126     brouard  10912:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   10913:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   10914:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   10915:     }
1.227     brouard  10916:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   10917:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  10918: 
1.145     brouard  10919:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10920:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10921:           
1.235     brouard  10922:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   10923:     if (cptcovn < 1){i1=1;}
                   10924:     
                   10925:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10926:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   10927:       if(TKresult[nres]!= k)
                   10928:        continue;
                   10929:       printf("\n#****** Selected:");
                   10930:       fprintf(ficrest,"\n#****** Selected:");
                   10931:       fprintf(ficlog,"\n#****** Selected:");
1.227     brouard  10932:       for(j=1;j<=cptcoveff;j++){ 
                   10933:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10934:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10935:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10936:       }
1.235     brouard  10937:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10938:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10939:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10940:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10941:       }        
1.208     brouard  10942:       fprintf(ficrest,"******\n");
1.227     brouard  10943:       fprintf(ficlog,"******\n");
                   10944:       printf("******\n");
1.208     brouard  10945:       
                   10946:       fprintf(ficresstdeij,"\n#****** ");
                   10947:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  10948:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  10949:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10950:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  10951:       }
1.235     brouard  10952:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10953:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10954:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10955:       }        
1.208     brouard  10956:       fprintf(ficresstdeij,"******\n");
                   10957:       fprintf(ficrescveij,"******\n");
                   10958:       
                   10959:       fprintf(ficresvij,"\n#****** ");
1.225     brouard  10960:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  10961:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10962:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10963:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10964:       }        
1.208     brouard  10965:       fprintf(ficresvij,"******\n");
                   10966:       
                   10967:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10968:       oldm=oldms;savm=savms;
1.235     brouard  10969:       printf(" cvevsij ");
                   10970:       fprintf(ficlog, " cvevsij ");
                   10971:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  10972:       printf(" end cvevsij \n ");
                   10973:       fprintf(ficlog, " end cvevsij \n ");
                   10974:       
                   10975:       /*
                   10976:        */
                   10977:       /* goto endfree; */
                   10978:       
                   10979:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10980:       pstamp(ficrest);
                   10981:       
                   10982:       
                   10983:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  10984:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   10985:        cptcod= 0; /* To be deleted */
                   10986:        printf("varevsij vpopbased=%d \n",vpopbased);
                   10987:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  10988:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
1.227     brouard  10989:        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 ");
                   10990:        if(vpopbased==1)
                   10991:          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);
                   10992:        else
                   10993:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   10994:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   10995:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   10996:        fprintf(ficrest,"\n");
                   10997:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   10998:        epj=vector(1,nlstate+1);
                   10999:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11000:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11001:        for(age=bage; age <=fage ;age++){
1.235     brouard  11002:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11003:          if (vpopbased==1) {
                   11004:            if(mobilav ==0){
                   11005:              for(i=1; i<=nlstate;i++)
                   11006:                prlim[i][i]=probs[(int)age][i][k];
                   11007:            }else{ /* mobilav */ 
                   11008:              for(i=1; i<=nlstate;i++)
                   11009:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11010:            }
                   11011:          }
1.219     brouard  11012:          
1.227     brouard  11013:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11014:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11015:          /* printf(" age %4.0f ",age); */
                   11016:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11017:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11018:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11019:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11020:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11021:            }
                   11022:            epj[nlstate+1] +=epj[j];
                   11023:          }
                   11024:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11025:          
1.227     brouard  11026:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11027:            for(j=1;j <=nlstate;j++)
                   11028:              vepp += vareij[i][j][(int)age];
                   11029:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11030:          for(j=1;j <=nlstate;j++){
                   11031:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11032:          }
                   11033:          fprintf(ficrest,"\n");
                   11034:        }
1.208     brouard  11035:       } /* End vpopbased */
                   11036:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11037:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11038:       free_vector(epj,1,nlstate+1);
1.235     brouard  11039:       printf("done selection\n");fflush(stdout);
                   11040:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11041:       
1.145     brouard  11042:       /*}*/
1.235     brouard  11043:     } /* End k selection */
1.227     brouard  11044: 
                   11045:     printf("done State-specific expectancies\n");fflush(stdout);
                   11046:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11047: 
1.126     brouard  11048:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11049:     
1.201     brouard  11050:     strcpy(fileresvpl,"VPL_");
                   11051:     strcat(fileresvpl,fileresu);
1.126     brouard  11052:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11053:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11054:       exit(0);
                   11055:     }
1.208     brouard  11056:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11057:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11058:     
1.145     brouard  11059:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11060:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11061:     
1.235     brouard  11062:     i1=pow(2,cptcoveff);
                   11063:     if (cptcovn < 1){i1=1;}
                   11064: 
                   11065:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11066:     for(k=1; k<=i1;k++){
                   11067:       if(TKresult[nres]!= k)
                   11068:        continue;
1.227     brouard  11069:       fprintf(ficresvpl,"\n#****** ");
                   11070:       printf("\n#****** ");
                   11071:       fprintf(ficlog,"\n#****** ");
                   11072:       for(j=1;j<=cptcoveff;j++) {
                   11073:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11074:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11075:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11076:       }
1.235     brouard  11077:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11078:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11079:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11080:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11081:       }        
1.227     brouard  11082:       fprintf(ficresvpl,"******\n");
                   11083:       printf("******\n");
                   11084:       fprintf(ficlog,"******\n");
                   11085:       
                   11086:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11087:       oldm=oldms;savm=savms;
1.235     brouard  11088:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11089:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11090:       /*}*/
1.126     brouard  11091:     }
1.227     brouard  11092:     
1.126     brouard  11093:     fclose(ficresvpl);
1.208     brouard  11094:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11095:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11096:     
                   11097:     free_vector(weight,1,n);
                   11098:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11099:     free_imatrix(s,1,maxwav+1,1,n);
                   11100:     free_matrix(anint,1,maxwav,1,n); 
                   11101:     free_matrix(mint,1,maxwav,1,n);
                   11102:     free_ivector(cod,1,n);
                   11103:     free_ivector(tab,1,NCOVMAX);
                   11104:     fclose(ficresstdeij);
                   11105:     fclose(ficrescveij);
                   11106:     fclose(ficresvij);
                   11107:     fclose(ficrest);
                   11108:     fclose(ficpar);
                   11109:     
                   11110:     
1.126     brouard  11111:     /*---------- End : free ----------------*/
1.219     brouard  11112:     if (mobilav!=0 ||mobilavproj !=0)
                   11113:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
1.218     brouard  11114:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11115:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11116:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11117:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11118:   /* endfree:*/
                   11119:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11120:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11121:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11122:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11123:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11124:   free_matrix(coqvar,1,maxwav,1,n);
                   11125:   free_matrix(covar,0,NCOVMAX,1,n);
                   11126:   free_matrix(matcov,1,npar,1,npar);
                   11127:   free_matrix(hess,1,npar,1,npar);
                   11128:   /*free_vector(delti,1,npar);*/
                   11129:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11130:   free_matrix(agev,1,maxwav,1,imx);
                   11131:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11132:   
                   11133:   free_ivector(ncodemax,1,NCOVMAX);
                   11134:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11135:   free_ivector(Dummy,-1,NCOVMAX);
                   11136:   free_ivector(Fixed,-1,NCOVMAX);
                   11137:   free_ivector(Typevar,-1,NCOVMAX);
                   11138:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11139:   free_ivector(TvarsQ,1,NCOVMAX);
                   11140:   free_ivector(TvarsQind,1,NCOVMAX);
                   11141:   free_ivector(TvarsD,1,NCOVMAX);
                   11142:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11143:   free_ivector(TvarFD,1,NCOVMAX);
                   11144:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11145:   free_ivector(TvarF,1,NCOVMAX);
                   11146:   free_ivector(TvarFind,1,NCOVMAX);
                   11147:   free_ivector(TvarV,1,NCOVMAX);
                   11148:   free_ivector(TvarVind,1,NCOVMAX);
                   11149:   free_ivector(TvarA,1,NCOVMAX);
                   11150:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11151:   free_ivector(TvarFQ,1,NCOVMAX);
                   11152:   free_ivector(TvarFQind,1,NCOVMAX);
                   11153:   free_ivector(TvarVD,1,NCOVMAX);
                   11154:   free_ivector(TvarVDind,1,NCOVMAX);
                   11155:   free_ivector(TvarVQ,1,NCOVMAX);
                   11156:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11157:   free_ivector(Tvarsel,1,NCOVMAX);
                   11158:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11159:   free_ivector(Tposprod,1,NCOVMAX);
                   11160:   free_ivector(Tprod,1,NCOVMAX);
                   11161:   free_ivector(Tvaraff,1,NCOVMAX);
                   11162:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11163:   free_ivector(Tage,1,NCOVMAX);
                   11164:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11165:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11166:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11167:   
                   11168:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11169:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11170:   fflush(fichtm);
                   11171:   fflush(ficgp);
                   11172:   
1.227     brouard  11173:   
1.126     brouard  11174:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11175:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11176:     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  11177:   }else{
                   11178:     printf("End of Imach\n");
                   11179:     fprintf(ficlog,"End of Imach\n");
                   11180:   }
                   11181:   printf("See log file on %s\n",filelog);
                   11182:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11183:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11184:   rend_time = time(NULL);  
                   11185:   end_time = *localtime(&rend_time);
                   11186:   /* tml = *localtime(&end_time.tm_sec); */
                   11187:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11188:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11189:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11190:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11191:   
1.157     brouard  11192:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11193:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11194:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11195:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11196: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11197:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11198:   fclose(fichtm);
                   11199:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11200:   fclose(fichtmcov);
                   11201:   fclose(ficgp);
                   11202:   fclose(ficlog);
                   11203:   /*------ End -----------*/
1.227     brouard  11204:   
                   11205:   
                   11206:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11207: #ifdef WIN32
1.227     brouard  11208:   if (_chdir(pathcd) != 0)
                   11209:     printf("Can't move to directory %s!\n",path);
                   11210:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11211: #else
1.227     brouard  11212:     if(chdir(pathcd) != 0)
                   11213:       printf("Can't move to directory %s!\n", path);
                   11214:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11215: #endif 
1.126     brouard  11216:     printf("Current directory %s!\n",pathcd);
                   11217:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11218:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11219: #ifdef _WIN32
1.126     brouard  11220:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11221: #endif
                   11222:   if(!stat(plotcmd,&info)){
1.158     brouard  11223:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11224:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11225:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11226:     }else
                   11227:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11228: #ifdef __unix
1.126     brouard  11229:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11230:     if(!stat(plotcmd,&info)){
1.158     brouard  11231:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11232:     }else
                   11233:       strcpy(pplotcmd,plotcmd);
                   11234: #endif
                   11235:   }else
                   11236:     strcpy(pplotcmd,plotcmd);
                   11237:   
                   11238:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11239:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11240:   
1.126     brouard  11241:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11242:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11243:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11244:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11245:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11246:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11247:   }
1.158     brouard  11248:   printf(" Successful, please wait...");
1.126     brouard  11249:   while (z[0] != 'q') {
                   11250:     /* chdir(path); */
1.154     brouard  11251:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11252:     scanf("%s",z);
                   11253: /*     if (z[0] == 'c') system("./imach"); */
                   11254:     if (z[0] == 'e') {
1.158     brouard  11255: #ifdef __APPLE__
1.152     brouard  11256:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11257: #elif __linux
                   11258:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11259: #else
1.152     brouard  11260:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11261: #endif
                   11262:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11263:       system(pplotcmd);
1.126     brouard  11264:     }
                   11265:     else if (z[0] == 'g') system(plotcmd);
                   11266:     else if (z[0] == 'q') exit(0);
                   11267:   }
1.227     brouard  11268: end:
1.126     brouard  11269:   while (z[0] != 'q') {
1.195     brouard  11270:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11271:     scanf("%s",z);
                   11272:   }
                   11273: }

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