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

1.250   ! brouard     1: /* $Id: imach.c,v 1.249 2016/09/07 17:14:18 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.250   ! brouard     4:   Revision 1.249  2016/09/07 17:14:18  brouard
        !             5:   Summary: Starting values from frequencies
        !             6: 
1.249     brouard     7:   Revision 1.248  2016/09/07 14:10:18  brouard
                      8:   *** empty log message ***
                      9: 
1.248     brouard    10:   Revision 1.247  2016/09/02 11:11:21  brouard
                     11:   *** empty log message ***
                     12: 
1.247     brouard    13:   Revision 1.246  2016/09/02 08:49:22  brouard
                     14:   *** empty log message ***
                     15: 
1.246     brouard    16:   Revision 1.245  2016/09/02 07:25:01  brouard
                     17:   *** empty log message ***
                     18: 
1.245     brouard    19:   Revision 1.244  2016/09/02 07:17:34  brouard
                     20:   *** empty log message ***
                     21: 
1.244     brouard    22:   Revision 1.243  2016/09/02 06:45:35  brouard
                     23:   *** empty log message ***
                     24: 
1.243     brouard    25:   Revision 1.242  2016/08/30 15:01:20  brouard
                     26:   Summary: Fixing a lots
                     27: 
1.242     brouard    28:   Revision 1.241  2016/08/29 17:17:25  brouard
                     29:   Summary: gnuplot problem in Back projection to fix
                     30: 
1.241     brouard    31:   Revision 1.240  2016/08/29 07:53:18  brouard
                     32:   Summary: Better
                     33: 
1.240     brouard    34:   Revision 1.239  2016/08/26 15:51:03  brouard
                     35:   Summary: Improvement in Powell output in order to copy and paste
                     36: 
                     37:   Author:
                     38: 
1.239     brouard    39:   Revision 1.238  2016/08/26 14:23:35  brouard
                     40:   Summary: Starting tests of 0.99
                     41: 
1.238     brouard    42:   Revision 1.237  2016/08/26 09:20:19  brouard
                     43:   Summary: to valgrind
                     44: 
1.237     brouard    45:   Revision 1.236  2016/08/25 10:50:18  brouard
                     46:   *** empty log message ***
                     47: 
1.236     brouard    48:   Revision 1.235  2016/08/25 06:59:23  brouard
                     49:   *** empty log message ***
                     50: 
1.235     brouard    51:   Revision 1.234  2016/08/23 16:51:20  brouard
                     52:   *** empty log message ***
                     53: 
1.234     brouard    54:   Revision 1.233  2016/08/23 07:40:50  brouard
                     55:   Summary: not working
                     56: 
1.233     brouard    57:   Revision 1.232  2016/08/22 14:20:21  brouard
                     58:   Summary: not working
                     59: 
1.232     brouard    60:   Revision 1.231  2016/08/22 07:17:15  brouard
                     61:   Summary: not working
                     62: 
1.231     brouard    63:   Revision 1.230  2016/08/22 06:55:53  brouard
                     64:   Summary: Not working
                     65: 
1.230     brouard    66:   Revision 1.229  2016/07/23 09:45:53  brouard
                     67:   Summary: Completing for func too
                     68: 
1.229     brouard    69:   Revision 1.228  2016/07/22 17:45:30  brouard
                     70:   Summary: Fixing some arrays, still debugging
                     71: 
1.227     brouard    72:   Revision 1.226  2016/07/12 18:42:34  brouard
                     73:   Summary: temp
                     74: 
1.226     brouard    75:   Revision 1.225  2016/07/12 08:40:03  brouard
                     76:   Summary: saving but not running
                     77: 
1.225     brouard    78:   Revision 1.224  2016/07/01 13:16:01  brouard
                     79:   Summary: Fixes
                     80: 
1.224     brouard    81:   Revision 1.223  2016/02/19 09:23:35  brouard
                     82:   Summary: temporary
                     83: 
1.223     brouard    84:   Revision 1.222  2016/02/17 08:14:50  brouard
                     85:   Summary: Probably last 0.98 stable version 0.98r6
                     86: 
1.222     brouard    87:   Revision 1.221  2016/02/15 23:35:36  brouard
                     88:   Summary: minor bug
                     89: 
1.220     brouard    90:   Revision 1.219  2016/02/15 00:48:12  brouard
                     91:   *** empty log message ***
                     92: 
1.219     brouard    93:   Revision 1.218  2016/02/12 11:29:23  brouard
                     94:   Summary: 0.99 Back projections
                     95: 
1.218     brouard    96:   Revision 1.217  2015/12/23 17:18:31  brouard
                     97:   Summary: Experimental backcast
                     98: 
1.217     brouard    99:   Revision 1.216  2015/12/18 17:32:11  brouard
                    100:   Summary: 0.98r4 Warning and status=-2
                    101: 
                    102:   Version 0.98r4 is now:
                    103:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    104:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    105:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    106: 
1.216     brouard   107:   Revision 1.215  2015/12/16 08:52:24  brouard
                    108:   Summary: 0.98r4 working
                    109: 
1.215     brouard   110:   Revision 1.214  2015/12/16 06:57:54  brouard
                    111:   Summary: temporary not working
                    112: 
1.214     brouard   113:   Revision 1.213  2015/12/11 18:22:17  brouard
                    114:   Summary: 0.98r4
                    115: 
1.213     brouard   116:   Revision 1.212  2015/11/21 12:47:24  brouard
                    117:   Summary: minor typo
                    118: 
1.212     brouard   119:   Revision 1.211  2015/11/21 12:41:11  brouard
                    120:   Summary: 0.98r3 with some graph of projected cross-sectional
                    121: 
                    122:   Author: Nicolas Brouard
                    123: 
1.211     brouard   124:   Revision 1.210  2015/11/18 17:41:20  brouard
                    125:   Summary: Start working on projected prevalences
                    126: 
1.210     brouard   127:   Revision 1.209  2015/11/17 22:12:03  brouard
                    128:   Summary: Adding ftolpl parameter
                    129:   Author: N Brouard
                    130: 
                    131:   We had difficulties to get smoothed confidence intervals. It was due
                    132:   to the period prevalence which wasn't computed accurately. The inner
                    133:   parameter ftolpl is now an outer parameter of the .imach parameter
                    134:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    135:   computation are long.
                    136: 
1.209     brouard   137:   Revision 1.208  2015/11/17 14:31:57  brouard
                    138:   Summary: temporary
                    139: 
1.208     brouard   140:   Revision 1.207  2015/10/27 17:36:57  brouard
                    141:   *** empty log message ***
                    142: 
1.207     brouard   143:   Revision 1.206  2015/10/24 07:14:11  brouard
                    144:   *** empty log message ***
                    145: 
1.206     brouard   146:   Revision 1.205  2015/10/23 15:50:53  brouard
                    147:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    148: 
1.205     brouard   149:   Revision 1.204  2015/10/01 16:20:26  brouard
                    150:   Summary: Some new graphs of contribution to likelihood
                    151: 
1.204     brouard   152:   Revision 1.203  2015/09/30 17:45:14  brouard
                    153:   Summary: looking at better estimation of the hessian
                    154: 
                    155:   Also a better criteria for convergence to the period prevalence And
                    156:   therefore adding the number of years needed to converge. (The
                    157:   prevalence in any alive state shold sum to one
                    158: 
1.203     brouard   159:   Revision 1.202  2015/09/22 19:45:16  brouard
                    160:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    161: 
1.202     brouard   162:   Revision 1.201  2015/09/15 17:34:58  brouard
                    163:   Summary: 0.98r0
                    164: 
                    165:   - Some new graphs like suvival functions
                    166:   - Some bugs fixed like model=1+age+V2.
                    167: 
1.201     brouard   168:   Revision 1.200  2015/09/09 16:53:55  brouard
                    169:   Summary: Big bug thanks to Flavia
                    170: 
                    171:   Even model=1+age+V2. did not work anymore
                    172: 
1.200     brouard   173:   Revision 1.199  2015/09/07 14:09:23  brouard
                    174:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    175: 
1.199     brouard   176:   Revision 1.198  2015/09/03 07:14:39  brouard
                    177:   Summary: 0.98q5 Flavia
                    178: 
1.198     brouard   179:   Revision 1.197  2015/09/01 18:24:39  brouard
                    180:   *** empty log message ***
                    181: 
1.197     brouard   182:   Revision 1.196  2015/08/18 23:17:52  brouard
                    183:   Summary: 0.98q5
                    184: 
1.196     brouard   185:   Revision 1.195  2015/08/18 16:28:39  brouard
                    186:   Summary: Adding a hack for testing purpose
                    187: 
                    188:   After reading the title, ftol and model lines, if the comment line has
                    189:   a q, starting with #q, the answer at the end of the run is quit. It
                    190:   permits to run test files in batch with ctest. The former workaround was
                    191:   $ echo q | imach foo.imach
                    192: 
1.195     brouard   193:   Revision 1.194  2015/08/18 13:32:00  brouard
                    194:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    195: 
1.194     brouard   196:   Revision 1.193  2015/08/04 07:17:42  brouard
                    197:   Summary: 0.98q4
                    198: 
1.193     brouard   199:   Revision 1.192  2015/07/16 16:49:02  brouard
                    200:   Summary: Fixing some outputs
                    201: 
1.192     brouard   202:   Revision 1.191  2015/07/14 10:00:33  brouard
                    203:   Summary: Some fixes
                    204: 
1.191     brouard   205:   Revision 1.190  2015/05/05 08:51:13  brouard
                    206:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    207: 
                    208:   Fix 1+age+.
                    209: 
1.190     brouard   210:   Revision 1.189  2015/04/30 14:45:16  brouard
                    211:   Summary: 0.98q2
                    212: 
1.189     brouard   213:   Revision 1.188  2015/04/30 08:27:53  brouard
                    214:   *** empty log message ***
                    215: 
1.188     brouard   216:   Revision 1.187  2015/04/29 09:11:15  brouard
                    217:   *** empty log message ***
                    218: 
1.187     brouard   219:   Revision 1.186  2015/04/23 12:01:52  brouard
                    220:   Summary: V1*age is working now, version 0.98q1
                    221: 
                    222:   Some codes had been disabled in order to simplify and Vn*age was
                    223:   working in the optimization phase, ie, giving correct MLE parameters,
                    224:   but, as usual, outputs were not correct and program core dumped.
                    225: 
1.186     brouard   226:   Revision 1.185  2015/03/11 13:26:42  brouard
                    227:   Summary: Inclusion of compile and links command line for Intel Compiler
                    228: 
1.185     brouard   229:   Revision 1.184  2015/03/11 11:52:39  brouard
                    230:   Summary: Back from Windows 8. Intel Compiler
                    231: 
1.184     brouard   232:   Revision 1.183  2015/03/10 20:34:32  brouard
                    233:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    234: 
                    235:   We use directest instead of original Powell test; probably no
                    236:   incidence on the results, but better justifications;
                    237:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    238:   wrong results.
                    239: 
1.183     brouard   240:   Revision 1.182  2015/02/12 08:19:57  brouard
                    241:   Summary: Trying to keep directest which seems simpler and more general
                    242:   Author: Nicolas Brouard
                    243: 
1.182     brouard   244:   Revision 1.181  2015/02/11 23:22:24  brouard
                    245:   Summary: Comments on Powell added
                    246: 
                    247:   Author:
                    248: 
1.181     brouard   249:   Revision 1.180  2015/02/11 17:33:45  brouard
                    250:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    251: 
1.180     brouard   252:   Revision 1.179  2015/01/04 09:57:06  brouard
                    253:   Summary: back to OS/X
                    254: 
1.179     brouard   255:   Revision 1.178  2015/01/04 09:35:48  brouard
                    256:   *** empty log message ***
                    257: 
1.178     brouard   258:   Revision 1.177  2015/01/03 18:40:56  brouard
                    259:   Summary: Still testing ilc32 on OSX
                    260: 
1.177     brouard   261:   Revision 1.176  2015/01/03 16:45:04  brouard
                    262:   *** empty log message ***
                    263: 
1.176     brouard   264:   Revision 1.175  2015/01/03 16:33:42  brouard
                    265:   *** empty log message ***
                    266: 
1.175     brouard   267:   Revision 1.174  2015/01/03 16:15:49  brouard
                    268:   Summary: Still in cross-compilation
                    269: 
1.174     brouard   270:   Revision 1.173  2015/01/03 12:06:26  brouard
                    271:   Summary: trying to detect cross-compilation
                    272: 
1.173     brouard   273:   Revision 1.172  2014/12/27 12:07:47  brouard
                    274:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    275: 
1.172     brouard   276:   Revision 1.171  2014/12/23 13:26:59  brouard
                    277:   Summary: Back from Visual C
                    278: 
                    279:   Still problem with utsname.h on Windows
                    280: 
1.171     brouard   281:   Revision 1.170  2014/12/23 11:17:12  brouard
                    282:   Summary: Cleaning some \%% back to %%
                    283: 
                    284:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    285: 
1.170     brouard   286:   Revision 1.169  2014/12/22 23:08:31  brouard
                    287:   Summary: 0.98p
                    288: 
                    289:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    290: 
1.169     brouard   291:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   292:   Summary: update
1.169     brouard   293: 
1.168     brouard   294:   Revision 1.167  2014/12/22 13:50:56  brouard
                    295:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    296: 
                    297:   Testing on Linux 64
                    298: 
1.167     brouard   299:   Revision 1.166  2014/12/22 11:40:47  brouard
                    300:   *** empty log message ***
                    301: 
1.166     brouard   302:   Revision 1.165  2014/12/16 11:20:36  brouard
                    303:   Summary: After compiling on Visual C
                    304: 
                    305:   * imach.c (Module): Merging 1.61 to 1.162
                    306: 
1.165     brouard   307:   Revision 1.164  2014/12/16 10:52:11  brouard
                    308:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    309: 
                    310:   * imach.c (Module): Merging 1.61 to 1.162
                    311: 
1.164     brouard   312:   Revision 1.163  2014/12/16 10:30:11  brouard
                    313:   * imach.c (Module): Merging 1.61 to 1.162
                    314: 
1.163     brouard   315:   Revision 1.162  2014/09/25 11:43:39  brouard
                    316:   Summary: temporary backup 0.99!
                    317: 
1.162     brouard   318:   Revision 1.1  2014/09/16 11:06:58  brouard
                    319:   Summary: With some code (wrong) for nlopt
                    320: 
                    321:   Author:
                    322: 
                    323:   Revision 1.161  2014/09/15 20:41:41  brouard
                    324:   Summary: Problem with macro SQR on Intel compiler
                    325: 
1.161     brouard   326:   Revision 1.160  2014/09/02 09:24:05  brouard
                    327:   *** empty log message ***
                    328: 
1.160     brouard   329:   Revision 1.159  2014/09/01 10:34:10  brouard
                    330:   Summary: WIN32
                    331:   Author: Brouard
                    332: 
1.159     brouard   333:   Revision 1.158  2014/08/27 17:11:51  brouard
                    334:   *** empty log message ***
                    335: 
1.158     brouard   336:   Revision 1.157  2014/08/27 16:26:55  brouard
                    337:   Summary: Preparing windows Visual studio version
                    338:   Author: Brouard
                    339: 
                    340:   In order to compile on Visual studio, time.h is now correct and time_t
                    341:   and tm struct should be used. difftime should be used but sometimes I
                    342:   just make the differences in raw time format (time(&now).
                    343:   Trying to suppress #ifdef LINUX
                    344:   Add xdg-open for __linux in order to open default browser.
                    345: 
1.157     brouard   346:   Revision 1.156  2014/08/25 20:10:10  brouard
                    347:   *** empty log message ***
                    348: 
1.156     brouard   349:   Revision 1.155  2014/08/25 18:32:34  brouard
                    350:   Summary: New compile, minor changes
                    351:   Author: Brouard
                    352: 
1.155     brouard   353:   Revision 1.154  2014/06/20 17:32:08  brouard
                    354:   Summary: Outputs now all graphs of convergence to period prevalence
                    355: 
1.154     brouard   356:   Revision 1.153  2014/06/20 16:45:46  brouard
                    357:   Summary: If 3 live state, convergence to period prevalence on same graph
                    358:   Author: Brouard
                    359: 
1.153     brouard   360:   Revision 1.152  2014/06/18 17:54:09  brouard
                    361:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    362: 
1.152     brouard   363:   Revision 1.151  2014/06/18 16:43:30  brouard
                    364:   *** empty log message ***
                    365: 
1.151     brouard   366:   Revision 1.150  2014/06/18 16:42:35  brouard
                    367:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    368:   Author: brouard
                    369: 
1.150     brouard   370:   Revision 1.149  2014/06/18 15:51:14  brouard
                    371:   Summary: Some fixes in parameter files errors
                    372:   Author: Nicolas Brouard
                    373: 
1.149     brouard   374:   Revision 1.148  2014/06/17 17:38:48  brouard
                    375:   Summary: Nothing new
                    376:   Author: Brouard
                    377: 
                    378:   Just a new packaging for OS/X version 0.98nS
                    379: 
1.148     brouard   380:   Revision 1.147  2014/06/16 10:33:11  brouard
                    381:   *** empty log message ***
                    382: 
1.147     brouard   383:   Revision 1.146  2014/06/16 10:20:28  brouard
                    384:   Summary: Merge
                    385:   Author: Brouard
                    386: 
                    387:   Merge, before building revised version.
                    388: 
1.146     brouard   389:   Revision 1.145  2014/06/10 21:23:15  brouard
                    390:   Summary: Debugging with valgrind
                    391:   Author: Nicolas Brouard
                    392: 
                    393:   Lot of changes in order to output the results with some covariates
                    394:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    395:   improve the code.
                    396:   No more memory valgrind error but a lot has to be done in order to
                    397:   continue the work of splitting the code into subroutines.
                    398:   Also, decodemodel has been improved. Tricode is still not
                    399:   optimal. nbcode should be improved. Documentation has been added in
                    400:   the source code.
                    401: 
1.144     brouard   402:   Revision 1.143  2014/01/26 09:45:38  brouard
                    403:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    404: 
                    405:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    406:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    407: 
1.143     brouard   408:   Revision 1.142  2014/01/26 03:57:36  brouard
                    409:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    410: 
                    411:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    412: 
1.142     brouard   413:   Revision 1.141  2014/01/26 02:42:01  brouard
                    414:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    415: 
1.141     brouard   416:   Revision 1.140  2011/09/02 10:37:54  brouard
                    417:   Summary: times.h is ok with mingw32 now.
                    418: 
1.140     brouard   419:   Revision 1.139  2010/06/14 07:50:17  brouard
                    420:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    421:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    422: 
1.139     brouard   423:   Revision 1.138  2010/04/30 18:19:40  brouard
                    424:   *** empty log message ***
                    425: 
1.138     brouard   426:   Revision 1.137  2010/04/29 18:11:38  brouard
                    427:   (Module): Checking covariates for more complex models
                    428:   than V1+V2. A lot of change to be done. Unstable.
                    429: 
1.137     brouard   430:   Revision 1.136  2010/04/26 20:30:53  brouard
                    431:   (Module): merging some libgsl code. Fixing computation
                    432:   of likelione (using inter/intrapolation if mle = 0) in order to
                    433:   get same likelihood as if mle=1.
                    434:   Some cleaning of code and comments added.
                    435: 
1.136     brouard   436:   Revision 1.135  2009/10/29 15:33:14  brouard
                    437:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    438: 
1.135     brouard   439:   Revision 1.134  2009/10/29 13:18:53  brouard
                    440:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    441: 
1.134     brouard   442:   Revision 1.133  2009/07/06 10:21:25  brouard
                    443:   just nforces
                    444: 
1.133     brouard   445:   Revision 1.132  2009/07/06 08:22:05  brouard
                    446:   Many tings
                    447: 
1.132     brouard   448:   Revision 1.131  2009/06/20 16:22:47  brouard
                    449:   Some dimensions resccaled
                    450: 
1.131     brouard   451:   Revision 1.130  2009/05/26 06:44:34  brouard
                    452:   (Module): Max Covariate is now set to 20 instead of 8. A
                    453:   lot of cleaning with variables initialized to 0. Trying to make
                    454:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    455: 
1.130     brouard   456:   Revision 1.129  2007/08/31 13:49:27  lievre
                    457:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    458: 
1.129     lievre    459:   Revision 1.128  2006/06/30 13:02:05  brouard
                    460:   (Module): Clarifications on computing e.j
                    461: 
1.128     brouard   462:   Revision 1.127  2006/04/28 18:11:50  brouard
                    463:   (Module): Yes the sum of survivors was wrong since
                    464:   imach-114 because nhstepm was no more computed in the age
                    465:   loop. Now we define nhstepma in the age loop.
                    466:   (Module): In order to speed up (in case of numerous covariates) we
                    467:   compute health expectancies (without variances) in a first step
                    468:   and then all the health expectancies with variances or standard
                    469:   deviation (needs data from the Hessian matrices) which slows the
                    470:   computation.
                    471:   In the future we should be able to stop the program is only health
                    472:   expectancies and graph are needed without standard deviations.
                    473: 
1.127     brouard   474:   Revision 1.126  2006/04/28 17:23:28  brouard
                    475:   (Module): Yes the sum of survivors was wrong since
                    476:   imach-114 because nhstepm was no more computed in the age
                    477:   loop. Now we define nhstepma in the age loop.
                    478:   Version 0.98h
                    479: 
1.126     brouard   480:   Revision 1.125  2006/04/04 15:20:31  lievre
                    481:   Errors in calculation of health expectancies. Age was not initialized.
                    482:   Forecasting file added.
                    483: 
                    484:   Revision 1.124  2006/03/22 17:13:53  lievre
                    485:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    486:   The log-likelihood is printed in the log file
                    487: 
                    488:   Revision 1.123  2006/03/20 10:52:43  brouard
                    489:   * imach.c (Module): <title> changed, corresponds to .htm file
                    490:   name. <head> headers where missing.
                    491: 
                    492:   * imach.c (Module): Weights can have a decimal point as for
                    493:   English (a comma might work with a correct LC_NUMERIC environment,
                    494:   otherwise the weight is truncated).
                    495:   Modification of warning when the covariates values are not 0 or
                    496:   1.
                    497:   Version 0.98g
                    498: 
                    499:   Revision 1.122  2006/03/20 09:45:41  brouard
                    500:   (Module): Weights can have a decimal point as for
                    501:   English (a comma might work with a correct LC_NUMERIC environment,
                    502:   otherwise the weight is truncated).
                    503:   Modification of warning when the covariates values are not 0 or
                    504:   1.
                    505:   Version 0.98g
                    506: 
                    507:   Revision 1.121  2006/03/16 17:45:01  lievre
                    508:   * imach.c (Module): Comments concerning covariates added
                    509: 
                    510:   * imach.c (Module): refinements in the computation of lli if
                    511:   status=-2 in order to have more reliable computation if stepm is
                    512:   not 1 month. Version 0.98f
                    513: 
                    514:   Revision 1.120  2006/03/16 15:10:38  lievre
                    515:   (Module): refinements in the computation of lli if
                    516:   status=-2 in order to have more reliable computation if stepm is
                    517:   not 1 month. Version 0.98f
                    518: 
                    519:   Revision 1.119  2006/03/15 17:42:26  brouard
                    520:   (Module): Bug if status = -2, the loglikelihood was
                    521:   computed as likelihood omitting the logarithm. Version O.98e
                    522: 
                    523:   Revision 1.118  2006/03/14 18:20:07  brouard
                    524:   (Module): varevsij Comments added explaining the second
                    525:   table of variances if popbased=1 .
                    526:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    527:   (Module): Function pstamp added
                    528:   (Module): Version 0.98d
                    529: 
                    530:   Revision 1.117  2006/03/14 17:16:22  brouard
                    531:   (Module): varevsij Comments added explaining the second
                    532:   table of variances if popbased=1 .
                    533:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    534:   (Module): Function pstamp added
                    535:   (Module): Version 0.98d
                    536: 
                    537:   Revision 1.116  2006/03/06 10:29:27  brouard
                    538:   (Module): Variance-covariance wrong links and
                    539:   varian-covariance of ej. is needed (Saito).
                    540: 
                    541:   Revision 1.115  2006/02/27 12:17:45  brouard
                    542:   (Module): One freematrix added in mlikeli! 0.98c
                    543: 
                    544:   Revision 1.114  2006/02/26 12:57:58  brouard
                    545:   (Module): Some improvements in processing parameter
                    546:   filename with strsep.
                    547: 
                    548:   Revision 1.113  2006/02/24 14:20:24  brouard
                    549:   (Module): Memory leaks checks with valgrind and:
                    550:   datafile was not closed, some imatrix were not freed and on matrix
                    551:   allocation too.
                    552: 
                    553:   Revision 1.112  2006/01/30 09:55:26  brouard
                    554:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    555: 
                    556:   Revision 1.111  2006/01/25 20:38:18  brouard
                    557:   (Module): Lots of cleaning and bugs added (Gompertz)
                    558:   (Module): Comments can be added in data file. Missing date values
                    559:   can be a simple dot '.'.
                    560: 
                    561:   Revision 1.110  2006/01/25 00:51:50  brouard
                    562:   (Module): Lots of cleaning and bugs added (Gompertz)
                    563: 
                    564:   Revision 1.109  2006/01/24 19:37:15  brouard
                    565:   (Module): Comments (lines starting with a #) are allowed in data.
                    566: 
                    567:   Revision 1.108  2006/01/19 18:05:42  lievre
                    568:   Gnuplot problem appeared...
                    569:   To be fixed
                    570: 
                    571:   Revision 1.107  2006/01/19 16:20:37  brouard
                    572:   Test existence of gnuplot in imach path
                    573: 
                    574:   Revision 1.106  2006/01/19 13:24:36  brouard
                    575:   Some cleaning and links added in html output
                    576: 
                    577:   Revision 1.105  2006/01/05 20:23:19  lievre
                    578:   *** empty log message ***
                    579: 
                    580:   Revision 1.104  2005/09/30 16:11:43  lievre
                    581:   (Module): sump fixed, loop imx fixed, and simplifications.
                    582:   (Module): If the status is missing at the last wave but we know
                    583:   that the person is alive, then we can code his/her status as -2
                    584:   (instead of missing=-1 in earlier versions) and his/her
                    585:   contributions to the likelihood is 1 - Prob of dying from last
                    586:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    587:   the healthy state at last known wave). Version is 0.98
                    588: 
                    589:   Revision 1.103  2005/09/30 15:54:49  lievre
                    590:   (Module): sump fixed, loop imx fixed, and simplifications.
                    591: 
                    592:   Revision 1.102  2004/09/15 17:31:30  brouard
                    593:   Add the possibility to read data file including tab characters.
                    594: 
                    595:   Revision 1.101  2004/09/15 10:38:38  brouard
                    596:   Fix on curr_time
                    597: 
                    598:   Revision 1.100  2004/07/12 18:29:06  brouard
                    599:   Add version for Mac OS X. Just define UNIX in Makefile
                    600: 
                    601:   Revision 1.99  2004/06/05 08:57:40  brouard
                    602:   *** empty log message ***
                    603: 
                    604:   Revision 1.98  2004/05/16 15:05:56  brouard
                    605:   New version 0.97 . First attempt to estimate force of mortality
                    606:   directly from the data i.e. without the need of knowing the health
                    607:   state at each age, but using a Gompertz model: log u =a + b*age .
                    608:   This is the basic analysis of mortality and should be done before any
                    609:   other analysis, in order to test if the mortality estimated from the
                    610:   cross-longitudinal survey is different from the mortality estimated
                    611:   from other sources like vital statistic data.
                    612: 
                    613:   The same imach parameter file can be used but the option for mle should be -3.
                    614: 
1.133     brouard   615:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   616:   former routines in order to include the new code within the former code.
                    617: 
                    618:   The output is very simple: only an estimate of the intercept and of
                    619:   the slope with 95% confident intervals.
                    620: 
                    621:   Current limitations:
                    622:   A) Even if you enter covariates, i.e. with the
                    623:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    624:   B) There is no computation of Life Expectancy nor Life Table.
                    625: 
                    626:   Revision 1.97  2004/02/20 13:25:42  lievre
                    627:   Version 0.96d. Population forecasting command line is (temporarily)
                    628:   suppressed.
                    629: 
                    630:   Revision 1.96  2003/07/15 15:38:55  brouard
                    631:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    632:   rewritten within the same printf. Workaround: many printfs.
                    633: 
                    634:   Revision 1.95  2003/07/08 07:54:34  brouard
                    635:   * imach.c (Repository):
                    636:   (Repository): Using imachwizard code to output a more meaningful covariance
                    637:   matrix (cov(a12,c31) instead of numbers.
                    638: 
                    639:   Revision 1.94  2003/06/27 13:00:02  brouard
                    640:   Just cleaning
                    641: 
                    642:   Revision 1.93  2003/06/25 16:33:55  brouard
                    643:   (Module): On windows (cygwin) function asctime_r doesn't
                    644:   exist so I changed back to asctime which exists.
                    645:   (Module): Version 0.96b
                    646: 
                    647:   Revision 1.92  2003/06/25 16:30:45  brouard
                    648:   (Module): On windows (cygwin) function asctime_r doesn't
                    649:   exist so I changed back to asctime which exists.
                    650: 
                    651:   Revision 1.91  2003/06/25 15:30:29  brouard
                    652:   * imach.c (Repository): Duplicated warning errors corrected.
                    653:   (Repository): Elapsed time after each iteration is now output. It
                    654:   helps to forecast when convergence will be reached. Elapsed time
                    655:   is stamped in powell.  We created a new html file for the graphs
                    656:   concerning matrix of covariance. It has extension -cov.htm.
                    657: 
                    658:   Revision 1.90  2003/06/24 12:34:15  brouard
                    659:   (Module): Some bugs corrected for windows. Also, when
                    660:   mle=-1 a template is output in file "or"mypar.txt with the design
                    661:   of the covariance matrix to be input.
                    662: 
                    663:   Revision 1.89  2003/06/24 12:30:52  brouard
                    664:   (Module): Some bugs corrected for windows. Also, when
                    665:   mle=-1 a template is output in file "or"mypar.txt with the design
                    666:   of the covariance matrix to be input.
                    667: 
                    668:   Revision 1.88  2003/06/23 17:54:56  brouard
                    669:   * 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.
                    670: 
                    671:   Revision 1.87  2003/06/18 12:26:01  brouard
                    672:   Version 0.96
                    673: 
                    674:   Revision 1.86  2003/06/17 20:04:08  brouard
                    675:   (Module): Change position of html and gnuplot routines and added
                    676:   routine fileappend.
                    677: 
                    678:   Revision 1.85  2003/06/17 13:12:43  brouard
                    679:   * imach.c (Repository): Check when date of death was earlier that
                    680:   current date of interview. It may happen when the death was just
                    681:   prior to the death. In this case, dh was negative and likelihood
                    682:   was wrong (infinity). We still send an "Error" but patch by
                    683:   assuming that the date of death was just one stepm after the
                    684:   interview.
                    685:   (Repository): Because some people have very long ID (first column)
                    686:   we changed int to long in num[] and we added a new lvector for
                    687:   memory allocation. But we also truncated to 8 characters (left
                    688:   truncation)
                    689:   (Repository): No more line truncation errors.
                    690: 
                    691:   Revision 1.84  2003/06/13 21:44:43  brouard
                    692:   * imach.c (Repository): Replace "freqsummary" at a correct
                    693:   place. It differs from routine "prevalence" which may be called
                    694:   many times. Probs is memory consuming and must be used with
                    695:   parcimony.
                    696:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    697: 
                    698:   Revision 1.83  2003/06/10 13:39:11  lievre
                    699:   *** empty log message ***
                    700: 
                    701:   Revision 1.82  2003/06/05 15:57:20  brouard
                    702:   Add log in  imach.c and  fullversion number is now printed.
                    703: 
                    704: */
                    705: /*
                    706:    Interpolated Markov Chain
                    707: 
                    708:   Short summary of the programme:
                    709:   
1.227     brouard   710:   This program computes Healthy Life Expectancies or State-specific
                    711:   (if states aren't health statuses) Expectancies from
                    712:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    713: 
                    714:   -1- a first survey ("cross") where individuals from different ages
                    715:   are interviewed on their health status or degree of disability (in
                    716:   the case of a health survey which is our main interest)
                    717: 
                    718:   -2- at least a second wave of interviews ("longitudinal") which
                    719:   measure each change (if any) in individual health status.  Health
                    720:   expectancies are computed from the time spent in each health state
                    721:   according to a model. More health states you consider, more time is
                    722:   necessary to reach the Maximum Likelihood of the parameters involved
                    723:   in the model.  The simplest model is the multinomial logistic model
                    724:   where pij is the probability to be observed in state j at the second
                    725:   wave conditional to be observed in state i at the first
                    726:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    727:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    728:   have a more complex model than "constant and age", you should modify
                    729:   the program where the markup *Covariates have to be included here
                    730:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   731:   convergence.
                    732: 
                    733:   The advantage of this computer programme, compared to a simple
                    734:   multinomial logistic model, is clear when the delay between waves is not
                    735:   identical for each individual. Also, if a individual missed an
                    736:   intermediate interview, the information is lost, but taken into
                    737:   account using an interpolation or extrapolation.  
                    738: 
                    739:   hPijx is the probability to be observed in state i at age x+h
                    740:   conditional to the observed state i at age x. The delay 'h' can be
                    741:   split into an exact number (nh*stepm) of unobserved intermediate
                    742:   states. This elementary transition (by month, quarter,
                    743:   semester or year) is modelled as a multinomial logistic.  The hPx
                    744:   matrix is simply the matrix product of nh*stepm elementary matrices
                    745:   and the contribution of each individual to the likelihood is simply
                    746:   hPijx.
                    747: 
                    748:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   749:   of the life expectancies. It also computes the period (stable) prevalence.
                    750: 
                    751: Back prevalence and projections:
1.227     brouard   752: 
                    753:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    754:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    755:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    756:    mobilavproj)
                    757: 
                    758:     Computes the back prevalence limit for any combination of
                    759:     covariate values k at any age between ageminpar and agemaxpar and
                    760:     returns it in **bprlim. In the loops,
                    761: 
                    762:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    763:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    764: 
                    765:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   766:    Computes for any combination of covariates k and any age between bage and fage 
                    767:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    768:                        oldm=oldms;savm=savms;
1.227     brouard   769: 
                    770:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   771:      Computes the transition matrix starting at age 'age' over
                    772:      'nhstepm*hstepm*stepm' months (i.e. until
                    773:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   774:      nhstepm*hstepm matrices. 
                    775: 
                    776:      Returns p3mat[i][j][h] after calling
                    777:      p3mat[i][j][h]=matprod2(newm,
                    778:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    779:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    780:      oldm);
1.226     brouard   781: 
                    782: Important routines
                    783: 
                    784: - func (or funcone), computes logit (pij) distinguishing
                    785:   o fixed variables (single or product dummies or quantitative);
                    786:   o varying variables by:
                    787:    (1) wave (single, product dummies, quantitative), 
                    788:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    789:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    790:        % varying dummy (not done) or quantitative (not done);
                    791: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    792:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    793: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    794:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    795:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   796: 
1.226     brouard   797: 
                    798:   
1.133     brouard   799:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    800:            Institut national d'études démographiques, Paris.
1.126     brouard   801:   This software have been partly granted by Euro-REVES, a concerted action
                    802:   from the European Union.
                    803:   It is copyrighted identically to a GNU software product, ie programme and
                    804:   software can be distributed freely for non commercial use. Latest version
                    805:   can be accessed at http://euroreves.ined.fr/imach .
                    806: 
                    807:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    808:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    809:   
                    810:   **********************************************************************/
                    811: /*
                    812:   main
                    813:   read parameterfile
                    814:   read datafile
                    815:   concatwav
                    816:   freqsummary
                    817:   if (mle >= 1)
                    818:     mlikeli
                    819:   print results files
                    820:   if mle==1 
                    821:      computes hessian
                    822:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    823:       begin-prev-date,...
                    824:   open gnuplot file
                    825:   open html file
1.145     brouard   826:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    827:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    828:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    829:     freexexit2 possible for memory heap.
                    830: 
                    831:   h Pij x                         | pij_nom  ficrestpij
                    832:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    833:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    834:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    835: 
                    836:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    837:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    838:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    839:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    840:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    841: 
1.126     brouard   842:   forecasting if prevfcast==1 prevforecast call prevalence()
                    843:   health expectancies
                    844:   Variance-covariance of DFLE
                    845:   prevalence()
                    846:    movingaverage()
                    847:   varevsij() 
                    848:   if popbased==1 varevsij(,popbased)
                    849:   total life expectancies
                    850:   Variance of period (stable) prevalence
                    851:  end
                    852: */
                    853: 
1.187     brouard   854: /* #define DEBUG */
                    855: /* #define DEBUGBRENT */
1.203     brouard   856: /* #define DEBUGLINMIN */
                    857: /* #define DEBUGHESS */
                    858: #define DEBUGHESSIJ
1.224     brouard   859: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   860: #define POWELL /* Instead of NLOPT */
1.224     brouard   861: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   862: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    863: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   864: 
                    865: #include <math.h>
                    866: #include <stdio.h>
                    867: #include <stdlib.h>
                    868: #include <string.h>
1.226     brouard   869: #include <ctype.h>
1.159     brouard   870: 
                    871: #ifdef _WIN32
                    872: #include <io.h>
1.172     brouard   873: #include <windows.h>
                    874: #include <tchar.h>
1.159     brouard   875: #else
1.126     brouard   876: #include <unistd.h>
1.159     brouard   877: #endif
1.126     brouard   878: 
                    879: #include <limits.h>
                    880: #include <sys/types.h>
1.171     brouard   881: 
                    882: #if defined(__GNUC__)
                    883: #include <sys/utsname.h> /* Doesn't work on Windows */
                    884: #endif
                    885: 
1.126     brouard   886: #include <sys/stat.h>
                    887: #include <errno.h>
1.159     brouard   888: /* extern int errno; */
1.126     brouard   889: 
1.157     brouard   890: /* #ifdef LINUX */
                    891: /* #include <time.h> */
                    892: /* #include "timeval.h" */
                    893: /* #else */
                    894: /* #include <sys/time.h> */
                    895: /* #endif */
                    896: 
1.126     brouard   897: #include <time.h>
                    898: 
1.136     brouard   899: #ifdef GSL
                    900: #include <gsl/gsl_errno.h>
                    901: #include <gsl/gsl_multimin.h>
                    902: #endif
                    903: 
1.167     brouard   904: 
1.162     brouard   905: #ifdef NLOPT
                    906: #include <nlopt.h>
                    907: typedef struct {
                    908:   double (* function)(double [] );
                    909: } myfunc_data ;
                    910: #endif
                    911: 
1.126     brouard   912: /* #include <libintl.h> */
                    913: /* #define _(String) gettext (String) */
                    914: 
1.141     brouard   915: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   916: 
                    917: #define GNUPLOTPROGRAM "gnuplot"
                    918: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    919: #define FILENAMELENGTH 132
                    920: 
                    921: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    922: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    923: 
1.144     brouard   924: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    925: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   926: 
                    927: #define NINTERVMAX 8
1.144     brouard   928: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    929: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    930: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   931: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   932: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    933: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   934: #define MAXN 20000
1.144     brouard   935: #define YEARM 12. /**< Number of months per year */
1.218     brouard   936: /* #define AGESUP 130 */
                    937: #define AGESUP 150
                    938: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   939: #define AGEBASE 40
1.194     brouard   940: #define AGEOVERFLOW 1.e20
1.164     brouard   941: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   942: #ifdef _WIN32
                    943: #define DIRSEPARATOR '\\'
                    944: #define CHARSEPARATOR "\\"
                    945: #define ODIRSEPARATOR '/'
                    946: #else
1.126     brouard   947: #define DIRSEPARATOR '/'
                    948: #define CHARSEPARATOR "/"
                    949: #define ODIRSEPARATOR '\\'
                    950: #endif
                    951: 
1.250   ! brouard   952: /* $Id: imach.c,v 1.249 2016/09/07 17:14:18 brouard Exp $ */
1.126     brouard   953: /* $State: Exp $ */
1.196     brouard   954: #include "version.h"
                    955: char version[]=__IMACH_VERSION__;
1.224     brouard   956: 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.250   ! brouard   957: char fullversion[]="$Revision: 1.249 $ $Date: 2016/09/07 17:14:18 $"; 
1.126     brouard   958: char strstart[80];
                    959: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   960: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   961: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   962: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    963: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    964: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   965: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    966: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   967: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    968: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    969: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   970: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    971: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   972: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   973: int nsd=0; /**< Total number of single dummy variables (output) */
                    974: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   975: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   976: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   977: int ntveff=0; /**< ntveff number of effective time varying variables */
                    978: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   979: int cptcov=0; /* Working variable */
1.218     brouard   980: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   981: int npar=NPARMAX;
                    982: int nlstate=2; /* Number of live states */
                    983: int ndeath=1; /* Number of dead states */
1.130     brouard   984: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   985: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   986: int popbased=0;
                    987: 
                    988: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   989: int maxwav=0; /* Maxim number of waves */
                    990: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    991: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    992: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   993:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   994: int mle=1, weightopt=0;
1.126     brouard   995: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    996: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    997: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    998:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   999: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1000: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1001: 
1.130     brouard  1002: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1003: double **matprod2(); /* test */
1.126     brouard  1004: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1005: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1006: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1007: 
1.136     brouard  1008: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1009: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1010: FILE *ficlog, *ficrespow;
1.130     brouard  1011: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1012: double fretone; /* Only one call to likelihood */
1.130     brouard  1013: long ipmx=0; /* Number of contributions */
1.126     brouard  1014: double sw; /* Sum of weights */
                   1015: char filerespow[FILENAMELENGTH];
                   1016: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1017: FILE *ficresilk;
                   1018: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1019: FILE *ficresprobmorprev;
                   1020: FILE *fichtm, *fichtmcov; /* Html File */
                   1021: FILE *ficreseij;
                   1022: char filerese[FILENAMELENGTH];
                   1023: FILE *ficresstdeij;
                   1024: char fileresstde[FILENAMELENGTH];
                   1025: FILE *ficrescveij;
                   1026: char filerescve[FILENAMELENGTH];
                   1027: FILE  *ficresvij;
                   1028: char fileresv[FILENAMELENGTH];
                   1029: FILE  *ficresvpl;
                   1030: char fileresvpl[FILENAMELENGTH];
                   1031: char title[MAXLINE];
1.234     brouard  1032: char model[MAXLINE]; /**< The model line */
1.217     brouard  1033: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1034: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1035: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1036: char command[FILENAMELENGTH];
                   1037: int  outcmd=0;
                   1038: 
1.217     brouard  1039: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1040: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1041: char filelog[FILENAMELENGTH]; /* Log file */
                   1042: char filerest[FILENAMELENGTH];
                   1043: char fileregp[FILENAMELENGTH];
                   1044: char popfile[FILENAMELENGTH];
                   1045: 
                   1046: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1047: 
1.157     brouard  1048: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1049: /* struct timezone tzp; */
                   1050: /* extern int gettimeofday(); */
                   1051: struct tm tml, *gmtime(), *localtime();
                   1052: 
                   1053: extern time_t time();
                   1054: 
                   1055: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1056: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1057: struct tm tm;
                   1058: 
1.126     brouard  1059: char strcurr[80], strfor[80];
                   1060: 
                   1061: char *endptr;
                   1062: long lval;
                   1063: double dval;
                   1064: 
                   1065: #define NR_END 1
                   1066: #define FREE_ARG char*
                   1067: #define FTOL 1.0e-10
                   1068: 
                   1069: #define NRANSI 
1.240     brouard  1070: #define ITMAX 200
                   1071: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1072: 
                   1073: #define TOL 2.0e-4 
                   1074: 
                   1075: #define CGOLD 0.3819660 
                   1076: #define ZEPS 1.0e-10 
                   1077: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1078: 
                   1079: #define GOLD 1.618034 
                   1080: #define GLIMIT 100.0 
                   1081: #define TINY 1.0e-20 
                   1082: 
                   1083: static double maxarg1,maxarg2;
                   1084: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1085: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1086:   
                   1087: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1088: #define rint(a) floor(a+0.5)
1.166     brouard  1089: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1090: #define mytinydouble 1.0e-16
1.166     brouard  1091: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1092: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1093: /* static double dsqrarg; */
                   1094: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1095: static double sqrarg;
                   1096: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1097: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1098: int agegomp= AGEGOMP;
                   1099: 
                   1100: int imx; 
                   1101: int stepm=1;
                   1102: /* Stepm, step in month: minimum step interpolation*/
                   1103: 
                   1104: int estepm;
                   1105: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1106: 
                   1107: int m,nb;
                   1108: long *num;
1.197     brouard  1109: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1110: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1111:                   covariate for which somebody answered excluding 
                   1112:                   undefined. Usually 2: 0 and 1. */
                   1113: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1114:                             covariate for which somebody answered including 
                   1115:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1116: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1117: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1118: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1119: double *ageexmed,*agecens;
                   1120: double dateintmean=0;
                   1121: 
                   1122: double *weight;
                   1123: int **s; /* Status */
1.141     brouard  1124: double *agedc;
1.145     brouard  1125: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1126:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1127:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1128: double **coqvar; /* Fixed quantitative covariate iqv */
                   1129: double ***cotvar; /* Time varying covariate itv */
                   1130: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1131: double  idx; 
                   1132: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1133: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1134: /*k          1  2   3   4     5    6    7     8    9 */
                   1135: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1136: /* Tndvar[k]    1   2   3               4          5 */
                   1137: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1138: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1139: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1140: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1141: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1142: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1143: /* Tprod[i]=k           4               7            */
                   1144: /* Tage[i]=k                  5               8      */
                   1145: /* */
                   1146: /* Type                    */
                   1147: /* V         1  2  3  4  5 */
                   1148: /*           F  F  V  V  V */
                   1149: /*           D  Q  D  D  Q */
                   1150: /*                         */
                   1151: int *TvarsD;
                   1152: int *TvarsDind;
                   1153: int *TvarsQ;
                   1154: int *TvarsQind;
                   1155: 
1.235     brouard  1156: #define MAXRESULTLINES 10
                   1157: int nresult=0;
                   1158: int TKresult[MAXRESULTLINES];
1.237     brouard  1159: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1160: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1161: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1162: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1163: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1164: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1165: 
1.234     brouard  1166: /* 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  1167: 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 */
                   1168: 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 */
                   1169: 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 */
                   1170: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1171: 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 */
                   1172: 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  1173: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1174: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1175: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1176: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1177: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1178: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1179: 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 */
                   1180: 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 */
                   1181: 
1.230     brouard  1182: int *Tvarsel; /**< Selected covariates for output */
                   1183: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1184: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1185: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1186: 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.238     brouard  1187: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1188: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1189: int *Tage;
1.227     brouard  1190: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1191: 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  1192: 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*/ 
                   1193: 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  1194: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1195: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1196: int **Tvard;
                   1197: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1198: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1199: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1200:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1201:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1202: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1203: double *lsurv, *lpop, *tpop;
                   1204: 
1.231     brouard  1205: #define FD 1; /* Fixed dummy covariate */
                   1206: #define FQ 2; /* Fixed quantitative covariate */
                   1207: #define FP 3; /* Fixed product covariate */
                   1208: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1209: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1210: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1211: #define VD 10; /* Varying dummy covariate */
                   1212: #define VQ 11; /* Varying quantitative covariate */
                   1213: #define VP 12; /* Varying product covariate */
                   1214: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1215: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1216: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1217: #define APFD 16; /* Age product * fixed dummy covariate */
                   1218: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1219: #define APVD 18; /* Age product * varying dummy covariate */
                   1220: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1221: 
                   1222: #define FTYPE 1; /* Fixed covariate */
                   1223: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1224: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1225: 
                   1226: struct kmodel{
                   1227:        int maintype; /* main type */
                   1228:        int subtype; /* subtype */
                   1229: };
                   1230: struct kmodel modell[NCOVMAX];
                   1231: 
1.143     brouard  1232: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1233: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1234: 
                   1235: /**************** split *************************/
                   1236: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1237: {
                   1238:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1239:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1240:   */ 
                   1241:   char *ss;                            /* pointer */
1.186     brouard  1242:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1243: 
                   1244:   l1 = strlen(path );                  /* length of path */
                   1245:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1246:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1247:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1248:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1249:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1250:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1251:     /* get current working directory */
                   1252:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1253: #ifdef WIN32
                   1254:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1255: #else
                   1256:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1257: #endif
1.126     brouard  1258:       return( GLOCK_ERROR_GETCWD );
                   1259:     }
                   1260:     /* got dirc from getcwd*/
                   1261:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1262:   } else {                             /* strip directory from path */
1.126     brouard  1263:     ss++;                              /* after this, the filename */
                   1264:     l2 = strlen( ss );                 /* length of filename */
                   1265:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1266:     strcpy( name, ss );                /* save file name */
                   1267:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1268:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1269:     printf(" DIRC2 = %s \n",dirc);
                   1270:   }
                   1271:   /* We add a separator at the end of dirc if not exists */
                   1272:   l1 = strlen( dirc );                 /* length of directory */
                   1273:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1274:     dirc[l1] =  DIRSEPARATOR;
                   1275:     dirc[l1+1] = 0; 
                   1276:     printf(" DIRC3 = %s \n",dirc);
                   1277:   }
                   1278:   ss = strrchr( name, '.' );           /* find last / */
                   1279:   if (ss >0){
                   1280:     ss++;
                   1281:     strcpy(ext,ss);                    /* save extension */
                   1282:     l1= strlen( name);
                   1283:     l2= strlen(ss)+1;
                   1284:     strncpy( finame, name, l1-l2);
                   1285:     finame[l1-l2]= 0;
                   1286:   }
                   1287: 
                   1288:   return( 0 );                         /* we're done */
                   1289: }
                   1290: 
                   1291: 
                   1292: /******************************************/
                   1293: 
                   1294: void replace_back_to_slash(char *s, char*t)
                   1295: {
                   1296:   int i;
                   1297:   int lg=0;
                   1298:   i=0;
                   1299:   lg=strlen(t);
                   1300:   for(i=0; i<= lg; i++) {
                   1301:     (s[i] = t[i]);
                   1302:     if (t[i]== '\\') s[i]='/';
                   1303:   }
                   1304: }
                   1305: 
1.132     brouard  1306: char *trimbb(char *out, char *in)
1.137     brouard  1307: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1308:   char *s;
                   1309:   s=out;
                   1310:   while (*in != '\0'){
1.137     brouard  1311:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1312:       in++;
                   1313:     }
                   1314:     *out++ = *in++;
                   1315:   }
                   1316:   *out='\0';
                   1317:   return s;
                   1318: }
                   1319: 
1.187     brouard  1320: /* char *substrchaine(char *out, char *in, char *chain) */
                   1321: /* { */
                   1322: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1323: /*   char *s, *t; */
                   1324: /*   t=in;s=out; */
                   1325: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1326: /*     *out++ = *in++; */
                   1327: /*   } */
                   1328: 
                   1329: /*   /\* *in matches *chain *\/ */
                   1330: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1331: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1332: /*   } */
                   1333: /*   in--; chain--; */
                   1334: /*   while ( (*in != '\0')){ */
                   1335: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1336: /*     *out++ = *in++; */
                   1337: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1338: /*   } */
                   1339: /*   *out='\0'; */
                   1340: /*   out=s; */
                   1341: /*   return out; */
                   1342: /* } */
                   1343: char *substrchaine(char *out, char *in, char *chain)
                   1344: {
                   1345:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1346:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1347: 
                   1348:   char *strloc;
                   1349: 
                   1350:   strcpy (out, in); 
                   1351:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1352:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1353:   if(strloc != NULL){ 
                   1354:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1355:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1356:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1357:   }
                   1358:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1359:   return out;
                   1360: }
                   1361: 
                   1362: 
1.145     brouard  1363: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1364: {
1.187     brouard  1365:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1366:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1367:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1368:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1369:   */
1.160     brouard  1370:   char *s, *t;
1.145     brouard  1371:   t=in;s=in;
                   1372:   while ((*in != occ) && (*in != '\0')){
                   1373:     *alocc++ = *in++;
                   1374:   }
                   1375:   if( *in == occ){
                   1376:     *(alocc)='\0';
                   1377:     s=++in;
                   1378:   }
                   1379:  
                   1380:   if (s == t) {/* occ not found */
                   1381:     *(alocc-(in-s))='\0';
                   1382:     in=s;
                   1383:   }
                   1384:   while ( *in != '\0'){
                   1385:     *blocc++ = *in++;
                   1386:   }
                   1387: 
                   1388:   *blocc='\0';
                   1389:   return t;
                   1390: }
1.137     brouard  1391: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1392: {
1.187     brouard  1393:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1394:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1395:      gives blocc="abcdef2ghi" and alocc="j".
                   1396:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1397:   */
                   1398:   char *s, *t;
                   1399:   t=in;s=in;
                   1400:   while (*in != '\0'){
                   1401:     while( *in == occ){
                   1402:       *blocc++ = *in++;
                   1403:       s=in;
                   1404:     }
                   1405:     *blocc++ = *in++;
                   1406:   }
                   1407:   if (s == t) /* occ not found */
                   1408:     *(blocc-(in-s))='\0';
                   1409:   else
                   1410:     *(blocc-(in-s)-1)='\0';
                   1411:   in=s;
                   1412:   while ( *in != '\0'){
                   1413:     *alocc++ = *in++;
                   1414:   }
                   1415: 
                   1416:   *alocc='\0';
                   1417:   return s;
                   1418: }
                   1419: 
1.126     brouard  1420: int nbocc(char *s, char occ)
                   1421: {
                   1422:   int i,j=0;
                   1423:   int lg=20;
                   1424:   i=0;
                   1425:   lg=strlen(s);
                   1426:   for(i=0; i<= lg; i++) {
1.234     brouard  1427:     if  (s[i] == occ ) j++;
1.126     brouard  1428:   }
                   1429:   return j;
                   1430: }
                   1431: 
1.137     brouard  1432: /* void cutv(char *u,char *v, char*t, char occ) */
                   1433: /* { */
                   1434: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1435: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1436: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1437: /*   int i,lg,j,p=0; */
                   1438: /*   i=0; */
                   1439: /*   lg=strlen(t); */
                   1440: /*   for(j=0; j<=lg-1; j++) { */
                   1441: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1442: /*   } */
1.126     brouard  1443: 
1.137     brouard  1444: /*   for(j=0; j<p; j++) { */
                   1445: /*     (u[j] = t[j]); */
                   1446: /*   } */
                   1447: /*      u[p]='\0'; */
1.126     brouard  1448: 
1.137     brouard  1449: /*    for(j=0; j<= lg; j++) { */
                   1450: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1451: /*   } */
                   1452: /* } */
1.126     brouard  1453: 
1.160     brouard  1454: #ifdef _WIN32
                   1455: char * strsep(char **pp, const char *delim)
                   1456: {
                   1457:   char *p, *q;
                   1458:          
                   1459:   if ((p = *pp) == NULL)
                   1460:     return 0;
                   1461:   if ((q = strpbrk (p, delim)) != NULL)
                   1462:   {
                   1463:     *pp = q + 1;
                   1464:     *q = '\0';
                   1465:   }
                   1466:   else
                   1467:     *pp = 0;
                   1468:   return p;
                   1469: }
                   1470: #endif
                   1471: 
1.126     brouard  1472: /********************** nrerror ********************/
                   1473: 
                   1474: void nrerror(char error_text[])
                   1475: {
                   1476:   fprintf(stderr,"ERREUR ...\n");
                   1477:   fprintf(stderr,"%s\n",error_text);
                   1478:   exit(EXIT_FAILURE);
                   1479: }
                   1480: /*********************** vector *******************/
                   1481: double *vector(int nl, int nh)
                   1482: {
                   1483:   double *v;
                   1484:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1485:   if (!v) nrerror("allocation failure in vector");
                   1486:   return v-nl+NR_END;
                   1487: }
                   1488: 
                   1489: /************************ free vector ******************/
                   1490: void free_vector(double*v, int nl, int nh)
                   1491: {
                   1492:   free((FREE_ARG)(v+nl-NR_END));
                   1493: }
                   1494: 
                   1495: /************************ivector *******************************/
                   1496: int *ivector(long nl,long nh)
                   1497: {
                   1498:   int *v;
                   1499:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1500:   if (!v) nrerror("allocation failure in ivector");
                   1501:   return v-nl+NR_END;
                   1502: }
                   1503: 
                   1504: /******************free ivector **************************/
                   1505: void free_ivector(int *v, long nl, long nh)
                   1506: {
                   1507:   free((FREE_ARG)(v+nl-NR_END));
                   1508: }
                   1509: 
                   1510: /************************lvector *******************************/
                   1511: long *lvector(long nl,long nh)
                   1512: {
                   1513:   long *v;
                   1514:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1515:   if (!v) nrerror("allocation failure in ivector");
                   1516:   return v-nl+NR_END;
                   1517: }
                   1518: 
                   1519: /******************free lvector **************************/
                   1520: void free_lvector(long *v, long nl, long nh)
                   1521: {
                   1522:   free((FREE_ARG)(v+nl-NR_END));
                   1523: }
                   1524: 
                   1525: /******************* imatrix *******************************/
                   1526: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1527:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1528: { 
                   1529:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1530:   int **m; 
                   1531:   
                   1532:   /* allocate pointers to rows */ 
                   1533:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1534:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1535:   m += NR_END; 
                   1536:   m -= nrl; 
                   1537:   
                   1538:   
                   1539:   /* allocate rows and set pointers to them */ 
                   1540:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1541:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1542:   m[nrl] += NR_END; 
                   1543:   m[nrl] -= ncl; 
                   1544:   
                   1545:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1546:   
                   1547:   /* return pointer to array of pointers to rows */ 
                   1548:   return m; 
                   1549: } 
                   1550: 
                   1551: /****************** free_imatrix *************************/
                   1552: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1553:       int **m;
                   1554:       long nch,ncl,nrh,nrl; 
                   1555:      /* free an int matrix allocated by imatrix() */ 
                   1556: { 
                   1557:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1558:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1559: } 
                   1560: 
                   1561: /******************* matrix *******************************/
                   1562: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1563: {
                   1564:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1565:   double **m;
                   1566: 
                   1567:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1568:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1569:   m += NR_END;
                   1570:   m -= nrl;
                   1571: 
                   1572:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1573:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1574:   m[nrl] += NR_END;
                   1575:   m[nrl] -= ncl;
                   1576: 
                   1577:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1578:   return m;
1.145     brouard  1579:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1580: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1581: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1582:    */
                   1583: }
                   1584: 
                   1585: /*************************free matrix ************************/
                   1586: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1587: {
                   1588:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1589:   free((FREE_ARG)(m+nrl-NR_END));
                   1590: }
                   1591: 
                   1592: /******************* ma3x *******************************/
                   1593: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1594: {
                   1595:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1596:   double ***m;
                   1597: 
                   1598:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1599:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1600:   m += NR_END;
                   1601:   m -= nrl;
                   1602: 
                   1603:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1604:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1605:   m[nrl] += NR_END;
                   1606:   m[nrl] -= ncl;
                   1607: 
                   1608:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1609: 
                   1610:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1611:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1612:   m[nrl][ncl] += NR_END;
                   1613:   m[nrl][ncl] -= nll;
                   1614:   for (j=ncl+1; j<=nch; j++) 
                   1615:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1616:   
                   1617:   for (i=nrl+1; i<=nrh; i++) {
                   1618:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1619:     for (j=ncl+1; j<=nch; j++) 
                   1620:       m[i][j]=m[i][j-1]+nlay;
                   1621:   }
                   1622:   return m; 
                   1623:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1624:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1625:   */
                   1626: }
                   1627: 
                   1628: /*************************free ma3x ************************/
                   1629: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1630: {
                   1631:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1632:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1633:   free((FREE_ARG)(m+nrl-NR_END));
                   1634: }
                   1635: 
                   1636: /*************** function subdirf ***********/
                   1637: char *subdirf(char fileres[])
                   1638: {
                   1639:   /* Caution optionfilefiname is hidden */
                   1640:   strcpy(tmpout,optionfilefiname);
                   1641:   strcat(tmpout,"/"); /* Add to the right */
                   1642:   strcat(tmpout,fileres);
                   1643:   return tmpout;
                   1644: }
                   1645: 
                   1646: /*************** function subdirf2 ***********/
                   1647: char *subdirf2(char fileres[], char *preop)
                   1648: {
                   1649:   
                   1650:   /* Caution optionfilefiname is hidden */
                   1651:   strcpy(tmpout,optionfilefiname);
                   1652:   strcat(tmpout,"/");
                   1653:   strcat(tmpout,preop);
                   1654:   strcat(tmpout,fileres);
                   1655:   return tmpout;
                   1656: }
                   1657: 
                   1658: /*************** function subdirf3 ***********/
                   1659: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1660: {
                   1661:   
                   1662:   /* Caution optionfilefiname is hidden */
                   1663:   strcpy(tmpout,optionfilefiname);
                   1664:   strcat(tmpout,"/");
                   1665:   strcat(tmpout,preop);
                   1666:   strcat(tmpout,preop2);
                   1667:   strcat(tmpout,fileres);
                   1668:   return tmpout;
                   1669: }
1.213     brouard  1670:  
                   1671: /*************** function subdirfext ***********/
                   1672: char *subdirfext(char fileres[], char *preop, char *postop)
                   1673: {
                   1674:   
                   1675:   strcpy(tmpout,preop);
                   1676:   strcat(tmpout,fileres);
                   1677:   strcat(tmpout,postop);
                   1678:   return tmpout;
                   1679: }
1.126     brouard  1680: 
1.213     brouard  1681: /*************** function subdirfext3 ***********/
                   1682: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1683: {
                   1684:   
                   1685:   /* Caution optionfilefiname is hidden */
                   1686:   strcpy(tmpout,optionfilefiname);
                   1687:   strcat(tmpout,"/");
                   1688:   strcat(tmpout,preop);
                   1689:   strcat(tmpout,fileres);
                   1690:   strcat(tmpout,postop);
                   1691:   return tmpout;
                   1692: }
                   1693:  
1.162     brouard  1694: char *asc_diff_time(long time_sec, char ascdiff[])
                   1695: {
                   1696:   long sec_left, days, hours, minutes;
                   1697:   days = (time_sec) / (60*60*24);
                   1698:   sec_left = (time_sec) % (60*60*24);
                   1699:   hours = (sec_left) / (60*60) ;
                   1700:   sec_left = (sec_left) %(60*60);
                   1701:   minutes = (sec_left) /60;
                   1702:   sec_left = (sec_left) % (60);
                   1703:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1704:   return ascdiff;
                   1705: }
                   1706: 
1.126     brouard  1707: /***************** f1dim *************************/
                   1708: extern int ncom; 
                   1709: extern double *pcom,*xicom;
                   1710: extern double (*nrfunc)(double []); 
                   1711:  
                   1712: double f1dim(double x) 
                   1713: { 
                   1714:   int j; 
                   1715:   double f;
                   1716:   double *xt; 
                   1717:  
                   1718:   xt=vector(1,ncom); 
                   1719:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1720:   f=(*nrfunc)(xt); 
                   1721:   free_vector(xt,1,ncom); 
                   1722:   return f; 
                   1723: } 
                   1724: 
                   1725: /*****************brent *************************/
                   1726: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1727: {
                   1728:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1729:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1730:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1731:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1732:    * returned function value. 
                   1733:   */
1.126     brouard  1734:   int iter; 
                   1735:   double a,b,d,etemp;
1.159     brouard  1736:   double fu=0,fv,fw,fx;
1.164     brouard  1737:   double ftemp=0.;
1.126     brouard  1738:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1739:   double e=0.0; 
                   1740:  
                   1741:   a=(ax < cx ? ax : cx); 
                   1742:   b=(ax > cx ? ax : cx); 
                   1743:   x=w=v=bx; 
                   1744:   fw=fv=fx=(*f)(x); 
                   1745:   for (iter=1;iter<=ITMAX;iter++) { 
                   1746:     xm=0.5*(a+b); 
                   1747:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1748:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1749:     printf(".");fflush(stdout);
                   1750:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1751: #ifdef DEBUGBRENT
1.126     brouard  1752:     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);
                   1753:     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);
                   1754:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1755: #endif
                   1756:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1757:       *xmin=x; 
                   1758:       return fx; 
                   1759:     } 
                   1760:     ftemp=fu;
                   1761:     if (fabs(e) > tol1) { 
                   1762:       r=(x-w)*(fx-fv); 
                   1763:       q=(x-v)*(fx-fw); 
                   1764:       p=(x-v)*q-(x-w)*r; 
                   1765:       q=2.0*(q-r); 
                   1766:       if (q > 0.0) p = -p; 
                   1767:       q=fabs(q); 
                   1768:       etemp=e; 
                   1769:       e=d; 
                   1770:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1771:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1772:       else { 
1.224     brouard  1773:                                d=p/q; 
                   1774:                                u=x+d; 
                   1775:                                if (u-a < tol2 || b-u < tol2) 
                   1776:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1777:       } 
                   1778:     } else { 
                   1779:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1780:     } 
                   1781:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1782:     fu=(*f)(u); 
                   1783:     if (fu <= fx) { 
                   1784:       if (u >= x) a=x; else b=x; 
                   1785:       SHFT(v,w,x,u) 
1.183     brouard  1786:       SHFT(fv,fw,fx,fu) 
                   1787:     } else { 
                   1788:       if (u < x) a=u; else b=u; 
                   1789:       if (fu <= fw || w == x) { 
1.224     brouard  1790:                                v=w; 
                   1791:                                w=u; 
                   1792:                                fv=fw; 
                   1793:                                fw=fu; 
1.183     brouard  1794:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1795:                                v=u; 
                   1796:                                fv=fu; 
1.183     brouard  1797:       } 
                   1798:     } 
1.126     brouard  1799:   } 
                   1800:   nrerror("Too many iterations in brent"); 
                   1801:   *xmin=x; 
                   1802:   return fx; 
                   1803: } 
                   1804: 
                   1805: /****************** mnbrak ***********************/
                   1806: 
                   1807: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1808:            double (*func)(double)) 
1.183     brouard  1809: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1810: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1811: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1812: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1813:    */
1.126     brouard  1814:   double ulim,u,r,q, dum;
                   1815:   double fu; 
1.187     brouard  1816: 
                   1817:   double scale=10.;
                   1818:   int iterscale=0;
                   1819: 
                   1820:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1821:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1822: 
                   1823: 
                   1824:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1825:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1826:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1827:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1828:   /* } */
                   1829: 
1.126     brouard  1830:   if (*fb > *fa) { 
                   1831:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1832:     SHFT(dum,*fb,*fa,dum) 
                   1833:   } 
1.126     brouard  1834:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1835:   *fc=(*func)(*cx); 
1.183     brouard  1836: #ifdef DEBUG
1.224     brouard  1837:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1838:   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  1839: #endif
1.224     brouard  1840:   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  1841:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1842:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1843:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1844:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1845:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1846:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1847:       fu=(*func)(u); 
1.163     brouard  1848: #ifdef DEBUG
                   1849:       /* f(x)=A(x-u)**2+f(u) */
                   1850:       double A, fparabu; 
                   1851:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1852:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1853:       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);
                   1854:       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  1855:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1856:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1857:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1858:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1859: #endif 
1.184     brouard  1860: #ifdef MNBRAKORIGINAL
1.183     brouard  1861: #else
1.191     brouard  1862: /*       if (fu > *fc) { */
                   1863: /* #ifdef DEBUG */
                   1864: /*       printf("mnbrak4  fu > fc \n"); */
                   1865: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1866: /* #endif */
                   1867: /*     /\* 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 *\\/  *\/ */
                   1868: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1869: /*     dum=u; /\* Shifting c and u *\/ */
                   1870: /*     u = *cx; */
                   1871: /*     *cx = dum; */
                   1872: /*     dum = fu; */
                   1873: /*     fu = *fc; */
                   1874: /*     *fc =dum; */
                   1875: /*       } else { /\* end *\/ */
                   1876: /* #ifdef DEBUG */
                   1877: /*       printf("mnbrak3  fu < fc \n"); */
                   1878: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1879: /* #endif */
                   1880: /*     dum=u; /\* Shifting c and u *\/ */
                   1881: /*     u = *cx; */
                   1882: /*     *cx = dum; */
                   1883: /*     dum = fu; */
                   1884: /*     fu = *fc; */
                   1885: /*     *fc =dum; */
                   1886: /*       } */
1.224     brouard  1887: #ifdef DEBUGMNBRAK
                   1888:                 double A, fparabu; 
                   1889:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1890:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1891:      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);
                   1892:      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  1893: #endif
1.191     brouard  1894:       dum=u; /* Shifting c and u */
                   1895:       u = *cx;
                   1896:       *cx = dum;
                   1897:       dum = fu;
                   1898:       fu = *fc;
                   1899:       *fc =dum;
1.183     brouard  1900: #endif
1.162     brouard  1901:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1902: #ifdef DEBUG
1.224     brouard  1903:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1904:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1905: #endif
1.126     brouard  1906:       fu=(*func)(u); 
                   1907:       if (fu < *fc) { 
1.183     brouard  1908: #ifdef DEBUG
1.224     brouard  1909:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1910:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1911: #endif
                   1912:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1913:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1914: #ifdef DEBUG
                   1915:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1916: #endif
                   1917:       } 
1.162     brouard  1918:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1919: #ifdef DEBUG
1.224     brouard  1920:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1921:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1922: #endif
1.126     brouard  1923:       u=ulim; 
                   1924:       fu=(*func)(u); 
1.183     brouard  1925:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1926: #ifdef DEBUG
1.224     brouard  1927:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1928:       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  1929: #endif
1.126     brouard  1930:       u=(*cx)+GOLD*(*cx-*bx); 
                   1931:       fu=(*func)(u); 
1.224     brouard  1932: #ifdef DEBUG
                   1933:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1934:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1935: #endif
1.183     brouard  1936:     } /* end tests */
1.126     brouard  1937:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1938:     SHFT(*fa,*fb,*fc,fu) 
                   1939: #ifdef DEBUG
1.224     brouard  1940:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1941:       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  1942: #endif
                   1943:   } /* 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  1944: } 
                   1945: 
                   1946: /*************** linmin ************************/
1.162     brouard  1947: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1948: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1949: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1950: the value of func at the returned location p . This is actually all accomplished by calling the
                   1951: routines mnbrak and brent .*/
1.126     brouard  1952: int ncom; 
                   1953: double *pcom,*xicom;
                   1954: double (*nrfunc)(double []); 
                   1955:  
1.224     brouard  1956: #ifdef LINMINORIGINAL
1.126     brouard  1957: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1958: #else
                   1959: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1960: #endif
1.126     brouard  1961: { 
                   1962:   double brent(double ax, double bx, double cx, 
                   1963:               double (*f)(double), double tol, double *xmin); 
                   1964:   double f1dim(double x); 
                   1965:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1966:              double *fc, double (*func)(double)); 
                   1967:   int j; 
                   1968:   double xx,xmin,bx,ax; 
                   1969:   double fx,fb,fa;
1.187     brouard  1970: 
1.203     brouard  1971: #ifdef LINMINORIGINAL
                   1972: #else
                   1973:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1974: #endif
                   1975:   
1.126     brouard  1976:   ncom=n; 
                   1977:   pcom=vector(1,n); 
                   1978:   xicom=vector(1,n); 
                   1979:   nrfunc=func; 
                   1980:   for (j=1;j<=n;j++) { 
                   1981:     pcom[j]=p[j]; 
1.202     brouard  1982:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1983:   } 
1.187     brouard  1984: 
1.203     brouard  1985: #ifdef LINMINORIGINAL
                   1986:   xx=1.;
                   1987: #else
                   1988:   axs=0.0;
                   1989:   xxs=1.;
                   1990:   do{
                   1991:     xx= xxs;
                   1992: #endif
1.187     brouard  1993:     ax=0.;
                   1994:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1995:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1996:     /* 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))   */
                   1997:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1998:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1999:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2000:     /* 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  2001: #ifdef LINMINORIGINAL
                   2002: #else
                   2003:     if (fx != fx){
1.224     brouard  2004:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2005:                        printf("|");
                   2006:                        fprintf(ficlog,"|");
1.203     brouard  2007: #ifdef DEBUGLINMIN
1.224     brouard  2008:                        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  2009: #endif
                   2010:     }
1.224     brouard  2011:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2012: #endif
                   2013:   
1.191     brouard  2014: #ifdef DEBUGLINMIN
                   2015:   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  2016:   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  2017: #endif
1.224     brouard  2018: #ifdef LINMINORIGINAL
                   2019: #else
                   2020:        if(fb == fx){ /* Flat function in the direction */
                   2021:                xmin=xx;
                   2022:     *flat=1;
                   2023:        }else{
                   2024:     *flat=0;
                   2025: #endif
                   2026:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2027:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2028:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2029:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2030:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2031:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2032: #ifdef DEBUG
1.224     brouard  2033:   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);
                   2034:   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);
                   2035: #endif
                   2036: #ifdef LINMINORIGINAL
                   2037: #else
                   2038:                        }
1.126     brouard  2039: #endif
1.191     brouard  2040: #ifdef DEBUGLINMIN
                   2041:   printf("linmin end ");
1.202     brouard  2042:   fprintf(ficlog,"linmin end ");
1.191     brouard  2043: #endif
1.126     brouard  2044:   for (j=1;j<=n;j++) { 
1.203     brouard  2045: #ifdef LINMINORIGINAL
                   2046:     xi[j] *= xmin; 
                   2047: #else
                   2048: #ifdef DEBUGLINMIN
                   2049:     if(xxs <1.0)
                   2050:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2051: #endif
                   2052:     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) */
                   2053: #ifdef DEBUGLINMIN
                   2054:     if(xxs <1.0)
                   2055:       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 );
                   2056: #endif
                   2057: #endif
1.187     brouard  2058:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2059:   } 
1.191     brouard  2060: #ifdef DEBUGLINMIN
1.203     brouard  2061:   printf("\n");
1.191     brouard  2062:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2063:   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  2064:   for (j=1;j<=n;j++) { 
1.202     brouard  2065:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2066:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2067:     if(j % ncovmodel == 0){
1.191     brouard  2068:       printf("\n");
1.202     brouard  2069:       fprintf(ficlog,"\n");
                   2070:     }
1.191     brouard  2071:   }
1.203     brouard  2072: #else
1.191     brouard  2073: #endif
1.126     brouard  2074:   free_vector(xicom,1,n); 
                   2075:   free_vector(pcom,1,n); 
                   2076: } 
                   2077: 
                   2078: 
                   2079: /*************** powell ************************/
1.162     brouard  2080: /*
                   2081: Minimization of a function func of n variables. Input consists of an initial starting point
                   2082: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2083: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2084: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2085: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2086: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2087:  */
1.224     brouard  2088: #ifdef LINMINORIGINAL
                   2089: #else
                   2090:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2091:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2092: #endif
1.126     brouard  2093: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2094:            double (*func)(double [])) 
                   2095: { 
1.224     brouard  2096: #ifdef LINMINORIGINAL
                   2097:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2098:              double (*func)(double [])); 
1.224     brouard  2099: #else 
1.241     brouard  2100:  void linmin(double p[], double xi[], int n, double *fret,
                   2101:             double (*func)(double []),int *flat); 
1.224     brouard  2102: #endif
1.239     brouard  2103:  int i,ibig,j,jk,k; 
1.126     brouard  2104:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2105:   double directest;
1.126     brouard  2106:   double fp,fptt;
                   2107:   double *xits;
                   2108:   int niterf, itmp;
1.224     brouard  2109: #ifdef LINMINORIGINAL
                   2110: #else
                   2111: 
                   2112:   flatdir=ivector(1,n); 
                   2113:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2114: #endif
1.126     brouard  2115: 
                   2116:   pt=vector(1,n); 
                   2117:   ptt=vector(1,n); 
                   2118:   xit=vector(1,n); 
                   2119:   xits=vector(1,n); 
                   2120:   *fret=(*func)(p); 
                   2121:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2122:   rcurr_time = time(NULL);  
1.126     brouard  2123:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2124:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2125:     ibig=0; 
                   2126:     del=0.0; 
1.157     brouard  2127:     rlast_time=rcurr_time;
                   2128:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2129:     rcurr_time = time(NULL);  
                   2130:     curr_time = *localtime(&rcurr_time);
                   2131:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2132:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2133: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2134:     for (i=1;i<=n;i++) {
1.126     brouard  2135:       fprintf(ficrespow," %.12lf", p[i]);
                   2136:     }
1.239     brouard  2137:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2138:     printf("\n#model=  1      +     age ");
                   2139:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2140:     if(nagesqr==1){
1.241     brouard  2141:        printf("  + age*age  ");
                   2142:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2143:     }
                   2144:     for(j=1;j <=ncovmodel-2;j++){
                   2145:       if(Typevar[j]==0) {
                   2146:        printf("  +      V%d  ",Tvar[j]);
                   2147:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2148:       }else if(Typevar[j]==1) {
                   2149:        printf("  +    V%d*age ",Tvar[j]);
                   2150:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2151:       }else if(Typevar[j]==2) {
                   2152:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2153:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2154:       }
                   2155:     }
1.126     brouard  2156:     printf("\n");
1.239     brouard  2157: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2158: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2159:     fprintf(ficlog,"\n");
1.239     brouard  2160:     for(i=1,jk=1; i <=nlstate; i++){
                   2161:       for(k=1; k <=(nlstate+ndeath); k++){
                   2162:        if (k != i) {
                   2163:          printf("%d%d ",i,k);
                   2164:          fprintf(ficlog,"%d%d ",i,k);
                   2165:          for(j=1; j <=ncovmodel; j++){
                   2166:            printf("%12.7f ",p[jk]);
                   2167:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2168:            jk++; 
                   2169:          }
                   2170:          printf("\n");
                   2171:          fprintf(ficlog,"\n");
                   2172:        }
                   2173:       }
                   2174:     }
1.241     brouard  2175:     if(*iter <=3 && *iter >1){
1.157     brouard  2176:       tml = *localtime(&rcurr_time);
                   2177:       strcpy(strcurr,asctime(&tml));
                   2178:       rforecast_time=rcurr_time; 
1.126     brouard  2179:       itmp = strlen(strcurr);
                   2180:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2181:        strcurr[itmp-1]='\0';
1.162     brouard  2182:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2183:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2184:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2185:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2186:        forecast_time = *localtime(&rforecast_time);
                   2187:        strcpy(strfor,asctime(&forecast_time));
                   2188:        itmp = strlen(strfor);
                   2189:        if(strfor[itmp-1]=='\n')
                   2190:          strfor[itmp-1]='\0';
                   2191:        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);
                   2192:        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  2193:       }
                   2194:     }
1.187     brouard  2195:     for (i=1;i<=n;i++) { /* For each direction i */
                   2196:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2197:       fptt=(*fret); 
                   2198: #ifdef DEBUG
1.203     brouard  2199:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2200:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2201: #endif
1.203     brouard  2202:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2203:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2204: #ifdef LINMINORIGINAL
1.188     brouard  2205:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2206: #else
                   2207:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2208:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2209: #endif
                   2210:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2211:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2212:                                /* because that direction will be replaced unless the gain del is small */
                   2213:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2214:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2215:                                /* with the new direction. */
                   2216:                                del=fabs(fptt-(*fret)); 
                   2217:                                ibig=i; 
1.126     brouard  2218:       } 
                   2219: #ifdef DEBUG
                   2220:       printf("%d %.12e",i,(*fret));
                   2221:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2222:       for (j=1;j<=n;j++) {
1.224     brouard  2223:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2224:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2225:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2226:       }
                   2227:       for(j=1;j<=n;j++) {
1.225     brouard  2228:                                printf(" p(%d)=%.12e",j,p[j]);
                   2229:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2230:       }
                   2231:       printf("\n");
                   2232:       fprintf(ficlog,"\n");
                   2233: #endif
1.187     brouard  2234:     } /* end loop on each direction i */
                   2235:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2236:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2237:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2238:       for(j=1;j<=n;j++) {
1.225     brouard  2239:                                if(flatdir[j] >0){
                   2240:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2241:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2242:                                }
                   2243:                                /* printf("\n"); */
                   2244:                                /* fprintf(ficlog,"\n"); */
                   2245:                        }
1.243     brouard  2246:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2247:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2248:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2249:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2250:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2251:       /* decreased of more than 3.84  */
                   2252:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2253:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2254:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2255:                        
1.188     brouard  2256:       /* Starting the program with initial values given by a former maximization will simply change */
                   2257:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2258:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2259:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2260: #ifdef DEBUG
                   2261:       int k[2],l;
                   2262:       k[0]=1;
                   2263:       k[1]=-1;
                   2264:       printf("Max: %.12e",(*func)(p));
                   2265:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2266:       for (j=1;j<=n;j++) {
                   2267:        printf(" %.12e",p[j]);
                   2268:        fprintf(ficlog," %.12e",p[j]);
                   2269:       }
                   2270:       printf("\n");
                   2271:       fprintf(ficlog,"\n");
                   2272:       for(l=0;l<=1;l++) {
                   2273:        for (j=1;j<=n;j++) {
                   2274:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2275:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2276:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2277:        }
                   2278:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2279:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2280:       }
                   2281: #endif
                   2282: 
1.224     brouard  2283: #ifdef LINMINORIGINAL
                   2284: #else
                   2285:       free_ivector(flatdir,1,n); 
                   2286: #endif
1.126     brouard  2287:       free_vector(xit,1,n); 
                   2288:       free_vector(xits,1,n); 
                   2289:       free_vector(ptt,1,n); 
                   2290:       free_vector(pt,1,n); 
                   2291:       return; 
1.192     brouard  2292:     } /* enough precision */ 
1.240     brouard  2293:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2294:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2295:       ptt[j]=2.0*p[j]-pt[j]; 
                   2296:       xit[j]=p[j]-pt[j]; 
                   2297:       pt[j]=p[j]; 
                   2298:     } 
1.181     brouard  2299:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2300: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2301:                if (*iter <=4) {
1.225     brouard  2302: #else
                   2303: #endif
1.224     brouard  2304: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2305: #else
1.161     brouard  2306:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2307: #endif
1.162     brouard  2308:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2309:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2310:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2311:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2312:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2313:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2314:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2315:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2316:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2317:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2318:       /* mu² and del² are equal when f3=f1 */
                   2319:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2320:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2321:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2322:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2323: #ifdef NRCORIGINAL
                   2324:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2325: #else
                   2326:       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  2327:       t= t- del*SQR(fp-fptt);
1.183     brouard  2328: #endif
1.202     brouard  2329:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2330: #ifdef DEBUG
1.181     brouard  2331:       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);
                   2332:       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  2333:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2334:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2335:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2336:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2337:       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);
                   2338:       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);
                   2339: #endif
1.183     brouard  2340: #ifdef POWELLORIGINAL
                   2341:       if (t < 0.0) { /* Then we use it for new direction */
                   2342: #else
1.182     brouard  2343:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2344:                                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  2345:         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  2346:         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  2347:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2348:       } 
1.181     brouard  2349:       if (directest < 0.0) { /* Then we use it for new direction */
                   2350: #endif
1.191     brouard  2351: #ifdef DEBUGLINMIN
1.234     brouard  2352:        printf("Before linmin in direction P%d-P0\n",n);
                   2353:        for (j=1;j<=n;j++) {
                   2354:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2355:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2356:          if(j % ncovmodel == 0){
                   2357:            printf("\n");
                   2358:            fprintf(ficlog,"\n");
                   2359:          }
                   2360:        }
1.224     brouard  2361: #endif
                   2362: #ifdef LINMINORIGINAL
1.234     brouard  2363:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2364: #else
1.234     brouard  2365:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2366:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2367: #endif
1.234     brouard  2368:        
1.191     brouard  2369: #ifdef DEBUGLINMIN
1.234     brouard  2370:        for (j=1;j<=n;j++) { 
                   2371:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2372:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2373:          if(j % ncovmodel == 0){
                   2374:            printf("\n");
                   2375:            fprintf(ficlog,"\n");
                   2376:          }
                   2377:        }
1.224     brouard  2378: #endif
1.234     brouard  2379:        for (j=1;j<=n;j++) { 
                   2380:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2381:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2382:        }
1.224     brouard  2383: #ifdef LINMINORIGINAL
                   2384: #else
1.234     brouard  2385:        for (j=1, flatd=0;j<=n;j++) {
                   2386:          if(flatdir[j]>0)
                   2387:            flatd++;
                   2388:        }
                   2389:        if(flatd >0){
                   2390:          printf("%d flat directions\n",flatd);
                   2391:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2392:          for (j=1;j<=n;j++) { 
                   2393:            if(flatdir[j]>0){
                   2394:              printf("%d ",j);
                   2395:              fprintf(ficlog,"%d ",j);
                   2396:            }
                   2397:          }
                   2398:          printf("\n");
                   2399:          fprintf(ficlog,"\n");
                   2400:        }
1.191     brouard  2401: #endif
1.234     brouard  2402:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2403:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2404:        
1.126     brouard  2405: #ifdef DEBUG
1.234     brouard  2406:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2407:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2408:        for(j=1;j<=n;j++){
                   2409:          printf(" %lf",xit[j]);
                   2410:          fprintf(ficlog," %lf",xit[j]);
                   2411:        }
                   2412:        printf("\n");
                   2413:        fprintf(ficlog,"\n");
1.126     brouard  2414: #endif
1.192     brouard  2415:       } /* end of t or directest negative */
1.224     brouard  2416: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2417: #else
1.234     brouard  2418:       } /* end if (fptt < fp)  */
1.192     brouard  2419: #endif
1.225     brouard  2420: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2421:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2422: #else
1.224     brouard  2423: #endif
1.234     brouard  2424:                } /* loop iteration */ 
1.126     brouard  2425: } 
1.234     brouard  2426:   
1.126     brouard  2427: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2428:   
1.235     brouard  2429:   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  2430:   {
1.235     brouard  2431:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2432:        (and selected quantitative values in nres)
                   2433:        by left multiplying the unit
1.234     brouard  2434:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2435:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2436:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2437:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2438:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2439:   /* Initial matrix pimij */
                   2440:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2441:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2442:   /*  0,                   0                  , 1} */
                   2443:   /*
                   2444:    * and after some iteration: */
                   2445:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2446:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2447:   /*  0,                   0                  , 1} */
                   2448:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2449:   /* {0.51571254859325999, 0.4842874514067399, */
                   2450:   /*  0.51326036147820708, 0.48673963852179264} */
                   2451:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2452:     
1.126     brouard  2453:   int i, ii,j,k;
1.209     brouard  2454:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2455:   /* double **matprod2(); */ /* test */
1.218     brouard  2456:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2457:   double **newm;
1.209     brouard  2458:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2459:   int ncvloop=0;
1.169     brouard  2460:   
1.209     brouard  2461:   min=vector(1,nlstate);
                   2462:   max=vector(1,nlstate);
                   2463:   meandiff=vector(1,nlstate);
                   2464: 
1.218     brouard  2465:        /* Starting with matrix unity */
1.126     brouard  2466:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2467:     for (j=1;j<=nlstate+ndeath;j++){
                   2468:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2469:     }
1.169     brouard  2470:   
                   2471:   cov[1]=1.;
                   2472:   
                   2473:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2474:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2475:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2476:     ncvloop++;
1.126     brouard  2477:     newm=savm;
                   2478:     /* Covariates have to be included here again */
1.138     brouard  2479:     cov[2]=agefin;
1.187     brouard  2480:     if(nagesqr==1)
                   2481:       cov[3]= agefin*agefin;;
1.234     brouard  2482:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2483:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2484:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2485:       /* 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  2486:     }
                   2487:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2488:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2489:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2490:       /* 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  2491:     }
1.237     brouard  2492:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2493:       if(Dummy[Tvar[Tage[k]]]){
                   2494:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2495:       } else{
1.235     brouard  2496:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2497:       }
1.235     brouard  2498:       /* 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  2499:     }
1.237     brouard  2500:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2501:       /* 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.237     brouard  2502:       if(Dummy[Tvard[k][1]==0]){
                   2503:        if(Dummy[Tvard[k][2]==0]){
                   2504:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2505:        }else{
                   2506:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2507:        }
                   2508:       }else{
                   2509:        if(Dummy[Tvard[k][2]==0]){
                   2510:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2511:        }else{
                   2512:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2513:        }
                   2514:       }
1.234     brouard  2515:     }
1.138     brouard  2516:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2517:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2518:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2519:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2520:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2521:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2522:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2523:     
1.126     brouard  2524:     savm=oldm;
                   2525:     oldm=newm;
1.209     brouard  2526: 
                   2527:     for(j=1; j<=nlstate; j++){
                   2528:       max[j]=0.;
                   2529:       min[j]=1.;
                   2530:     }
                   2531:     for(i=1;i<=nlstate;i++){
                   2532:       sumnew=0;
                   2533:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2534:       for(j=1; j<=nlstate; j++){ 
                   2535:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2536:        max[j]=FMAX(max[j],prlim[i][j]);
                   2537:        min[j]=FMIN(min[j],prlim[i][j]);
                   2538:       }
                   2539:     }
                   2540: 
1.126     brouard  2541:     maxmax=0.;
1.209     brouard  2542:     for(j=1; j<=nlstate; j++){
                   2543:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2544:       maxmax=FMAX(maxmax,meandiff[j]);
                   2545:       /* 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  2546:     } /* j loop */
1.203     brouard  2547:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2548:     /* 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  2549:     if(maxmax < ftolpl){
1.209     brouard  2550:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2551:       free_vector(min,1,nlstate);
                   2552:       free_vector(max,1,nlstate);
                   2553:       free_vector(meandiff,1,nlstate);
1.126     brouard  2554:       return prlim;
                   2555:     }
1.169     brouard  2556:   } /* age loop */
1.208     brouard  2557:     /* After some age loop it doesn't converge */
1.209     brouard  2558:   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  2559: 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  2560:   /* 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); */
                   2561:   free_vector(min,1,nlstate);
                   2562:   free_vector(max,1,nlstate);
                   2563:   free_vector(meandiff,1,nlstate);
1.208     brouard  2564:   
1.169     brouard  2565:   return prlim; /* should not reach here */
1.126     brouard  2566: }
                   2567: 
1.217     brouard  2568: 
                   2569:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2570: 
1.218     brouard  2571:  /* 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) */
                   2572:  /* 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) */
1.242     brouard  2573:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2574: {
1.218     brouard  2575:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2576:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2577:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2578:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2579:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2580:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2581:   /* Initial matrix pimij */
                   2582:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2583:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2584:   /*  0,                   0                  , 1} */
                   2585:   /*
                   2586:    * and after some iteration: */
                   2587:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2588:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2589:   /*  0,                   0                  , 1} */
                   2590:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2591:   /* {0.51571254859325999, 0.4842874514067399, */
                   2592:   /*  0.51326036147820708, 0.48673963852179264} */
                   2593:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2594: 
                   2595:   int i, ii,j,k;
1.247     brouard  2596:   int first=0;
1.217     brouard  2597:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2598:   /* double **matprod2(); */ /* test */
                   2599:   double **out, cov[NCOVMAX+1], **bmij();
                   2600:   double **newm;
1.218     brouard  2601:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2602:   double        **oldm, **savm;  /* for use */
                   2603: 
1.217     brouard  2604:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2605:   int ncvloop=0;
                   2606:   
                   2607:   min=vector(1,nlstate);
                   2608:   max=vector(1,nlstate);
                   2609:   meandiff=vector(1,nlstate);
                   2610: 
1.218     brouard  2611:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2612:        oldm=oldms; savm=savms;
                   2613: 
                   2614:        /* Starting with matrix unity */
                   2615:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2616:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2617:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2618:     }
                   2619:   
                   2620:   cov[1]=1.;
                   2621:   
                   2622:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2623:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2624:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2625:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2626:     ncvloop++;
1.218     brouard  2627:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2628:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2629:     /* Covariates have to be included here again */
                   2630:     cov[2]=agefin;
                   2631:     if(nagesqr==1)
                   2632:       cov[3]= agefin*agefin;;
1.242     brouard  2633:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2634:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2635:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2636:       /* printf("bprevalim 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)); */
                   2637:     }
                   2638:     /* for (k=1; k<=cptcovn;k++) { */
                   2639:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2640:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2641:     /*   /\* 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])]); *\/ */
                   2642:     /* } */
                   2643:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2644:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2645:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2646:       /* 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]); */
                   2647:     }
                   2648:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2649:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2650:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2651:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2652:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2653:       if(Dummy[Tvar[Tage[k]]]){
                   2654:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2655:       } else{
                   2656:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2657:       }
                   2658:       /* 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]); */
                   2659:     }
                   2660:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2661:       /* 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]); */
                   2662:       if(Dummy[Tvard[k][1]==0]){
                   2663:        if(Dummy[Tvard[k][2]==0]){
                   2664:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2665:        }else{
                   2666:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2667:        }
                   2668:       }else{
                   2669:        if(Dummy[Tvard[k][2]==0]){
                   2670:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2671:        }else{
                   2672:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2673:        }
                   2674:       }
1.217     brouard  2675:     }
                   2676:     
                   2677:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2678:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2679:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2680:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2681:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2682:                /* ij should be linked to the correct index of cov */
                   2683:                /* age and covariate values ij are in 'cov', but we need to pass
                   2684:                 * ij for the observed prevalence at age and status and covariate
                   2685:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2686:                 */
                   2687:     /* 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 *\/ */
                   2688:     /* 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 *\/ */
                   2689:     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  2690:     savm=oldm;
                   2691:     oldm=newm;
                   2692:     for(j=1; j<=nlstate; j++){
                   2693:       max[j]=0.;
                   2694:       min[j]=1.;
                   2695:     }
                   2696:     for(j=1; j<=nlstate; j++){ 
                   2697:       for(i=1;i<=nlstate;i++){
1.234     brouard  2698:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2699:        bprlim[i][j]= newm[i][j];
                   2700:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2701:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2702:       }
                   2703:     }
1.218     brouard  2704:                
1.217     brouard  2705:     maxmax=0.;
                   2706:     for(i=1; i<=nlstate; i++){
                   2707:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2708:       maxmax=FMAX(maxmax,meandiff[i]);
                   2709:       /* 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); */
                   2710:     } /* j loop */
                   2711:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2712:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2713:     if(maxmax < ftolpl){
1.220     brouard  2714:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2715:       free_vector(min,1,nlstate);
                   2716:       free_vector(max,1,nlstate);
                   2717:       free_vector(meandiff,1,nlstate);
                   2718:       return bprlim;
                   2719:     }
                   2720:   } /* age loop */
                   2721:     /* After some age loop it doesn't converge */
1.247     brouard  2722:   if(first){
                   2723:     first=1;
                   2724:     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'. Others in log file only...\n\
                   2725: 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);
                   2726:   }
                   2727:   fprintf(ficlog,"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\
1.217     brouard  2728: 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);
                   2729:   /* 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); */
                   2730:   free_vector(min,1,nlstate);
                   2731:   free_vector(max,1,nlstate);
                   2732:   free_vector(meandiff,1,nlstate);
                   2733:   
                   2734:   return bprlim; /* should not reach here */
                   2735: }
                   2736: 
1.126     brouard  2737: /*************** transition probabilities ***************/ 
                   2738: 
                   2739: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2740: {
1.138     brouard  2741:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2742:      computes the probability to be observed in state j being in state i by appying the
                   2743:      model to the ncovmodel covariates (including constant and age).
                   2744:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2745:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2746:      ncth covariate in the global vector x is given by the formula:
                   2747:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2748:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2749:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2750:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2751:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2752:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2753:   */
                   2754:   double s1, lnpijopii;
1.126     brouard  2755:   /*double t34;*/
1.164     brouard  2756:   int i,j, nc, ii, jj;
1.126     brouard  2757: 
1.223     brouard  2758:   for(i=1; i<= nlstate; i++){
                   2759:     for(j=1; j<i;j++){
                   2760:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2761:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2762:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2763:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2764:       }
                   2765:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2766:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2767:     }
                   2768:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2769:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2770:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2771:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2772:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2773:       }
                   2774:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2775:     }
                   2776:   }
1.218     brouard  2777:   
1.223     brouard  2778:   for(i=1; i<= nlstate; i++){
                   2779:     s1=0;
                   2780:     for(j=1; j<i; j++){
                   2781:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2782:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2783:     }
                   2784:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2785:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2786:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2787:     }
                   2788:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2789:     ps[i][i]=1./(s1+1.);
                   2790:     /* Computing other pijs */
                   2791:     for(j=1; j<i; j++)
                   2792:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2793:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2794:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2795:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2796:   } /* end i */
1.218     brouard  2797:   
1.223     brouard  2798:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2799:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2800:       ps[ii][jj]=0;
                   2801:       ps[ii][ii]=1;
                   2802:     }
                   2803:   }
1.218     brouard  2804:   
                   2805:   
1.223     brouard  2806:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2807:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2808:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2809:   /*   } */
                   2810:   /*   printf("\n "); */
                   2811:   /* } */
                   2812:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2813:   /*
                   2814:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2815:                goto end;*/
1.223     brouard  2816:   return ps;
1.126     brouard  2817: }
                   2818: 
1.218     brouard  2819: /*************** backward transition probabilities ***************/ 
                   2820: 
                   2821:  /* 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 ) */
                   2822: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2823:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2824: {
1.222     brouard  2825:   /* Computes the backward probability at age agefin and covariate ij
                   2826:    * and returns in **ps as well as **bmij.
                   2827:    */
1.218     brouard  2828:   int i, ii, j,k;
1.222     brouard  2829:   
                   2830:   double **out, **pmij();
                   2831:   double sumnew=0.;
1.218     brouard  2832:   double agefin;
1.222     brouard  2833:   
                   2834:   double **dnewm, **dsavm, **doldm;
                   2835:   double **bbmij;
                   2836:   
1.218     brouard  2837:   doldm=ddoldms; /* global pointers */
1.222     brouard  2838:   dnewm=ddnewms;
                   2839:   dsavm=ddsavms;
                   2840:   
                   2841:   agefin=cov[2];
                   2842:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2843:      the observed prevalence (with this covariate ij) */
                   2844:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2845:   /* We do have the matrix Px in savm  and we need pij */
                   2846:   for (j=1;j<=nlstate+ndeath;j++){
                   2847:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2848:     for (ii=1;ii<=nlstate;ii++){
                   2849:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2850:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2851:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2852:       if(sumnew >= 1.e-10){
                   2853:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2854:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2855:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2856:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2857:        /* }else */
                   2858:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2859:       }else{
1.242     brouard  2860:        ;
                   2861:        /* 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); */
1.222     brouard  2862:       }
                   2863:     } /*End ii */
                   2864:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2865:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2866:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2867:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2868:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2869:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2870:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2871:   for (j=1;j<=nlstate+ndeath;j++){
                   2872:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2873:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2874:     }
                   2875:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2876:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2877:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2878:   /* end bmij */
                   2879:   return ps; 
1.218     brouard  2880: }
1.217     brouard  2881: /*************** transition probabilities ***************/ 
                   2882: 
1.218     brouard  2883: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2884: {
                   2885:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2886:      computes the probability to be observed in state j being in state i by appying the
                   2887:      model to the ncovmodel covariates (including constant and age).
                   2888:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2889:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2890:      ncth covariate in the global vector x is given by the formula:
                   2891:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2892:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2893:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2894:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2895:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2896:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2897:   */
                   2898:   double s1, lnpijopii;
                   2899:   /*double t34;*/
                   2900:   int i,j, nc, ii, jj;
                   2901: 
1.234     brouard  2902:   for(i=1; i<= nlstate; i++){
                   2903:     for(j=1; j<i;j++){
                   2904:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2905:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2906:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2907:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2908:       }
                   2909:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2910:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2911:     }
                   2912:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2913:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2914:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2915:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2916:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2917:       }
                   2918:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2919:     }
                   2920:   }
                   2921:   
                   2922:   for(i=1; i<= nlstate; i++){
                   2923:     s1=0;
                   2924:     for(j=1; j<i; j++){
                   2925:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2926:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2927:     }
                   2928:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2929:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2930:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2931:     }
                   2932:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2933:     ps[i][i]=1./(s1+1.);
                   2934:     /* Computing other pijs */
                   2935:     for(j=1; j<i; j++)
                   2936:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2937:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2938:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2939:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2940:   } /* end i */
                   2941:   
                   2942:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2943:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2944:       ps[ii][jj]=0;
                   2945:       ps[ii][ii]=1;
                   2946:     }
                   2947:   }
                   2948:   /* Added for backcast */ /* Transposed matrix too */
                   2949:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2950:     s1=0.;
                   2951:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2952:       s1+=ps[ii][jj];
                   2953:     }
                   2954:     for(ii=1; ii<= nlstate; ii++){
                   2955:       ps[ii][jj]=ps[ii][jj]/s1;
                   2956:     }
                   2957:   }
                   2958:   /* Transposition */
                   2959:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2960:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2961:       s1=ps[ii][jj];
                   2962:       ps[ii][jj]=ps[jj][ii];
                   2963:       ps[jj][ii]=s1;
                   2964:     }
                   2965:   }
                   2966:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2967:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2968:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2969:   /*   } */
                   2970:   /*   printf("\n "); */
                   2971:   /* } */
                   2972:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2973:   /*
                   2974:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2975:     goto end;*/
                   2976:   return ps;
1.217     brouard  2977: }
                   2978: 
                   2979: 
1.126     brouard  2980: /**************** Product of 2 matrices ******************/
                   2981: 
1.145     brouard  2982: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2983: {
                   2984:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2985:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2986:   /* in, b, out are matrice of pointers which should have been initialized 
                   2987:      before: only the contents of out is modified. The function returns
                   2988:      a pointer to pointers identical to out */
1.145     brouard  2989:   int i, j, k;
1.126     brouard  2990:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2991:     for(k=ncolol; k<=ncoloh; k++){
                   2992:       out[i][k]=0.;
                   2993:       for(j=ncl; j<=nch; j++)
                   2994:        out[i][k] +=in[i][j]*b[j][k];
                   2995:     }
1.126     brouard  2996:   return out;
                   2997: }
                   2998: 
                   2999: 
                   3000: /************* Higher Matrix Product ***************/
                   3001: 
1.235     brouard  3002: 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  3003: {
1.218     brouard  3004:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3005:      'nhstepm*hstepm*stepm' months (i.e. until
                   3006:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3007:      nhstepm*hstepm matrices. 
                   3008:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3009:      (typically every 2 years instead of every month which is too big 
                   3010:      for the memory).
                   3011:      Model is determined by parameters x and covariates have to be 
                   3012:      included manually here. 
                   3013: 
                   3014:      */
                   3015: 
                   3016:   int i, j, d, h, k;
1.131     brouard  3017:   double **out, cov[NCOVMAX+1];
1.126     brouard  3018:   double **newm;
1.187     brouard  3019:   double agexact;
1.214     brouard  3020:   double agebegin, ageend;
1.126     brouard  3021: 
                   3022:   /* Hstepm could be zero and should return the unit matrix */
                   3023:   for (i=1;i<=nlstate+ndeath;i++)
                   3024:     for (j=1;j<=nlstate+ndeath;j++){
                   3025:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3026:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3027:     }
                   3028:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3029:   for(h=1; h <=nhstepm; h++){
                   3030:     for(d=1; d <=hstepm; d++){
                   3031:       newm=savm;
                   3032:       /* Covariates have to be included here again */
                   3033:       cov[1]=1.;
1.214     brouard  3034:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3035:       cov[2]=agexact;
                   3036:       if(nagesqr==1)
1.227     brouard  3037:        cov[3]= agexact*agexact;
1.235     brouard  3038:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3039:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3040:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3041:        /* 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)); */
                   3042:       }
                   3043:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3044:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3045:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3046:        /* 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]); */
                   3047:       }
                   3048:       for (k=1; k<=cptcovage;k++){
                   3049:        if(Dummy[Tvar[Tage[k]]]){
                   3050:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3051:        } else{
                   3052:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3053:        }
                   3054:        /* 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]); */
                   3055:       }
                   3056:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3057:        /* 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]); */
                   3058:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3059:       }
                   3060:       /* for (k=1; k<=cptcovn;k++)  */
                   3061:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3062:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3063:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3064:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3065:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3066:       
                   3067:       
1.126     brouard  3068:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3069:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3070:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3071:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3072:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3073:       /* if((int)age == 70){ */
                   3074:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3075:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3076:       /*         printf("%d pmmij ",i); */
                   3077:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3078:       /*           printf("%f ",pmmij[i][j]); */
                   3079:       /*         } */
                   3080:       /*         printf(" oldm "); */
                   3081:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3082:       /*           printf("%f ",oldm[i][j]); */
                   3083:       /*         } */
                   3084:       /*         printf("\n"); */
                   3085:       /*       } */
                   3086:       /* } */
1.126     brouard  3087:       savm=oldm;
                   3088:       oldm=newm;
                   3089:     }
                   3090:     for(i=1; i<=nlstate+ndeath; i++)
                   3091:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3092:                                po[i][j][h]=newm[i][j];
                   3093:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3094:       }
1.128     brouard  3095:     /*printf("h=%d ",h);*/
1.126     brouard  3096:   } /* end h */
1.218     brouard  3097:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3098:   return po;
                   3099: }
                   3100: 
1.217     brouard  3101: /************* Higher Back Matrix Product ***************/
1.218     brouard  3102: /* 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  3103: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3104: {
1.218     brouard  3105:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3106:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3107:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3108:      nhstepm*hstepm matrices.
                   3109:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3110:      (typically every 2 years instead of every month which is too big
1.217     brouard  3111:      for the memory).
1.218     brouard  3112:      Model is determined by parameters x and covariates have to be
                   3113:      included manually here.
1.217     brouard  3114: 
1.222     brouard  3115:   */
1.217     brouard  3116: 
                   3117:   int i, j, d, h, k;
                   3118:   double **out, cov[NCOVMAX+1];
                   3119:   double **newm;
                   3120:   double agexact;
                   3121:   double agebegin, ageend;
1.222     brouard  3122:   double **oldm, **savm;
1.217     brouard  3123: 
1.222     brouard  3124:   oldm=oldms;savm=savms;
1.217     brouard  3125:   /* Hstepm could be zero and should return the unit matrix */
                   3126:   for (i=1;i<=nlstate+ndeath;i++)
                   3127:     for (j=1;j<=nlstate+ndeath;j++){
                   3128:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3129:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3130:     }
                   3131:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3132:   for(h=1; h <=nhstepm; h++){
                   3133:     for(d=1; d <=hstepm; d++){
                   3134:       newm=savm;
                   3135:       /* Covariates have to be included here again */
                   3136:       cov[1]=1.;
                   3137:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3138:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3139:       cov[2]=agexact;
                   3140:       if(nagesqr==1)
1.222     brouard  3141:        cov[3]= agexact*agexact;
1.218     brouard  3142:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3143:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3144:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3145:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3146:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3147:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3148:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3149:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3150:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3151:       /* 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  3152:                        
                   3153:                        
1.217     brouard  3154:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3155:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3156:       /* Careful transposed matrix */
1.222     brouard  3157:       /* age is in cov[2] */
1.218     brouard  3158:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3159:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3160:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3161:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3162:       /* if((int)age == 70){ */
                   3163:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3164:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3165:       /*         printf("%d pmmij ",i); */
                   3166:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3167:       /*           printf("%f ",pmmij[i][j]); */
                   3168:       /*         } */
                   3169:       /*         printf(" oldm "); */
                   3170:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3171:       /*           printf("%f ",oldm[i][j]); */
                   3172:       /*         } */
                   3173:       /*         printf("\n"); */
                   3174:       /*       } */
                   3175:       /* } */
                   3176:       savm=oldm;
                   3177:       oldm=newm;
                   3178:     }
                   3179:     for(i=1; i<=nlstate+ndeath; i++)
                   3180:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3181:        po[i][j][h]=newm[i][j];
                   3182:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3183:       }
                   3184:     /*printf("h=%d ",h);*/
                   3185:   } /* end h */
1.222     brouard  3186:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3187:   return po;
                   3188: }
                   3189: 
                   3190: 
1.162     brouard  3191: #ifdef NLOPT
                   3192:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3193:   double fret;
                   3194:   double *xt;
                   3195:   int j;
                   3196:   myfunc_data *d2 = (myfunc_data *) pd;
                   3197: /* xt = (p1-1); */
                   3198:   xt=vector(1,n); 
                   3199:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3200: 
                   3201:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3202:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3203:   printf("Function = %.12lf ",fret);
                   3204:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3205:   printf("\n");
                   3206:  free_vector(xt,1,n);
                   3207:   return fret;
                   3208: }
                   3209: #endif
1.126     brouard  3210: 
                   3211: /*************** log-likelihood *************/
                   3212: double func( double *x)
                   3213: {
1.226     brouard  3214:   int i, ii, j, k, mi, d, kk;
                   3215:   int ioffset=0;
                   3216:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3217:   double **out;
                   3218:   double lli; /* Individual log likelihood */
                   3219:   int s1, s2;
1.228     brouard  3220:   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  3221:   double bbh, survp;
                   3222:   long ipmx;
                   3223:   double agexact;
                   3224:   /*extern weight */
                   3225:   /* We are differentiating ll according to initial status */
                   3226:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3227:   /*for(i=1;i<imx;i++) 
                   3228:     printf(" %d\n",s[4][i]);
                   3229:   */
1.162     brouard  3230: 
1.226     brouard  3231:   ++countcallfunc;
1.162     brouard  3232: 
1.226     brouard  3233:   cov[1]=1.;
1.126     brouard  3234: 
1.226     brouard  3235:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3236:   ioffset=0;
1.226     brouard  3237:   if(mle==1){
                   3238:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3239:       /* Computes the values of the ncovmodel covariates of the model
                   3240:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3241:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3242:         to be observed in j being in i according to the model.
                   3243:       */
1.243     brouard  3244:       ioffset=2+nagesqr ;
1.233     brouard  3245:    /* Fixed */
1.234     brouard  3246:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3247:        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)*/
                   3248:       }
1.226     brouard  3249:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3250:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3251:         has been calculated etc */
                   3252:       /* For an individual i, wav[i] gives the number of effective waves */
                   3253:       /* We compute the contribution to Likelihood of each effective transition
                   3254:         mw[mi][i] is real wave of the mi th effectve wave */
                   3255:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3256:         s2=s[mw[mi+1][i]][i];
                   3257:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3258:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3259:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3260:       */
                   3261:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3262:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3263:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3264:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3265:        }
                   3266:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3267:          for (j=1;j<=nlstate+ndeath;j++){
                   3268:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3269:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3270:          }
                   3271:        for(d=0; d<dh[mi][i]; d++){
                   3272:          newm=savm;
                   3273:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3274:          cov[2]=agexact;
                   3275:          if(nagesqr==1)
                   3276:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3277:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3278:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3279:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3280:          else
                   3281:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3282:          }
                   3283:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3284:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3285:          savm=oldm;
                   3286:          oldm=newm;
                   3287:        } /* end mult */
                   3288:        
                   3289:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3290:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3291:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3292:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3293:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3294:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3295:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3296:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3297:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3298:                                 * -stepm/2 to stepm/2 .
                   3299:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3300:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3301:                                 */
1.234     brouard  3302:        s1=s[mw[mi][i]][i];
                   3303:        s2=s[mw[mi+1][i]][i];
                   3304:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3305:        /* bias bh is positive if real duration
                   3306:         * is higher than the multiple of stepm and negative otherwise.
                   3307:         */
                   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]));*/
                   3309:        if( s2 > nlstate){ 
                   3310:          /* i.e. if s2 is a death state and if the date of death is known 
                   3311:             then the contribution to the likelihood is the probability to 
                   3312:             die between last step unit time and current  step unit time, 
                   3313:             which is also equal to probability to die before dh 
                   3314:             minus probability to die before dh-stepm . 
                   3315:             In version up to 0.92 likelihood was computed
                   3316:             as if date of death was unknown. Death was treated as any other
                   3317:             health state: the date of the interview describes the actual state
                   3318:             and not the date of a change in health state. The former idea was
                   3319:             to consider that at each interview the state was recorded
                   3320:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3321:             introduced the exact date of death then we should have modified
                   3322:             the contribution of an exact death to the likelihood. This new
                   3323:             contribution is smaller and very dependent of the step unit
                   3324:             stepm. It is no more the probability to die between last interview
                   3325:             and month of death but the probability to survive from last
                   3326:             interview up to one month before death multiplied by the
                   3327:             probability to die within a month. Thanks to Chris
                   3328:             Jackson for correcting this bug.  Former versions increased
                   3329:             mortality artificially. The bad side is that we add another loop
                   3330:             which slows down the processing. The difference can be up to 10%
                   3331:             lower mortality.
                   3332:          */
                   3333:          /* If, at the beginning of the maximization mostly, the
                   3334:             cumulative probability or probability to be dead is
                   3335:             constant (ie = 1) over time d, the difference is equal to
                   3336:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3337:             s1 at precedent wave, to be dead a month before current
                   3338:             wave is equal to probability, being at state s1 at
                   3339:             precedent wave, to be dead at mont of the current
                   3340:             wave. Then the observed probability (that this person died)
                   3341:             is null according to current estimated parameter. In fact,
                   3342:             it should be very low but not zero otherwise the log go to
                   3343:             infinity.
                   3344:          */
1.183     brouard  3345: /* #ifdef INFINITYORIGINAL */
                   3346: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3347: /* #else */
                   3348: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3349: /*         lli=log(mytinydouble); */
                   3350: /*       else */
                   3351: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3352: /* #endif */
1.226     brouard  3353:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3354:          
1.226     brouard  3355:        } else if  ( s2==-1 ) { /* alive */
                   3356:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3357:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3358:          /*survp += out[s1][j]; */
                   3359:          lli= log(survp);
                   3360:        }
                   3361:        else if  (s2==-4) { 
                   3362:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3363:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3364:          lli= log(survp); 
                   3365:        } 
                   3366:        else if  (s2==-5) { 
                   3367:          for (j=1,survp=0. ; j<=2; j++)  
                   3368:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3369:          lli= log(survp); 
                   3370:        } 
                   3371:        else{
                   3372:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3373:          /*  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 */
                   3374:        } 
                   3375:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3376:        /*if(lli ==000.0)*/
                   3377:        /*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); */
                   3378:        ipmx +=1;
                   3379:        sw += weight[i];
                   3380:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3381:        /* if (lli < log(mytinydouble)){ */
                   3382:        /*   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); */
                   3383:        /*   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]); */
                   3384:        /* } */
                   3385:       } /* end of wave */
                   3386:     } /* end of individual */
                   3387:   }  else if(mle==2){
                   3388:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3389:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3390:       for(mi=1; mi<= wav[i]-1; mi++){
                   3391:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3392:          for (j=1;j<=nlstate+ndeath;j++){
                   3393:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3394:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3395:          }
                   3396:        for(d=0; d<=dh[mi][i]; d++){
                   3397:          newm=savm;
                   3398:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3399:          cov[2]=agexact;
                   3400:          if(nagesqr==1)
                   3401:            cov[3]= agexact*agexact;
                   3402:          for (kk=1; kk<=cptcovage;kk++) {
                   3403:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3404:          }
                   3405:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3406:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3407:          savm=oldm;
                   3408:          oldm=newm;
                   3409:        } /* end mult */
                   3410:       
                   3411:        s1=s[mw[mi][i]][i];
                   3412:        s2=s[mw[mi+1][i]][i];
                   3413:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3414:        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 */
                   3415:        ipmx +=1;
                   3416:        sw += weight[i];
                   3417:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3418:       } /* end of wave */
                   3419:     } /* end of individual */
                   3420:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3421:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3422:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3423:       for(mi=1; mi<= wav[i]-1; mi++){
                   3424:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3425:          for (j=1;j<=nlstate+ndeath;j++){
                   3426:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3427:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3428:          }
                   3429:        for(d=0; d<dh[mi][i]; d++){
                   3430:          newm=savm;
                   3431:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3432:          cov[2]=agexact;
                   3433:          if(nagesqr==1)
                   3434:            cov[3]= agexact*agexact;
                   3435:          for (kk=1; kk<=cptcovage;kk++) {
                   3436:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3437:          }
                   3438:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3439:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3440:          savm=oldm;
                   3441:          oldm=newm;
                   3442:        } /* end mult */
                   3443:       
                   3444:        s1=s[mw[mi][i]][i];
                   3445:        s2=s[mw[mi+1][i]][i];
                   3446:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3447:        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 */
                   3448:        ipmx +=1;
                   3449:        sw += weight[i];
                   3450:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3451:       } /* end of wave */
                   3452:     } /* end of individual */
                   3453:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3454:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3455:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3456:       for(mi=1; mi<= wav[i]-1; mi++){
                   3457:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3458:          for (j=1;j<=nlstate+ndeath;j++){
                   3459:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3460:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3461:          }
                   3462:        for(d=0; d<dh[mi][i]; d++){
                   3463:          newm=savm;
                   3464:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3465:          cov[2]=agexact;
                   3466:          if(nagesqr==1)
                   3467:            cov[3]= agexact*agexact;
                   3468:          for (kk=1; kk<=cptcovage;kk++) {
                   3469:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3470:          }
1.126     brouard  3471:        
1.226     brouard  3472:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3473:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3474:          savm=oldm;
                   3475:          oldm=newm;
                   3476:        } /* end mult */
                   3477:       
                   3478:        s1=s[mw[mi][i]][i];
                   3479:        s2=s[mw[mi+1][i]][i];
                   3480:        if( s2 > nlstate){ 
                   3481:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3482:        } else if  ( s2==-1 ) { /* alive */
                   3483:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3484:            survp += out[s1][j];
                   3485:          lli= log(survp);
                   3486:        }else{
                   3487:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3488:        }
                   3489:        ipmx +=1;
                   3490:        sw += weight[i];
                   3491:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3492: /*     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  3493:       } /* end of wave */
                   3494:     } /* end of individual */
                   3495:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3496:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3497:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3498:       for(mi=1; mi<= wav[i]-1; mi++){
                   3499:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3500:          for (j=1;j<=nlstate+ndeath;j++){
                   3501:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3502:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3503:          }
                   3504:        for(d=0; d<dh[mi][i]; d++){
                   3505:          newm=savm;
                   3506:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3507:          cov[2]=agexact;
                   3508:          if(nagesqr==1)
                   3509:            cov[3]= agexact*agexact;
                   3510:          for (kk=1; kk<=cptcovage;kk++) {
                   3511:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3512:          }
1.126     brouard  3513:        
1.226     brouard  3514:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3515:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3516:          savm=oldm;
                   3517:          oldm=newm;
                   3518:        } /* end mult */
                   3519:       
                   3520:        s1=s[mw[mi][i]][i];
                   3521:        s2=s[mw[mi+1][i]][i];
                   3522:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3523:        ipmx +=1;
                   3524:        sw += weight[i];
                   3525:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3526:        /*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]);*/
                   3527:       } /* end of wave */
                   3528:     } /* end of individual */
                   3529:   } /* End of if */
                   3530:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3531:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3532:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3533:   return -l;
1.126     brouard  3534: }
                   3535: 
                   3536: /*************** log-likelihood *************/
                   3537: double funcone( double *x)
                   3538: {
1.228     brouard  3539:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3540:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3541:   int ioffset=0;
1.131     brouard  3542:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3543:   double **out;
                   3544:   double lli; /* Individual log likelihood */
                   3545:   double llt;
                   3546:   int s1, s2;
1.228     brouard  3547:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3548: 
1.126     brouard  3549:   double bbh, survp;
1.187     brouard  3550:   double agexact;
1.214     brouard  3551:   double agebegin, ageend;
1.126     brouard  3552:   /*extern weight */
                   3553:   /* We are differentiating ll according to initial status */
                   3554:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3555:   /*for(i=1;i<imx;i++) 
                   3556:     printf(" %d\n",s[4][i]);
                   3557:   */
                   3558:   cov[1]=1.;
                   3559: 
                   3560:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3561:   ioffset=0;
                   3562:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3563:     /* ioffset=2+nagesqr+cptcovage; */
                   3564:     ioffset=2+nagesqr;
1.232     brouard  3565:     /* Fixed */
1.224     brouard  3566:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3567:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3568:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3569:       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)*/
                   3570: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3571: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3572: /*    cov[2+6]=covar[2][i]; V2  */
                   3573: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3574: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3575: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3576: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3577: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3578: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3579:     }
1.232     brouard  3580:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3581:     /*   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?)*\/ */
                   3582:     /* } */
1.231     brouard  3583:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3584:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3585:     /* } */
1.225     brouard  3586:     
1.233     brouard  3587: 
                   3588:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3589:     /* Wave varying (but not age varying) */
                   3590:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3591:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3592:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3593:       }
1.232     brouard  3594:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3595:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3596:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3597:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3598:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3599:       /* 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  3600:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3601:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3602:       /*       /\* 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]); *\/ */
                   3603:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3604:       /* } */
1.126     brouard  3605:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3606:        for (j=1;j<=nlstate+ndeath;j++){
                   3607:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3608:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3609:        }
1.214     brouard  3610:       
                   3611:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3612:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3613:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3614:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3615:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3616:          and mw[mi+1][i]. dh depends on stepm.*/
                   3617:        newm=savm;
1.247     brouard  3618:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3619:        cov[2]=agexact;
                   3620:        if(nagesqr==1)
                   3621:          cov[3]= agexact*agexact;
                   3622:        for (kk=1; kk<=cptcovage;kk++) {
                   3623:          if(!FixedV[Tvar[Tage[kk]]])
                   3624:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3625:          else
                   3626:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3627:        }
                   3628:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3629:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3630:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3631:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3632:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3633:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3634:        savm=oldm;
                   3635:        oldm=newm;
1.126     brouard  3636:       } /* end mult */
                   3637:       
                   3638:       s1=s[mw[mi][i]][i];
                   3639:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3640:       /* if(s2==-1){ */
                   3641:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3642:       /*       /\* exit(1); *\/ */
                   3643:       /* } */
1.126     brouard  3644:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3645:       /* bias is positive if real duration
                   3646:        * is higher than the multiple of stepm and negative otherwise.
                   3647:        */
                   3648:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3649:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3650:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3651:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3652:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3653:        lli= log(survp);
1.126     brouard  3654:       }else if (mle==1){
1.242     brouard  3655:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3656:       } else if(mle==2){
1.242     brouard  3657:        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  3658:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3659:        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  3660:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3661:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3662:       } else{  /* mle=0 back to 1 */
1.242     brouard  3663:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3664:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3665:       } /* End of if */
                   3666:       ipmx +=1;
                   3667:       sw += weight[i];
                   3668:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3669:       /*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  3670:       if(globpr){
1.246     brouard  3671:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3672:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3673:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3674:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3675:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3676:          llt +=ll[k]*gipmx/gsw;
                   3677:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3678:        }
                   3679:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3680:       }
1.232     brouard  3681:        } /* end of wave */
                   3682: } /* end of individual */
                   3683: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3684: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3685: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3686: if(globpr==0){ /* First time we count the contributions and weights */
                   3687:        gipmx=ipmx;
                   3688:        gsw=sw;
                   3689: }
                   3690: return -l;
1.126     brouard  3691: }
                   3692: 
                   3693: 
                   3694: /*************** function likelione ***********/
                   3695: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3696: {
                   3697:   /* This routine should help understanding what is done with 
                   3698:      the selection of individuals/waves and
                   3699:      to check the exact contribution to the likelihood.
                   3700:      Plotting could be done.
                   3701:    */
                   3702:   int k;
                   3703: 
                   3704:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3705:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3706:     strcat(fileresilk,fileresu);
1.126     brouard  3707:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3708:       printf("Problem with resultfile: %s\n", fileresilk);
                   3709:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3710:     }
1.214     brouard  3711:     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");
                   3712:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3713:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3714:     for(k=1; k<=nlstate; k++) 
                   3715:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3716:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3717:   }
                   3718: 
                   3719:   *fretone=(*funcone)(p);
                   3720:   if(*globpri !=0){
                   3721:     fclose(ficresilk);
1.205     brouard  3722:     if (mle ==0)
                   3723:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3724:     else if(mle >=1)
                   3725:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3726:     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  3727:     
1.208     brouard  3728:       
                   3729:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3730:       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  3731: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3732:     }
1.207     brouard  3733:     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  3734: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3735:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3736: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3737:     fflush(fichtm);
1.205     brouard  3738:   }
1.126     brouard  3739:   return;
                   3740: }
                   3741: 
                   3742: 
                   3743: /*********** Maximum Likelihood Estimation ***************/
                   3744: 
                   3745: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3746: {
1.165     brouard  3747:   int i,j, iter=0;
1.126     brouard  3748:   double **xi;
                   3749:   double fret;
                   3750:   double fretone; /* Only one call to likelihood */
                   3751:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3752: 
                   3753: #ifdef NLOPT
                   3754:   int creturn;
                   3755:   nlopt_opt opt;
                   3756:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3757:   double *lb;
                   3758:   double minf; /* the minimum objective value, upon return */
                   3759:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3760:   myfunc_data dinst, *d = &dinst;
                   3761: #endif
                   3762: 
                   3763: 
1.126     brouard  3764:   xi=matrix(1,npar,1,npar);
                   3765:   for (i=1;i<=npar;i++)
                   3766:     for (j=1;j<=npar;j++)
                   3767:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3768:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3769:   strcpy(filerespow,"POW_"); 
1.126     brouard  3770:   strcat(filerespow,fileres);
                   3771:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3772:     printf("Problem with resultfile: %s\n", filerespow);
                   3773:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3774:   }
                   3775:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3776:   for (i=1;i<=nlstate;i++)
                   3777:     for(j=1;j<=nlstate+ndeath;j++)
                   3778:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3779:   fprintf(ficrespow,"\n");
1.162     brouard  3780: #ifdef POWELL
1.126     brouard  3781:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3782: #endif
1.126     brouard  3783: 
1.162     brouard  3784: #ifdef NLOPT
                   3785: #ifdef NEWUOA
                   3786:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3787: #else
                   3788:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3789: #endif
                   3790:   lb=vector(0,npar-1);
                   3791:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3792:   nlopt_set_lower_bounds(opt, lb);
                   3793:   nlopt_set_initial_step1(opt, 0.1);
                   3794:   
                   3795:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3796:   d->function = func;
                   3797:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3798:   nlopt_set_min_objective(opt, myfunc, d);
                   3799:   nlopt_set_xtol_rel(opt, ftol);
                   3800:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3801:     printf("nlopt failed! %d\n",creturn); 
                   3802:   }
                   3803:   else {
                   3804:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3805:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3806:     iter=1; /* not equal */
                   3807:   }
                   3808:   nlopt_destroy(opt);
                   3809: #endif
1.126     brouard  3810:   free_matrix(xi,1,npar,1,npar);
                   3811:   fclose(ficrespow);
1.203     brouard  3812:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3813:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3814:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3815: 
                   3816: }
                   3817: 
                   3818: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3819: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3820: {
                   3821:   double  **a,**y,*x,pd;
1.203     brouard  3822:   /* double **hess; */
1.164     brouard  3823:   int i, j;
1.126     brouard  3824:   int *indx;
                   3825: 
                   3826:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3827:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3828:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3829:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3830:   double gompertz(double p[]);
1.203     brouard  3831:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3832: 
                   3833:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3834:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3835:   for (i=1;i<=npar;i++){
1.203     brouard  3836:     printf("%d-",i);fflush(stdout);
                   3837:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3838:    
                   3839:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3840:     
                   3841:     /*  printf(" %f ",p[i]);
                   3842:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3843:   }
                   3844:   
                   3845:   for (i=1;i<=npar;i++) {
                   3846:     for (j=1;j<=npar;j++)  {
                   3847:       if (j>i) { 
1.203     brouard  3848:        printf(".%d-%d",i,j);fflush(stdout);
                   3849:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3850:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3851:        
                   3852:        hess[j][i]=hess[i][j];    
                   3853:        /*printf(" %lf ",hess[i][j]);*/
                   3854:       }
                   3855:     }
                   3856:   }
                   3857:   printf("\n");
                   3858:   fprintf(ficlog,"\n");
                   3859: 
                   3860:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3861:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3862:   
                   3863:   a=matrix(1,npar,1,npar);
                   3864:   y=matrix(1,npar,1,npar);
                   3865:   x=vector(1,npar);
                   3866:   indx=ivector(1,npar);
                   3867:   for (i=1;i<=npar;i++)
                   3868:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3869:   ludcmp(a,npar,indx,&pd);
                   3870: 
                   3871:   for (j=1;j<=npar;j++) {
                   3872:     for (i=1;i<=npar;i++) x[i]=0;
                   3873:     x[j]=1;
                   3874:     lubksb(a,npar,indx,x);
                   3875:     for (i=1;i<=npar;i++){ 
                   3876:       matcov[i][j]=x[i];
                   3877:     }
                   3878:   }
                   3879: 
                   3880:   printf("\n#Hessian matrix#\n");
                   3881:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3882:   for (i=1;i<=npar;i++) { 
                   3883:     for (j=1;j<=npar;j++) { 
1.203     brouard  3884:       printf("%.6e ",hess[i][j]);
                   3885:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3886:     }
                   3887:     printf("\n");
                   3888:     fprintf(ficlog,"\n");
                   3889:   }
                   3890: 
1.203     brouard  3891:   /* printf("\n#Covariance matrix#\n"); */
                   3892:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3893:   /* for (i=1;i<=npar;i++) {  */
                   3894:   /*   for (j=1;j<=npar;j++) {  */
                   3895:   /*     printf("%.6e ",matcov[i][j]); */
                   3896:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3897:   /*   } */
                   3898:   /*   printf("\n"); */
                   3899:   /*   fprintf(ficlog,"\n"); */
                   3900:   /* } */
                   3901: 
1.126     brouard  3902:   /* Recompute Inverse */
1.203     brouard  3903:   /* for (i=1;i<=npar;i++) */
                   3904:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3905:   /* ludcmp(a,npar,indx,&pd); */
                   3906: 
                   3907:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3908: 
                   3909:   /* for (j=1;j<=npar;j++) { */
                   3910:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3911:   /*   x[j]=1; */
                   3912:   /*   lubksb(a,npar,indx,x); */
                   3913:   /*   for (i=1;i<=npar;i++){  */
                   3914:   /*     y[i][j]=x[i]; */
                   3915:   /*     printf("%.3e ",y[i][j]); */
                   3916:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3917:   /*   } */
                   3918:   /*   printf("\n"); */
                   3919:   /*   fprintf(ficlog,"\n"); */
                   3920:   /* } */
                   3921: 
                   3922:   /* Verifying the inverse matrix */
                   3923: #ifdef DEBUGHESS
                   3924:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3925: 
1.203     brouard  3926:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3927:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3928: 
                   3929:   for (j=1;j<=npar;j++) {
                   3930:     for (i=1;i<=npar;i++){ 
1.203     brouard  3931:       printf("%.2f ",y[i][j]);
                   3932:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3933:     }
                   3934:     printf("\n");
                   3935:     fprintf(ficlog,"\n");
                   3936:   }
1.203     brouard  3937: #endif
1.126     brouard  3938: 
                   3939:   free_matrix(a,1,npar,1,npar);
                   3940:   free_matrix(y,1,npar,1,npar);
                   3941:   free_vector(x,1,npar);
                   3942:   free_ivector(indx,1,npar);
1.203     brouard  3943:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3944: 
                   3945: 
                   3946: }
                   3947: 
                   3948: /*************** hessian matrix ****************/
                   3949: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3950: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3951:   int i;
                   3952:   int l=1, lmax=20;
1.203     brouard  3953:   double k1,k2, res, fx;
1.132     brouard  3954:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3955:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3956:   int k=0,kmax=10;
                   3957:   double l1;
                   3958: 
                   3959:   fx=func(x);
                   3960:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3961:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3962:     l1=pow(10,l);
                   3963:     delts=delt;
                   3964:     for(k=1 ; k <kmax; k=k+1){
                   3965:       delt = delta*(l1*k);
                   3966:       p2[theta]=x[theta] +delt;
1.145     brouard  3967:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3968:       p2[theta]=x[theta]-delt;
                   3969:       k2=func(p2)-fx;
                   3970:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3971:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3972:       
1.203     brouard  3973: #ifdef DEBUGHESSII
1.126     brouard  3974:       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);
                   3975:       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);
                   3976: #endif
                   3977:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3978:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3979:        k=kmax;
                   3980:       }
                   3981:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3982:        k=kmax; l=lmax*10;
1.126     brouard  3983:       }
                   3984:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3985:        delts=delt;
                   3986:       }
1.203     brouard  3987:     } /* End loop k */
1.126     brouard  3988:   }
                   3989:   delti[theta]=delts;
                   3990:   return res; 
                   3991:   
                   3992: }
                   3993: 
1.203     brouard  3994: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3995: {
                   3996:   int i;
1.164     brouard  3997:   int l=1, lmax=20;
1.126     brouard  3998:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3999:   double p2[MAXPARM+1];
1.203     brouard  4000:   int k, kmax=1;
                   4001:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4002: 
                   4003:   int firstime=0;
1.203     brouard  4004:   
1.126     brouard  4005:   fx=func(x);
1.203     brouard  4006:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4007:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4008:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4009:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4010:     k1=func(p2)-fx;
                   4011:   
1.203     brouard  4012:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4013:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4014:     k2=func(p2)-fx;
                   4015:   
1.203     brouard  4016:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4017:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4018:     k3=func(p2)-fx;
                   4019:   
1.203     brouard  4020:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4021:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4022:     k4=func(p2)-fx;
1.203     brouard  4023:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4024:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4025:       firstime=1;
1.203     brouard  4026:       kmax=kmax+10;
1.208     brouard  4027:     }
                   4028:     if(kmax >=10 || firstime ==1){
1.246     brouard  4029:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
                   4030:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  4031:       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);
                   4032:       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);
                   4033:     }
                   4034: #ifdef DEBUGHESSIJ
                   4035:     v1=hess[thetai][thetai];
                   4036:     v2=hess[thetaj][thetaj];
                   4037:     cv12=res;
                   4038:     /* Computing eigen value of Hessian matrix */
                   4039:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4040:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4041:     if ((lc2 <0) || (lc1 <0) ){
                   4042:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4043:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4044:       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);
                   4045:       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);
                   4046:     }
1.126     brouard  4047: #endif
                   4048:   }
                   4049:   return res;
                   4050: }
                   4051: 
1.203     brouard  4052:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4053: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4054: /* { */
                   4055: /*   int i; */
                   4056: /*   int l=1, lmax=20; */
                   4057: /*   double k1,k2,k3,k4,res,fx; */
                   4058: /*   double p2[MAXPARM+1]; */
                   4059: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4060: /*   int k=0,kmax=10; */
                   4061: /*   double l1; */
                   4062:   
                   4063: /*   fx=func(x); */
                   4064: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4065: /*     l1=pow(10,l); */
                   4066: /*     delts=delt; */
                   4067: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4068: /*       delt = delti*(l1*k); */
                   4069: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4070: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4071: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4072: /*       k1=func(p2)-fx; */
                   4073:       
                   4074: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4075: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4076: /*       k2=func(p2)-fx; */
                   4077:       
                   4078: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4079: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4080: /*       k3=func(p2)-fx; */
                   4081:       
                   4082: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4083: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4084: /*       k4=func(p2)-fx; */
                   4085: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4086: /* #ifdef DEBUGHESSIJ */
                   4087: /*       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); */
                   4088: /*       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); */
                   4089: /* #endif */
                   4090: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4091: /*     k=kmax; */
                   4092: /*       } */
                   4093: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4094: /*     k=kmax; l=lmax*10; */
                   4095: /*       } */
                   4096: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4097: /*     delts=delt; */
                   4098: /*       } */
                   4099: /*     } /\* End loop k *\/ */
                   4100: /*   } */
                   4101: /*   delti[theta]=delts; */
                   4102: /*   return res;  */
                   4103: /* } */
                   4104: 
                   4105: 
1.126     brouard  4106: /************** Inverse of matrix **************/
                   4107: void ludcmp(double **a, int n, int *indx, double *d) 
                   4108: { 
                   4109:   int i,imax,j,k; 
                   4110:   double big,dum,sum,temp; 
                   4111:   double *vv; 
                   4112:  
                   4113:   vv=vector(1,n); 
                   4114:   *d=1.0; 
                   4115:   for (i=1;i<=n;i++) { 
                   4116:     big=0.0; 
                   4117:     for (j=1;j<=n;j++) 
                   4118:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   4119:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   4120:     vv[i]=1.0/big; 
                   4121:   } 
                   4122:   for (j=1;j<=n;j++) { 
                   4123:     for (i=1;i<j;i++) { 
                   4124:       sum=a[i][j]; 
                   4125:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4126:       a[i][j]=sum; 
                   4127:     } 
                   4128:     big=0.0; 
                   4129:     for (i=j;i<=n;i++) { 
                   4130:       sum=a[i][j]; 
                   4131:       for (k=1;k<j;k++) 
                   4132:        sum -= a[i][k]*a[k][j]; 
                   4133:       a[i][j]=sum; 
                   4134:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4135:        big=dum; 
                   4136:        imax=i; 
                   4137:       } 
                   4138:     } 
                   4139:     if (j != imax) { 
                   4140:       for (k=1;k<=n;k++) { 
                   4141:        dum=a[imax][k]; 
                   4142:        a[imax][k]=a[j][k]; 
                   4143:        a[j][k]=dum; 
                   4144:       } 
                   4145:       *d = -(*d); 
                   4146:       vv[imax]=vv[j]; 
                   4147:     } 
                   4148:     indx[j]=imax; 
                   4149:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4150:     if (j != n) { 
                   4151:       dum=1.0/(a[j][j]); 
                   4152:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4153:     } 
                   4154:   } 
                   4155:   free_vector(vv,1,n);  /* Doesn't work */
                   4156: ;
                   4157: } 
                   4158: 
                   4159: void lubksb(double **a, int n, int *indx, double b[]) 
                   4160: { 
                   4161:   int i,ii=0,ip,j; 
                   4162:   double sum; 
                   4163:  
                   4164:   for (i=1;i<=n;i++) { 
                   4165:     ip=indx[i]; 
                   4166:     sum=b[ip]; 
                   4167:     b[ip]=b[i]; 
                   4168:     if (ii) 
                   4169:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4170:     else if (sum) ii=i; 
                   4171:     b[i]=sum; 
                   4172:   } 
                   4173:   for (i=n;i>=1;i--) { 
                   4174:     sum=b[i]; 
                   4175:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4176:     b[i]=sum/a[i][i]; 
                   4177:   } 
                   4178: } 
                   4179: 
                   4180: void pstamp(FILE *fichier)
                   4181: {
1.196     brouard  4182:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4183: }
                   4184: 
                   4185: /************ Frequencies ********************/
1.250   ! brouard  4186: void  freqsummary(char fileres[], double p[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4187:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4188:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250   ! brouard  4189: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4190:   
1.250   ! brouard  4191:   int i, m, jk, j1, bool, z1,j, k, iv, jj=0;
1.226     brouard  4192:   int iind=0, iage=0;
                   4193:   int mi; /* Effective wave */
                   4194:   int first;
                   4195:   double ***freq; /* Frequencies */
                   4196:   double *meanq;
                   4197:   double **meanqt;
                   4198:   double *pp, **prop, *posprop, *pospropt;
                   4199:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4200:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4201:   double agebegin, ageend;
                   4202:     
                   4203:   pp=vector(1,nlstate);
                   4204:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4205:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4206:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4207:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4208:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4209:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4210:   strcpy(fileresp,"P_");
                   4211:   strcat(fileresp,fileresu);
                   4212:   /*strcat(fileresphtm,fileresu);*/
                   4213:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4214:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4215:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4216:     exit(0);
                   4217:   }
1.240     brouard  4218:   
1.226     brouard  4219:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4220:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4221:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4222:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4223:     fflush(ficlog);
                   4224:     exit(70); 
                   4225:   }
                   4226:   else{
                   4227:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4228: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4229: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4230:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4231:   }
1.237     brouard  4232:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
1.240     brouard  4233:   
1.226     brouard  4234:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4235:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4236:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4237:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4238:     fflush(ficlog);
                   4239:     exit(70); 
1.240     brouard  4240:   } else{
1.226     brouard  4241:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4242: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4243: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4244:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4245:   }
1.240     brouard  4246:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions of the model, by age at begin of transition, and covariate value at the begin of transition (if the covariate is a varying covariate) </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
                   4247:   
1.226     brouard  4248:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4249:   j1=0;
1.126     brouard  4250:   
1.227     brouard  4251:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4252:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4253:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4254:   
                   4255:   
1.226     brouard  4256:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4257:      reference=low_education V1=0,V2=0
                   4258:      med_educ                V1=1 V2=0, 
                   4259:      high_educ               V1=0 V2=1
                   4260:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4261:   */
1.249     brouard  4262:   dateintsum=0;
                   4263:   k2cpt=0;
                   4264: 
                   4265:   for (j = 0; j <= cptcoveff; j+=cptcoveff){   
                   4266:   first=1;
1.227     brouard  4267:   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  4268:     posproptt=0.;
                   4269:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4270:       scanf("%d", i);*/
                   4271:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4272:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.240     brouard  4273:        for(m=iagemin; m <= iagemax+3; m++)
                   4274:          freq[i][jk][m]=0;
                   4275:     
1.226     brouard  4276:     for (i=1; i<=nlstate; i++)  {
                   4277:       for(m=iagemin; m <= iagemax+3; m++)
1.240     brouard  4278:        prop[i][m]=0;
1.226     brouard  4279:       posprop[i]=0;
                   4280:       pospropt[i]=0;
                   4281:     }
1.227     brouard  4282:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4283:     /*   meanq[z1]+=0.; */
                   4284:     /*   for(m=1;m<=lastpass;m++){ */
                   4285:     /*         meanqt[m][z1]=0.; */
                   4286:     /*   } */
                   4287:     /* } */
1.240     brouard  4288:     
1.249     brouard  4289:     /* dateintsum=0; */
                   4290:     /* k2cpt=0; */
                   4291: 
1.227     brouard  4292:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4293:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4294:       bool=1;
1.249     brouard  4295:       if(j !=0){
1.227     brouard  4296:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4297:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4298:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4299:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4300:          /* } */
1.250   ! brouard  4301:          for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.234     brouard  4302:            /* if(Tvaraff[z1] ==-20){ */
                   4303:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4304:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4305:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4306:            /* }else  */
1.250   ! brouard  4307:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
        !          4308:              /* Tests if this individual iind responded to combination j1 (V4=1 V3=0) */
        !          4309:              bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.234     brouard  4310:              /* 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", 
                   4311:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4312:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4313:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4314:            } /* Onlyf fixed */
                   4315:          } /* end z1 */
                   4316:        } /* cptcovn > 0 */
1.227     brouard  4317:       } /* end any */
1.249     brouard  4318:       }/* end j==0 */
1.227     brouard  4319:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4320:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4321:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4322:          m=mw[mi][iind];
1.249     brouard  4323:          if(j!=0){
1.234     brouard  4324:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4325:            for (z1=1; z1<=cptcoveff; z1++) {
                   4326:              if( Fixed[Tmodelind[z1]]==1){
                   4327:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.250   ! brouard  4328:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
        !          4329:                                                                                  value is -1, we don't select. It differs from the 
        !          4330:                                                                                  constant and age model which counts them. */
1.249     brouard  4331:                  bool=0; /* not selected */
1.234     brouard  4332:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4333:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4334:                  bool=0;
                   4335:                }
                   4336:              }
                   4337:            }
                   4338:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
1.249     brouard  4339:          } /* end j==0 */
1.234     brouard  4340:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4341:          if(bool==1){
                   4342:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4343:               and mw[mi+1][iind]. dh depends on stepm. */
                   4344:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4345:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4346:            if(m >=firstpass && m <=lastpass){
                   4347:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4348:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4349:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4350:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4351:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4352:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4353:              if (m<lastpass) {
                   4354:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4355:                /*   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]); */
                   4356:                if(s[m][iind]==-1)
                   4357:                  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.));
                   4358:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
1.250   ! brouard  4359:                /* if((int)agev[m][iind] == 55) */
        !          4360:                /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
1.234     brouard  4361:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4362:                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 */
                   4363:              }
                   4364:            } /* end if between passes */  
1.249     brouard  4365:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4366:              dateintsum=dateintsum+k2; /* on all covariates ?*/
1.234     brouard  4367:              k2cpt++;
                   4368:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4369:            }
1.250   ! brouard  4370:          }else{
        !          4371:            bool=1;
        !          4372:          }/* end bool 2 */
1.234     brouard  4373:        } /* end m */
1.226     brouard  4374:       } /* end bool */
                   4375:     } /* end iind = 1 to imx */
                   4376:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4377:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.240     brouard  4378:     
                   4379:     
1.226     brouard  4380:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4381:     pstamp(ficresp);
1.249     brouard  4382:     if  (cptcoveff>0 && j!=0){
1.226     brouard  4383:       fprintf(ficresp, "\n#********** Variable "); 
                   4384:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4385:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.240     brouard  4386:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4387:       for (z1=1; z1<=cptcoveff; z1++){
1.240     brouard  4388:        if(DummyV[z1]){
                   4389:          fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4390:          fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4391:          fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4392:          fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4393:        }else{
                   4394:          fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4395:          fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4396:          fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4397:          fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4398:        }
1.226     brouard  4399:       }
                   4400:       fprintf(ficresp, "**********\n#");
                   4401:       fprintf(ficresphtm, "**********</h3>\n");
                   4402:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4403:       fprintf(ficlog, "**********\n");
                   4404:     }
                   4405:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4406:     for(i=1; i<=nlstate;i++) {
1.240     brouard  4407:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
1.226     brouard  4408:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4409:     }
                   4410:     fprintf(ficresp, "\n");
                   4411:     fprintf(ficresphtm, "\n");
1.240     brouard  4412:     
1.226     brouard  4413:     /* Header of frequency table by age */
                   4414:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4415:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4416:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4417:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4418:        if(jk!=0 && m!=0)
                   4419:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4420:       }
                   4421:     }
                   4422:     fprintf(ficresphtmfr, "\n");
1.240     brouard  4423:     
1.226     brouard  4424:     /* For each age */
                   4425:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4426:       fprintf(ficresphtm,"<tr>");
                   4427:       if(iage==iagemax+1){
1.240     brouard  4428:        fprintf(ficlog,"1");
                   4429:        fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4430:       }else if(iage==iagemax+2){
1.240     brouard  4431:        fprintf(ficlog,"0");
                   4432:        fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4433:       }else if(iage==iagemax+3){
1.240     brouard  4434:        fprintf(ficlog,"Total");
                   4435:        fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4436:       }else{
1.240     brouard  4437:        if(first==1){
                   4438:          first=0;
                   4439:          printf("See log file for details...\n");
                   4440:        }
                   4441:        fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4442:        fprintf(ficlog,"Age %d", iage);
1.226     brouard  4443:       }
                   4444:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4445:        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4446:          pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4447:       }
                   4448:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4449:        for(m=-1, pos=0; m <=0 ; m++)
                   4450:          pos += freq[jk][m][iage];
                   4451:        if(pp[jk]>=1.e-10){
                   4452:          if(first==1){
                   4453:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4454:          }
                   4455:          fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4456:        }else{
                   4457:          if(first==1)
                   4458:            printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4459:          fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4460:        }
1.226     brouard  4461:       }
1.240     brouard  4462:       
1.226     brouard  4463:       for(jk=1; jk <=nlstate ; jk++){ 
1.240     brouard  4464:        /* posprop[jk]=0; */
                   4465:        for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4466:          pp[jk] += freq[jk][m][iage];
1.226     brouard  4467:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.240     brouard  4468:       
1.226     brouard  4469:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.240     brouard  4470:        pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4471:        posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4472:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4473:        pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4474:                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4475:       }
                   4476:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4477:        if(pos>=1.e-5){
                   4478:          if(first==1)
                   4479:            printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4480:          fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4481:        }else{
                   4482:          if(first==1)
                   4483:            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4484:          fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4485:        }
                   4486:        if( iage <= iagemax){
                   4487:          if(pos>=1.e-5){
                   4488:            fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4489:            fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4490:            /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4491:            /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4492:          }
                   4493:          else{
                   4494:            fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4495:            fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4496:          }
                   4497:        }
                   4498:        pospropt[jk] +=posprop[jk];
1.226     brouard  4499:       } /* end loop jk */
                   4500:       /* pospropt=0.; */
                   4501:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.240     brouard  4502:        for(m=-1; m <=nlstate+ndeath; m++){
                   4503:          if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4504:            if(first==1){
                   4505:              printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4506:            }
                   4507:            fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4508:          }
                   4509:          if(jk!=0 && m!=0)
                   4510:            fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4511:        }
1.226     brouard  4512:       } /* end loop jk */
                   4513:       posproptt=0.; 
                   4514:       for(jk=1; jk <=nlstate; jk++){
1.240     brouard  4515:        posproptt += pospropt[jk];
1.226     brouard  4516:       }
                   4517:       fprintf(ficresphtmfr,"</tr>\n ");
                   4518:       if(iage <= iagemax){
1.240     brouard  4519:        fprintf(ficresp,"\n");
                   4520:        fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4521:       }
                   4522:       if(first==1)
1.240     brouard  4523:        printf("Others in log...\n");
1.226     brouard  4524:       fprintf(ficlog,"\n");
                   4525:     } /* end loop age iage */
                   4526:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4527:     for(jk=1; jk <=nlstate ; jk++){
                   4528:       if(posproptt < 1.e-5){
1.240     brouard  4529:        fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4530:       }else{
1.240     brouard  4531:        fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4532:       }
                   4533:     }
                   4534:     fprintf(ficresphtm,"</tr>\n");
                   4535:     fprintf(ficresphtm,"</table>\n");
                   4536:     fprintf(ficresphtmfr,"</table>\n");
                   4537:     if(posproptt < 1.e-5){
                   4538:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4539:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4540:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4541:       invalidvarcomb[j1]=1;
                   4542:     }else{
                   4543:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4544:       invalidvarcomb[j1]=0;
                   4545:     }
                   4546:     fprintf(ficresphtmfr,"</table>\n");
                   4547:   } /* end selected combination of covariate j1 */
1.249     brouard  4548:   if(j==0){ /* We can estimate starting values from the occurences in each case */
1.250   ! brouard  4549:     printf("#Freqsummary\n");
        !          4550:     fprintf(ficlog,"\n");
        !          4551:     for(i=1,jk=1; i <=nlstate; i++){
        !          4552:       for(k=1; k <=(nlstate+ndeath); k++){
        !          4553:        if (k != i) {
        !          4554:          printf("%d%d ",i,k);
        !          4555:          fprintf(ficlog,"%d%d ",i,k);
        !          4556:          for(jj=1; jj <=ncovmodel; jj++){
        !          4557:            if(jj==1){
        !          4558:              printf("%12.7f ln(%12.1f/%12.1f)= %12.7f ",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
        !          4559:              fprintf(ficlog,"%12.7f ln(%12.1f/%12.1f)= %12.7f ",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
        !          4560:            }
        !          4561:            /* printf("%12.7f )", param[i][jj][k]); */
        !          4562:            /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
        !          4563:            jk++; 
        !          4564:          }
        !          4565:          printf("\n");
        !          4566:          fprintf(ficlog,"\n");
        !          4567:        }
        !          4568:       }
        !          4569:     }
        !          4570:     printf("#Freqsummary\n");
        !          4571:     fprintf(ficlog,"\n");
1.249     brouard  4572:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4573:       for(m=-1; m <=nlstate+ndeath; m++){
                   4574:        /* param[i]|j][k]= freq[jk][m][iagemax+3] */
1.250   ! brouard  4575:          printf(" %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]);
        !          4576:          fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]);
        !          4577:        /* if(freq[jk][m][iage] !=0 ) { /\* minimizing output *\/ */
        !          4578:        /*   printf(" %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]); */
        !          4579:        /*   fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]); */
        !          4580:        /* } */
1.249     brouard  4581:       }
                   4582:     } /* end loop jk */
1.250   ! brouard  4583:     printf("\n");
        !          4584:     fprintf(ficlog,"\n");
        !          4585:   } /* if j=0 */
1.249     brouard  4586:   } /* end j */
1.226     brouard  4587:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4588:   
1.226     brouard  4589:   fclose(ficresp);
                   4590:   fclose(ficresphtm);
                   4591:   fclose(ficresphtmfr);
                   4592:   free_vector(meanq,1,nqfveff);
                   4593:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4594:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4595:   free_vector(pospropt,1,nlstate);
                   4596:   free_vector(posprop,1,nlstate);
                   4597:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4598:   free_vector(pp,1,nlstate);
                   4599:   /* End of freqsummary */
                   4600: }
1.126     brouard  4601: 
                   4602: /************ Prevalence ********************/
1.227     brouard  4603: 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)
                   4604: {  
                   4605:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4606:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4607:      We still use firstpass and lastpass as another selection.
                   4608:   */
1.126     brouard  4609:  
1.227     brouard  4610:   int i, m, jk, j1, bool, z1,j, iv;
                   4611:   int mi; /* Effective wave */
                   4612:   int iage;
                   4613:   double agebegin, ageend;
                   4614: 
                   4615:   double **prop;
                   4616:   double posprop; 
                   4617:   double  y2; /* in fractional years */
                   4618:   int iagemin, iagemax;
                   4619:   int first; /** to stop verbosity which is redirected to log file */
                   4620: 
                   4621:   iagemin= (int) agemin;
                   4622:   iagemax= (int) agemax;
                   4623:   /*pp=vector(1,nlstate);*/
                   4624:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4625:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4626:   j1=0;
1.222     brouard  4627:   
1.227     brouard  4628:   /*j=cptcoveff;*/
                   4629:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4630:   
1.227     brouard  4631:   first=1;
                   4632:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4633:     for (i=1; i<=nlstate; i++)  
                   4634:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4635:        prop[i][iage]=0.0;
                   4636:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4637:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4638:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4639:     
                   4640:     for (i=1; i<=imx; i++) { /* Each individual */
                   4641:       bool=1;
                   4642:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4643:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4644:        m=mw[mi][i];
                   4645:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4646:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4647:        for (z1=1; z1<=cptcoveff; z1++){
                   4648:          if( Fixed[Tmodelind[z1]]==1){
                   4649:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4650:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4651:              bool=0;
                   4652:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4653:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4654:              bool=0;
                   4655:            }
                   4656:        }
                   4657:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4658:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4659:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4660:          if(m >=firstpass && m <=lastpass){
                   4661:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4662:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4663:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4664:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4665:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4666:                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); 
                   4667:                exit(1);
                   4668:              }
                   4669:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4670:                /*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]]);*/
                   4671:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4672:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4673:              } /* end valid statuses */ 
                   4674:            } /* end selection of dates */
                   4675:          } /* end selection of waves */
                   4676:        } /* end bool */
                   4677:       } /* end wave */
                   4678:     } /* end individual */
                   4679:     for(i=iagemin; i <= iagemax+3; i++){  
                   4680:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4681:        posprop += prop[jk][i]; 
                   4682:       } 
                   4683:       
                   4684:       for(jk=1; jk <=nlstate ; jk++){      
                   4685:        if( i <=  iagemax){ 
                   4686:          if(posprop>=1.e-5){ 
                   4687:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4688:          } else{
                   4689:            if(first==1){
                   4690:              first=0;
                   4691:              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]);
                   4692:            }
                   4693:          }
                   4694:        } 
                   4695:       }/* end jk */ 
                   4696:     }/* end i */ 
1.222     brouard  4697:      /*} *//* end i1 */
1.227     brouard  4698:   } /* end j1 */
1.222     brouard  4699:   
1.227     brouard  4700:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4701:   /*free_vector(pp,1,nlstate);*/
                   4702:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4703: }  /* End of prevalence */
1.126     brouard  4704: 
                   4705: /************* Waves Concatenation ***************/
                   4706: 
                   4707: 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)
                   4708: {
                   4709:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4710:      Death is a valid wave (if date is known).
                   4711:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4712:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4713:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4714:   */
1.126     brouard  4715: 
1.224     brouard  4716:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4717:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4718:      double sum=0., jmean=0.;*/
1.224     brouard  4719:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4720:   int j, k=0,jk, ju, jl;
                   4721:   double sum=0.;
                   4722:   first=0;
1.214     brouard  4723:   firstwo=0;
1.217     brouard  4724:   firsthree=0;
1.218     brouard  4725:   firstfour=0;
1.164     brouard  4726:   jmin=100000;
1.126     brouard  4727:   jmax=-1;
                   4728:   jmean=0.;
1.224     brouard  4729: 
                   4730: /* Treating live states */
1.214     brouard  4731:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4732:     mi=0;  /* First valid wave */
1.227     brouard  4733:     mli=0; /* Last valid wave */
1.126     brouard  4734:     m=firstpass;
1.214     brouard  4735:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4736:       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 */
                   4737:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4738:       }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 */
                   4739:        mw[++mi][i]=m;
                   4740:        mli=m;
1.224     brouard  4741:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4742:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4743:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4744:       }
1.227     brouard  4745:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4746: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4747:        break;
1.224     brouard  4748: #else
1.227     brouard  4749:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4750:          if(firsthree == 0){
                   4751:            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);
                   4752:            firsthree=1;
                   4753:          }
                   4754:          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);
                   4755:          mw[++mi][i]=m;
                   4756:          mli=m;
                   4757:        }
                   4758:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4759:          nbwarn++;
                   4760:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4761:            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);
                   4762:            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);
                   4763:          }
                   4764:          break;
                   4765:        }
                   4766:        break;
1.224     brouard  4767: #endif
1.227     brouard  4768:       }/* End m >= lastpass */
1.126     brouard  4769:     }/* end while */
1.224     brouard  4770: 
1.227     brouard  4771:     /* 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  4772:     /* After last pass */
1.224     brouard  4773: /* Treating death states */
1.214     brouard  4774:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4775:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4776:       /* } */
1.126     brouard  4777:       mi++;    /* Death is another wave */
                   4778:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4779:       /* Only death is a correct wave */
1.126     brouard  4780:       mw[mi][i]=m;
1.224     brouard  4781:     }
                   4782: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4783:     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  4784:       /* m++; */
                   4785:       /* mi++; */
                   4786:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4787:       /* mw[mi][i]=m; */
1.218     brouard  4788:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4789:        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 */
                   4790:          nbwarn++;
                   4791:          if(firstfiv==0){
                   4792:            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 );
                   4793:            firstfiv=1;
                   4794:          }else{
                   4795:            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 );
                   4796:          }
                   4797:        }else{ /* Death occured afer last wave potential bias */
                   4798:          nberr++;
                   4799:          if(firstwo==0){
                   4800:            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 );
                   4801:            firstwo=1;
                   4802:          }
                   4803:          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 );
                   4804:        }
1.218     brouard  4805:       }else{ /* end date of interview is known */
1.227     brouard  4806:        /* death is known but not confirmed by death status at any wave */
                   4807:        if(firstfour==0){
                   4808:          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 );
                   4809:          firstfour=1;
                   4810:        }
                   4811:        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  4812:       }
1.224     brouard  4813:     } /* end if date of death is known */
                   4814: #endif
                   4815:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4816:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4817:     if(mi==0){
                   4818:       nbwarn++;
                   4819:       if(first==0){
1.227     brouard  4820:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4821:        first=1;
1.126     brouard  4822:       }
                   4823:       if(first==1){
1.227     brouard  4824:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4825:       }
                   4826:     } /* end mi==0 */
                   4827:   } /* End individuals */
1.214     brouard  4828:   /* wav and mw are no more changed */
1.223     brouard  4829:        
1.214     brouard  4830:   
1.126     brouard  4831:   for(i=1; i<=imx; i++){
                   4832:     for(mi=1; mi<wav[i];mi++){
                   4833:       if (stepm <=0)
1.227     brouard  4834:        dh[mi][i]=1;
1.126     brouard  4835:       else{
1.227     brouard  4836:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4837:          if (agedc[i] < 2*AGESUP) {
                   4838:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4839:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4840:            else if(j<0){
                   4841:              nberr++;
                   4842:              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]);
                   4843:              j=1; /* Temporary Dangerous patch */
                   4844:              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);
                   4845:              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]);
                   4846:              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);
                   4847:            }
                   4848:            k=k+1;
                   4849:            if (j >= jmax){
                   4850:              jmax=j;
                   4851:              ijmax=i;
                   4852:            }
                   4853:            if (j <= jmin){
                   4854:              jmin=j;
                   4855:              ijmin=i;
                   4856:            }
                   4857:            sum=sum+j;
                   4858:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4859:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4860:          }
                   4861:        }
                   4862:        else{
                   4863:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4864: /*       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  4865:                                        
1.227     brouard  4866:          k=k+1;
                   4867:          if (j >= jmax) {
                   4868:            jmax=j;
                   4869:            ijmax=i;
                   4870:          }
                   4871:          else if (j <= jmin){
                   4872:            jmin=j;
                   4873:            ijmin=i;
                   4874:          }
                   4875:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4876:          /*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]);*/
                   4877:          if(j<0){
                   4878:            nberr++;
                   4879:            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]);
                   4880:            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]);
                   4881:          }
                   4882:          sum=sum+j;
                   4883:        }
                   4884:        jk= j/stepm;
                   4885:        jl= j -jk*stepm;
                   4886:        ju= j -(jk+1)*stepm;
                   4887:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4888:          if(jl==0){
                   4889:            dh[mi][i]=jk;
                   4890:            bh[mi][i]=0;
                   4891:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4892:                  * to avoid the price of an extra matrix product in likelihood */
                   4893:            dh[mi][i]=jk+1;
                   4894:            bh[mi][i]=ju;
                   4895:          }
                   4896:        }else{
                   4897:          if(jl <= -ju){
                   4898:            dh[mi][i]=jk;
                   4899:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4900:                                 * is higher than the multiple of stepm and negative otherwise.
                   4901:                                 */
                   4902:          }
                   4903:          else{
                   4904:            dh[mi][i]=jk+1;
                   4905:            bh[mi][i]=ju;
                   4906:          }
                   4907:          if(dh[mi][i]==0){
                   4908:            dh[mi][i]=1; /* At least one step */
                   4909:            bh[mi][i]=ju; /* At least one step */
                   4910:            /*  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);*/
                   4911:          }
                   4912:        } /* end if mle */
1.126     brouard  4913:       }
                   4914:     } /* end wave */
                   4915:   }
                   4916:   jmean=sum/k;
                   4917:   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  4918:   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  4919: }
1.126     brouard  4920: 
                   4921: /*********** Tricode ****************************/
1.220     brouard  4922:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  4923:  {
                   4924:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4925:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   4926:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   4927:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4928:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   4929:     */
1.130     brouard  4930: 
1.242     brouard  4931:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   4932:    int modmaxcovj=0; /* Modality max of covariates j */
                   4933:    int cptcode=0; /* Modality max of covariates j */
                   4934:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  4935: 
                   4936: 
1.242     brouard  4937:    /* cptcoveff=0;  */
                   4938:    /* *cptcov=0; */
1.126     brouard  4939:  
1.242     brouard  4940:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4941: 
1.242     brouard  4942:    /* Loop on covariates without age and products and no quantitative variable */
                   4943:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
                   4944:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4945:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4946:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4947:        switch(Fixed[k]) {
                   4948:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   4949:         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*/
                   4950:           ij=(int)(covar[Tvar[k]][i]);
                   4951:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4952:            * If product of Vn*Vm, still boolean *:
                   4953:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4954:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4955:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4956:              modality of the nth covariate of individual i. */
                   4957:           if (ij > modmaxcovj)
                   4958:             modmaxcovj=ij; 
                   4959:           else if (ij < modmincovj) 
                   4960:             modmincovj=ij; 
                   4961:           if ((ij < -1) && (ij > NCOVMAX)){
                   4962:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4963:             exit(1);
                   4964:           }else
                   4965:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4966:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4967:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4968:           /* getting the maximum value of the modality of the covariate
                   4969:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4970:              female ies 1, then modmaxcovj=1.
                   4971:           */
                   4972:         } /* end for loop on individuals i */
                   4973:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4974:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4975:         cptcode=modmaxcovj;
                   4976:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4977:         /*for (i=0; i<=cptcode; i++) {*/
                   4978:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4979:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4980:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4981:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4982:             if( j != -1){
                   4983:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4984:                                  covariate for which somebody answered excluding 
                   4985:                                  undefined. Usually 2: 0 and 1. */
                   4986:             }
                   4987:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4988:                                     covariate for which somebody answered including 
                   4989:                                     undefined. Usually 3: -1, 0 and 1. */
                   4990:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4991:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4992:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  4993:                        
1.242     brouard  4994:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4995:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4996:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4997:         /* modmincovj=3; modmaxcovj = 7; */
                   4998:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4999:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5000:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5001:         /* nbcode[Tvar[j]][ij]=k; */
                   5002:         /* nbcode[Tvar[j]][1]=0; */
                   5003:         /* nbcode[Tvar[j]][2]=1; */
                   5004:         /* nbcode[Tvar[j]][3]=2; */
                   5005:         /* To be continued (not working yet). */
                   5006:         ij=0; /* ij is similar to i but can jump over null modalities */
                   5007:         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*/
                   5008:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5009:             break;
                   5010:           }
                   5011:           ij++;
                   5012:           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*/
                   5013:           cptcode = ij; /* New max modality for covar j */
                   5014:         } /* end of loop on modality i=-1 to 1 or more */
                   5015:         break;
                   5016:        case 1: /* Testing on varying covariate, could be simple and
                   5017:                * should look at waves or product of fixed *
                   5018:                * varying. No time to test -1, assuming 0 and 1 only */
                   5019:         ij=0;
                   5020:         for(i=0; i<=1;i++){
                   5021:           nbcode[Tvar[k]][++ij]=i;
                   5022:         }
                   5023:         break;
                   5024:        default:
                   5025:         break;
                   5026:        } /* end switch */
                   5027:      } /* end dummy test */
                   5028:     
                   5029:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   5030:      /*        /\*recode from 0 *\/ */
                   5031:      /*                                     k is a modality. If we have model=V1+V1*sex  */
                   5032:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   5033:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   5034:      /*        } */
                   5035:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   5036:      /*        if (ij > ncodemax[j]) { */
                   5037:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   5038:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   5039:      /*          break; */
                   5040:      /*        } */
                   5041:      /*   }  /\* end of loop on modality k *\/ */
                   5042:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   5043:   
                   5044:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5045:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5046:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5047:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5048:      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 */ 
                   5049:      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 */
                   5050:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5051:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5052:   
                   5053:    ij=0;
                   5054:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5055:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5056:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5057:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5058:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5059:        /* If product not in single variable we don't print results */
                   5060:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5061:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5062:        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*/
                   5063:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5064:        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 */
                   5065:        if(Fixed[k]!=0)
                   5066:         anyvaryingduminmodel=1;
                   5067:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5068:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5069:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5070:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5071:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5072:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5073:      } 
                   5074:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5075:    /* ij--; */
                   5076:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5077:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5078:                * because they can be excluded from the model and real
                   5079:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5080:    for(j=ij+1; j<= cptcovt; j++){
                   5081:      Tvaraff[j]=0;
                   5082:      Tmodelind[j]=0;
                   5083:    }
                   5084:    for(j=ntveff+1; j<= cptcovt; j++){
                   5085:      TmodelInvind[j]=0;
                   5086:    }
                   5087:    /* To be sorted */
                   5088:    ;
                   5089:  }
1.126     brouard  5090: 
1.145     brouard  5091: 
1.126     brouard  5092: /*********** Health Expectancies ****************/
                   5093: 
1.235     brouard  5094:  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  5095: 
                   5096: {
                   5097:   /* Health expectancies, no variances */
1.164     brouard  5098:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5099:   int nhstepma, nstepma; /* Decreasing with age */
                   5100:   double age, agelim, hf;
                   5101:   double ***p3mat;
                   5102:   double eip;
                   5103: 
1.238     brouard  5104:   /* pstamp(ficreseij); */
1.126     brouard  5105:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5106:   fprintf(ficreseij,"# Age");
                   5107:   for(i=1; i<=nlstate;i++){
                   5108:     for(j=1; j<=nlstate;j++){
                   5109:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5110:     }
                   5111:     fprintf(ficreseij," e%1d. ",i);
                   5112:   }
                   5113:   fprintf(ficreseij,"\n");
                   5114: 
                   5115:   
                   5116:   if(estepm < stepm){
                   5117:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5118:   }
                   5119:   else  hstepm=estepm;   
                   5120:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5121:    * This is mainly to measure the difference between two models: for example
                   5122:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5123:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5124:    * progression in between and thus overestimating or underestimating according
                   5125:    * to the curvature of the survival function. If, for the same date, we 
                   5126:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5127:    * to compare the new estimate of Life expectancy with the same linear 
                   5128:    * hypothesis. A more precise result, taking into account a more precise
                   5129:    * curvature will be obtained if estepm is as small as stepm. */
                   5130: 
                   5131:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5132:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5133:      nhstepm is the number of hstepm from age to agelim 
                   5134:      nstepm is the number of stepm from age to agelin. 
                   5135:      Look at hpijx to understand the reason of that which relies in memory size
                   5136:      and note for a fixed period like estepm months */
                   5137:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5138:      survival function given by stepm (the optimization length). Unfortunately it
                   5139:      means that if the survival funtion is printed only each two years of age and if
                   5140:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5141:      results. So we changed our mind and took the option of the best precision.
                   5142:   */
                   5143:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5144: 
                   5145:   agelim=AGESUP;
                   5146:   /* If stepm=6 months */
                   5147:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5148:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5149:     
                   5150: /* nhstepm age range expressed in number of stepm */
                   5151:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5152:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5153:   /* if (stepm >= YEARM) hstepm=1;*/
                   5154:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5155:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5156: 
                   5157:   for (age=bage; age<=fage; age ++){ 
                   5158:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5159:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5160:     /* if (stepm >= YEARM) hstepm=1;*/
                   5161:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5162: 
                   5163:     /* If stepm=6 months */
                   5164:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5165:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5166:     
1.235     brouard  5167:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5168:     
                   5169:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5170:     
                   5171:     printf("%d|",(int)age);fflush(stdout);
                   5172:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5173:     
                   5174:     /* Computing expectancies */
                   5175:     for(i=1; i<=nlstate;i++)
                   5176:       for(j=1; j<=nlstate;j++)
                   5177:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5178:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5179:          
                   5180:          /* 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]);*/
                   5181: 
                   5182:        }
                   5183: 
                   5184:     fprintf(ficreseij,"%3.0f",age );
                   5185:     for(i=1; i<=nlstate;i++){
                   5186:       eip=0;
                   5187:       for(j=1; j<=nlstate;j++){
                   5188:        eip +=eij[i][j][(int)age];
                   5189:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5190:       }
                   5191:       fprintf(ficreseij,"%9.4f", eip );
                   5192:     }
                   5193:     fprintf(ficreseij,"\n");
                   5194:     
                   5195:   }
                   5196:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5197:   printf("\n");
                   5198:   fprintf(ficlog,"\n");
                   5199:   
                   5200: }
                   5201: 
1.235     brouard  5202:  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  5203: 
                   5204: {
                   5205:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5206:      to initial status i, ei. .
1.126     brouard  5207:   */
                   5208:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5209:   int nhstepma, nstepma; /* Decreasing with age */
                   5210:   double age, agelim, hf;
                   5211:   double ***p3matp, ***p3matm, ***varhe;
                   5212:   double **dnewm,**doldm;
                   5213:   double *xp, *xm;
                   5214:   double **gp, **gm;
                   5215:   double ***gradg, ***trgradg;
                   5216:   int theta;
                   5217: 
                   5218:   double eip, vip;
                   5219: 
                   5220:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5221:   xp=vector(1,npar);
                   5222:   xm=vector(1,npar);
                   5223:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5224:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5225:   
                   5226:   pstamp(ficresstdeij);
                   5227:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5228:   fprintf(ficresstdeij,"# Age");
                   5229:   for(i=1; i<=nlstate;i++){
                   5230:     for(j=1; j<=nlstate;j++)
                   5231:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5232:     fprintf(ficresstdeij," e%1d. ",i);
                   5233:   }
                   5234:   fprintf(ficresstdeij,"\n");
                   5235: 
                   5236:   pstamp(ficrescveij);
                   5237:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5238:   fprintf(ficrescveij,"# Age");
                   5239:   for(i=1; i<=nlstate;i++)
                   5240:     for(j=1; j<=nlstate;j++){
                   5241:       cptj= (j-1)*nlstate+i;
                   5242:       for(i2=1; i2<=nlstate;i2++)
                   5243:        for(j2=1; j2<=nlstate;j2++){
                   5244:          cptj2= (j2-1)*nlstate+i2;
                   5245:          if(cptj2 <= cptj)
                   5246:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5247:        }
                   5248:     }
                   5249:   fprintf(ficrescveij,"\n");
                   5250:   
                   5251:   if(estepm < stepm){
                   5252:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5253:   }
                   5254:   else  hstepm=estepm;   
                   5255:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5256:    * This is mainly to measure the difference between two models: for example
                   5257:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5258:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5259:    * progression in between and thus overestimating or underestimating according
                   5260:    * to the curvature of the survival function. If, for the same date, we 
                   5261:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5262:    * to compare the new estimate of Life expectancy with the same linear 
                   5263:    * hypothesis. A more precise result, taking into account a more precise
                   5264:    * curvature will be obtained if estepm is as small as stepm. */
                   5265: 
                   5266:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5267:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5268:      nhstepm is the number of hstepm from age to agelim 
                   5269:      nstepm is the number of stepm from age to agelin. 
                   5270:      Look at hpijx to understand the reason of that which relies in memory size
                   5271:      and note for a fixed period like estepm months */
                   5272:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5273:      survival function given by stepm (the optimization length). Unfortunately it
                   5274:      means that if the survival funtion is printed only each two years of age and if
                   5275:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5276:      results. So we changed our mind and took the option of the best precision.
                   5277:   */
                   5278:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5279: 
                   5280:   /* If stepm=6 months */
                   5281:   /* nhstepm age range expressed in number of stepm */
                   5282:   agelim=AGESUP;
                   5283:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5284:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5285:   /* if (stepm >= YEARM) hstepm=1;*/
                   5286:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5287:   
                   5288:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5289:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5290:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5291:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5292:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5293:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5294: 
                   5295:   for (age=bage; age<=fage; age ++){ 
                   5296:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5297:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5298:     /* if (stepm >= YEARM) hstepm=1;*/
                   5299:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5300:                
1.126     brouard  5301:     /* If stepm=6 months */
                   5302:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5303:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5304:     
                   5305:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5306:                
1.126     brouard  5307:     /* Computing  Variances of health expectancies */
                   5308:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5309:        decrease memory allocation */
                   5310:     for(theta=1; theta <=npar; theta++){
                   5311:       for(i=1; i<=npar; i++){ 
1.222     brouard  5312:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5313:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5314:       }
1.235     brouard  5315:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5316:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5317:                        
1.126     brouard  5318:       for(j=1; j<= nlstate; j++){
1.222     brouard  5319:        for(i=1; i<=nlstate; i++){
                   5320:          for(h=0; h<=nhstepm-1; h++){
                   5321:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5322:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5323:          }
                   5324:        }
1.126     brouard  5325:       }
1.218     brouard  5326:                        
1.126     brouard  5327:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5328:        for(h=0; h<=nhstepm-1; h++){
                   5329:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5330:        }
1.126     brouard  5331:     }/* End theta */
                   5332:     
                   5333:     
                   5334:     for(h=0; h<=nhstepm-1; h++)
                   5335:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5336:        for(theta=1; theta <=npar; theta++)
                   5337:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5338:     
1.218     brouard  5339:                
1.222     brouard  5340:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5341:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5342:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5343:                
1.222     brouard  5344:     printf("%d|",(int)age);fflush(stdout);
                   5345:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5346:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5347:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5348:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5349:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5350:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5351:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5352:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5353:       }
                   5354:     }
1.218     brouard  5355:                
1.126     brouard  5356:     /* Computing expectancies */
1.235     brouard  5357:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5358:     for(i=1; i<=nlstate;i++)
                   5359:       for(j=1; j<=nlstate;j++)
1.222     brouard  5360:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5361:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5362:                                        
1.222     brouard  5363:          /* 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  5364:                                        
1.222     brouard  5365:        }
1.218     brouard  5366:                
1.126     brouard  5367:     fprintf(ficresstdeij,"%3.0f",age );
                   5368:     for(i=1; i<=nlstate;i++){
                   5369:       eip=0.;
                   5370:       vip=0.;
                   5371:       for(j=1; j<=nlstate;j++){
1.222     brouard  5372:        eip += eij[i][j][(int)age];
                   5373:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5374:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5375:        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  5376:       }
                   5377:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5378:     }
                   5379:     fprintf(ficresstdeij,"\n");
1.218     brouard  5380:                
1.126     brouard  5381:     fprintf(ficrescveij,"%3.0f",age );
                   5382:     for(i=1; i<=nlstate;i++)
                   5383:       for(j=1; j<=nlstate;j++){
1.222     brouard  5384:        cptj= (j-1)*nlstate+i;
                   5385:        for(i2=1; i2<=nlstate;i2++)
                   5386:          for(j2=1; j2<=nlstate;j2++){
                   5387:            cptj2= (j2-1)*nlstate+i2;
                   5388:            if(cptj2 <= cptj)
                   5389:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5390:          }
1.126     brouard  5391:       }
                   5392:     fprintf(ficrescveij,"\n");
1.218     brouard  5393:                
1.126     brouard  5394:   }
                   5395:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5396:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5397:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5398:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5399:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5400:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5401:   printf("\n");
                   5402:   fprintf(ficlog,"\n");
1.218     brouard  5403:        
1.126     brouard  5404:   free_vector(xm,1,npar);
                   5405:   free_vector(xp,1,npar);
                   5406:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5407:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5408:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5409: }
1.218     brouard  5410:  
1.126     brouard  5411: /************ Variance ******************/
1.235     brouard  5412:  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  5413:  {
                   5414:    /* Variance of health expectancies */
                   5415:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5416:    /* double **newm;*/
                   5417:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5418:   
                   5419:    /* int movingaverage(); */
                   5420:    double **dnewm,**doldm;
                   5421:    double **dnewmp,**doldmp;
                   5422:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5423:    int k;
                   5424:    double *xp;
                   5425:    double **gp, **gm;  /* for var eij */
                   5426:    double ***gradg, ***trgradg; /*for var eij */
                   5427:    double **gradgp, **trgradgp; /* for var p point j */
                   5428:    double *gpp, *gmp; /* for var p point j */
                   5429:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5430:    double ***p3mat;
                   5431:    double age,agelim, hf;
                   5432:    /* double ***mobaverage; */
                   5433:    int theta;
                   5434:    char digit[4];
                   5435:    char digitp[25];
                   5436: 
                   5437:    char fileresprobmorprev[FILENAMELENGTH];
                   5438: 
                   5439:    if(popbased==1){
                   5440:      if(mobilav!=0)
                   5441:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5442:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5443:    }
                   5444:    else 
                   5445:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5446: 
1.218     brouard  5447:    /* if (mobilav!=0) { */
                   5448:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5449:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5450:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5451:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5452:    /*   } */
                   5453:    /* } */
                   5454: 
                   5455:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5456:    sprintf(digit,"%-d",ij);
                   5457:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5458:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5459:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5460:    strcat(fileresprobmorprev,fileresu);
                   5461:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5462:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5463:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5464:    }
                   5465:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5466:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5467:    pstamp(ficresprobmorprev);
                   5468:    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);
1.238     brouard  5469:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5470:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5471:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5472:    }
                   5473:    for(j=1;j<=cptcoveff;j++) 
                   5474:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5475:    fprintf(ficresprobmorprev,"\n");
                   5476: 
1.218     brouard  5477:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5478:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5479:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5480:      for(i=1; i<=nlstate;i++)
                   5481:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5482:    }  
                   5483:    fprintf(ficresprobmorprev,"\n");
                   5484:   
                   5485:    fprintf(ficgp,"\n# Routine varevsij");
                   5486:    fprintf(ficgp,"\nunset title \n");
                   5487:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5488:    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");
                   5489:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5490:    /*   } */
                   5491:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5492:    pstamp(ficresvij);
                   5493:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5494:    if(popbased==1)
                   5495:      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);
                   5496:    else
                   5497:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5498:    fprintf(ficresvij,"# Age");
                   5499:    for(i=1; i<=nlstate;i++)
                   5500:      for(j=1; j<=nlstate;j++)
                   5501:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5502:    fprintf(ficresvij,"\n");
                   5503: 
                   5504:    xp=vector(1,npar);
                   5505:    dnewm=matrix(1,nlstate,1,npar);
                   5506:    doldm=matrix(1,nlstate,1,nlstate);
                   5507:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5508:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5509: 
                   5510:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5511:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5512:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5513:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5514:   
1.218     brouard  5515:    if(estepm < stepm){
                   5516:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5517:    }
                   5518:    else  hstepm=estepm;   
                   5519:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5520:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5521:       nhstepm is the number of hstepm from age to agelim 
                   5522:       nstepm is the number of stepm from age to agelim. 
                   5523:       Look at function hpijx to understand why because of memory size limitations, 
                   5524:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5525:       survival function given by stepm (the optimization length). Unfortunately it
                   5526:       means that if the survival funtion is printed every two years of age and if
                   5527:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5528:       results. So we changed our mind and took the option of the best precision.
                   5529:    */
                   5530:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5531:    agelim = AGESUP;
                   5532:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5533:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5534:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5535:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5536:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5537:      gp=matrix(0,nhstepm,1,nlstate);
                   5538:      gm=matrix(0,nhstepm,1,nlstate);
                   5539:                
                   5540:                
                   5541:      for(theta=1; theta <=npar; theta++){
                   5542:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5543:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5544:        }
                   5545:                        
1.242     brouard  5546:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5547:                        
                   5548:        if (popbased==1) {
                   5549:         if(mobilav ==0){
                   5550:           for(i=1; i<=nlstate;i++)
                   5551:             prlim[i][i]=probs[(int)age][i][ij];
                   5552:         }else{ /* mobilav */ 
                   5553:           for(i=1; i<=nlstate;i++)
                   5554:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5555:         }
                   5556:        }
                   5557:                        
1.235     brouard  5558:        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  5559:        for(j=1; j<= nlstate; j++){
                   5560:         for(h=0; h<=nhstepm; h++){
                   5561:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5562:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5563:         }
                   5564:        }
                   5565:        /* Next for computing probability of death (h=1 means
                   5566:          computed over hstepm matrices product = hstepm*stepm months) 
                   5567:          as a weighted average of prlim.
                   5568:        */
                   5569:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5570:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5571:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5572:        }    
                   5573:        /* end probability of death */
                   5574:                        
                   5575:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5576:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5577:                        
1.242     brouard  5578:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5579:                        
                   5580:        if (popbased==1) {
                   5581:         if(mobilav ==0){
                   5582:           for(i=1; i<=nlstate;i++)
                   5583:             prlim[i][i]=probs[(int)age][i][ij];
                   5584:         }else{ /* mobilav */ 
                   5585:           for(i=1; i<=nlstate;i++)
                   5586:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5587:         }
                   5588:        }
                   5589:                        
1.235     brouard  5590:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5591:                        
                   5592:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5593:         for(h=0; h<=nhstepm; h++){
                   5594:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5595:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5596:         }
                   5597:        }
                   5598:        /* This for computing probability of death (h=1 means
                   5599:          computed over hstepm matrices product = hstepm*stepm months) 
                   5600:          as a weighted average of prlim.
                   5601:        */
                   5602:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5603:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5604:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5605:        }    
                   5606:        /* end probability of death */
                   5607:                        
                   5608:        for(j=1; j<= nlstate; j++) /* vareij */
                   5609:         for(h=0; h<=nhstepm; h++){
                   5610:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5611:         }
                   5612:                        
                   5613:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5614:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5615:        }
                   5616:                        
                   5617:      } /* End theta */
                   5618:                
                   5619:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5620:                
                   5621:      for(h=0; h<=nhstepm; h++) /* veij */
                   5622:        for(j=1; j<=nlstate;j++)
                   5623:         for(theta=1; theta <=npar; theta++)
                   5624:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5625:                
                   5626:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5627:        for(theta=1; theta <=npar; theta++)
                   5628:         trgradgp[j][theta]=gradgp[theta][j];
                   5629:                
                   5630:                
                   5631:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5632:      for(i=1;i<=nlstate;i++)
                   5633:        for(j=1;j<=nlstate;j++)
                   5634:         vareij[i][j][(int)age] =0.;
                   5635:                
                   5636:      for(h=0;h<=nhstepm;h++){
                   5637:        for(k=0;k<=nhstepm;k++){
                   5638:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5639:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5640:         for(i=1;i<=nlstate;i++)
                   5641:           for(j=1;j<=nlstate;j++)
                   5642:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5643:        }
                   5644:      }
                   5645:                
                   5646:      /* pptj */
                   5647:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5648:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5649:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5650:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5651:         varppt[j][i]=doldmp[j][i];
                   5652:      /* end ppptj */
                   5653:      /*  x centered again */
                   5654:                
1.242     brouard  5655:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5656:                
                   5657:      if (popbased==1) {
                   5658:        if(mobilav ==0){
                   5659:         for(i=1; i<=nlstate;i++)
                   5660:           prlim[i][i]=probs[(int)age][i][ij];
                   5661:        }else{ /* mobilav */ 
                   5662:         for(i=1; i<=nlstate;i++)
                   5663:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5664:        }
                   5665:      }
                   5666:                
                   5667:      /* This for computing probability of death (h=1 means
                   5668:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5669:        as a weighted average of prlim.
                   5670:      */
1.235     brouard  5671:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5672:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5673:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5674:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5675:      }    
                   5676:      /* end probability of death */
                   5677:                
                   5678:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5679:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5680:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5681:        for(i=1; i<=nlstate;i++){
                   5682:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5683:        }
                   5684:      } 
                   5685:      fprintf(ficresprobmorprev,"\n");
                   5686:                
                   5687:      fprintf(ficresvij,"%.0f ",age );
                   5688:      for(i=1; i<=nlstate;i++)
                   5689:        for(j=1; j<=nlstate;j++){
                   5690:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5691:        }
                   5692:      fprintf(ficresvij,"\n");
                   5693:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5694:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5695:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5696:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5697:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5698:    } /* End age */
                   5699:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5700:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5701:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5702:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5703:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5704:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5705:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5706:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5707:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5708:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5709:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5710:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5711:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5712:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5713:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5714:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5715:    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);
                   5716:    /*  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  5717:     */
1.218     brouard  5718:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5719:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5720: 
1.218     brouard  5721:    free_vector(xp,1,npar);
                   5722:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5723:    free_matrix(dnewm,1,nlstate,1,npar);
                   5724:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5725:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5726:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5727:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5728:    fclose(ficresprobmorprev);
                   5729:    fflush(ficgp);
                   5730:    fflush(fichtm); 
                   5731:  }  /* end varevsij */
1.126     brouard  5732: 
                   5733: /************ Variance of prevlim ******************/
1.235     brouard  5734:  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  5735: {
1.205     brouard  5736:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5737:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5738: 
1.126     brouard  5739:   double **dnewm,**doldm;
                   5740:   int i, j, nhstepm, hstepm;
                   5741:   double *xp;
                   5742:   double *gp, *gm;
                   5743:   double **gradg, **trgradg;
1.208     brouard  5744:   double **mgm, **mgp;
1.126     brouard  5745:   double age,agelim;
                   5746:   int theta;
                   5747:   
                   5748:   pstamp(ficresvpl);
                   5749:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5750:   fprintf(ficresvpl,"# Age ");
                   5751:   if(nresult >=1)
                   5752:     fprintf(ficresvpl," Result# ");
1.126     brouard  5753:   for(i=1; i<=nlstate;i++)
                   5754:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5755:   fprintf(ficresvpl,"\n");
                   5756: 
                   5757:   xp=vector(1,npar);
                   5758:   dnewm=matrix(1,nlstate,1,npar);
                   5759:   doldm=matrix(1,nlstate,1,nlstate);
                   5760:   
                   5761:   hstepm=1*YEARM; /* Every year of age */
                   5762:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5763:   agelim = AGESUP;
                   5764:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5765:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5766:     if (stepm >= YEARM) hstepm=1;
                   5767:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5768:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5769:     mgp=matrix(1,npar,1,nlstate);
                   5770:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5771:     gp=vector(1,nlstate);
                   5772:     gm=vector(1,nlstate);
                   5773: 
                   5774:     for(theta=1; theta <=npar; theta++){
                   5775:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5776:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5777:       }
1.209     brouard  5778:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5779:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5780:       else
1.235     brouard  5781:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5782:       for(i=1;i<=nlstate;i++){
1.126     brouard  5783:        gp[i] = prlim[i][i];
1.208     brouard  5784:        mgp[theta][i] = prlim[i][i];
                   5785:       }
1.126     brouard  5786:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5787:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5788:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5789:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5790:       else
1.235     brouard  5791:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5792:       for(i=1;i<=nlstate;i++){
1.126     brouard  5793:        gm[i] = prlim[i][i];
1.208     brouard  5794:        mgm[theta][i] = prlim[i][i];
                   5795:       }
1.126     brouard  5796:       for(i=1;i<=nlstate;i++)
                   5797:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5798:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5799:     } /* End theta */
                   5800: 
                   5801:     trgradg =matrix(1,nlstate,1,npar);
                   5802: 
                   5803:     for(j=1; j<=nlstate;j++)
                   5804:       for(theta=1; theta <=npar; theta++)
                   5805:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5806:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5807:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5808:     /*   for(j=1; j<=nlstate;j++){ */
                   5809:     /*         printf(" %d ",j); */
                   5810:     /*         for(theta=1; theta <=npar; theta++) */
                   5811:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5812:     /*         printf("\n "); */
                   5813:     /*   } */
                   5814:     /* } */
                   5815:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5816:     /*   printf("\n gradg %d ",(int)age); */
                   5817:     /*   for(j=1; j<=nlstate;j++){ */
                   5818:     /*         printf("%d ",j); */
                   5819:     /*         for(theta=1; theta <=npar; theta++) */
                   5820:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5821:     /*         printf("\n "); */
                   5822:     /*   } */
                   5823:     /* } */
1.126     brouard  5824: 
                   5825:     for(i=1;i<=nlstate;i++)
                   5826:       varpl[i][(int)age] =0.;
1.209     brouard  5827:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5828:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5829:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5830:     }else{
1.126     brouard  5831:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5832:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5833:     }
1.126     brouard  5834:     for(i=1;i<=nlstate;i++)
                   5835:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5836: 
                   5837:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  5838:     if(nresult >=1)
                   5839:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  5840:     for(i=1; i<=nlstate;i++)
                   5841:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5842:     fprintf(ficresvpl,"\n");
                   5843:     free_vector(gp,1,nlstate);
                   5844:     free_vector(gm,1,nlstate);
1.208     brouard  5845:     free_matrix(mgm,1,npar,1,nlstate);
                   5846:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5847:     free_matrix(gradg,1,npar,1,nlstate);
                   5848:     free_matrix(trgradg,1,nlstate,1,npar);
                   5849:   } /* End age */
                   5850: 
                   5851:   free_vector(xp,1,npar);
                   5852:   free_matrix(doldm,1,nlstate,1,npar);
                   5853:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5854: 
                   5855: }
                   5856: 
                   5857: /************ Variance of one-step probabilities  ******************/
                   5858: 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  5859:  {
                   5860:    int i, j=0,  k1, l1, tj;
                   5861:    int k2, l2, j1,  z1;
                   5862:    int k=0, l;
                   5863:    int first=1, first1, first2;
                   5864:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5865:    double **dnewm,**doldm;
                   5866:    double *xp;
                   5867:    double *gp, *gm;
                   5868:    double **gradg, **trgradg;
                   5869:    double **mu;
                   5870:    double age, cov[NCOVMAX+1];
                   5871:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5872:    int theta;
                   5873:    char fileresprob[FILENAMELENGTH];
                   5874:    char fileresprobcov[FILENAMELENGTH];
                   5875:    char fileresprobcor[FILENAMELENGTH];
                   5876:    double ***varpij;
                   5877: 
                   5878:    strcpy(fileresprob,"PROB_"); 
                   5879:    strcat(fileresprob,fileres);
                   5880:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5881:      printf("Problem with resultfile: %s\n", fileresprob);
                   5882:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5883:    }
                   5884:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5885:    strcat(fileresprobcov,fileresu);
                   5886:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5887:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5888:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5889:    }
                   5890:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5891:    strcat(fileresprobcor,fileresu);
                   5892:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5893:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5894:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5895:    }
                   5896:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5897:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5898:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5899:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5900:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5901:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5902:    pstamp(ficresprob);
                   5903:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5904:    fprintf(ficresprob,"# Age");
                   5905:    pstamp(ficresprobcov);
                   5906:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5907:    fprintf(ficresprobcov,"# Age");
                   5908:    pstamp(ficresprobcor);
                   5909:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5910:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5911: 
                   5912: 
1.222     brouard  5913:    for(i=1; i<=nlstate;i++)
                   5914:      for(j=1; j<=(nlstate+ndeath);j++){
                   5915:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5916:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5917:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5918:      }  
                   5919:    /* fprintf(ficresprob,"\n");
                   5920:       fprintf(ficresprobcov,"\n");
                   5921:       fprintf(ficresprobcor,"\n");
                   5922:    */
                   5923:    xp=vector(1,npar);
                   5924:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5925:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5926:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5927:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5928:    first=1;
                   5929:    fprintf(ficgp,"\n# Routine varprob");
                   5930:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5931:    fprintf(fichtm,"\n");
                   5932: 
                   5933:    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);
                   5934:    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);
                   5935:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5936: and drawn. It helps understanding how is the covariance between two incidences.\
                   5937:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5938:    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  5939: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5940: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5941: standard deviations wide on each axis. <br>\
                   5942:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5943:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5944: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5945: 
1.222     brouard  5946:    cov[1]=1;
                   5947:    /* tj=cptcoveff; */
1.225     brouard  5948:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5949:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5950:    j1=0;
1.224     brouard  5951:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5952:      if  (cptcovn>0) {
                   5953:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5954:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5955:        fprintf(ficresprob, "**********\n#\n");
                   5956:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5957:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5958:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5959:                        
1.222     brouard  5960:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5961:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5962:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5963:                        
                   5964:                        
1.222     brouard  5965:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5966:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5967:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5968:                        
1.222     brouard  5969:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5970:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5971:        fprintf(ficresprobcor, "**********\n#");    
                   5972:        if(invalidvarcomb[j1]){
                   5973:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5974:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5975:         continue;
                   5976:        }
                   5977:      }
                   5978:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5979:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5980:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5981:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5982:      for (age=bage; age<=fage; age ++){ 
                   5983:        cov[2]=age;
                   5984:        if(nagesqr==1)
                   5985:         cov[3]= age*age;
                   5986:        for (k=1; k<=cptcovn;k++) {
                   5987:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5988:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5989:                                                                    * 1  1 1 1 1
                   5990:                                                                    * 2  2 1 1 1
                   5991:                                                                    * 3  1 2 1 1
                   5992:                                                                    */
                   5993:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5994:        }
                   5995:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5996:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5997:        for (k=1; k<=cptcovprod;k++)
                   5998:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5999:                        
                   6000:                        
1.222     brouard  6001:        for(theta=1; theta <=npar; theta++){
                   6002:         for(i=1; i<=npar; i++)
                   6003:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6004:                                
1.222     brouard  6005:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6006:                                
1.222     brouard  6007:         k=0;
                   6008:         for(i=1; i<= (nlstate); i++){
                   6009:           for(j=1; j<=(nlstate+ndeath);j++){
                   6010:             k=k+1;
                   6011:             gp[k]=pmmij[i][j];
                   6012:           }
                   6013:         }
1.220     brouard  6014:                                
1.222     brouard  6015:         for(i=1; i<=npar; i++)
                   6016:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6017:                                
1.222     brouard  6018:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6019:         k=0;
                   6020:         for(i=1; i<=(nlstate); i++){
                   6021:           for(j=1; j<=(nlstate+ndeath);j++){
                   6022:             k=k+1;
                   6023:             gm[k]=pmmij[i][j];
                   6024:           }
                   6025:         }
1.220     brouard  6026:                                
1.222     brouard  6027:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6028:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6029:        }
1.126     brouard  6030: 
1.222     brouard  6031:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6032:         for(theta=1; theta <=npar; theta++)
                   6033:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6034:                        
1.222     brouard  6035:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6036:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6037:                        
1.222     brouard  6038:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6039:                        
1.222     brouard  6040:        k=0;
                   6041:        for(i=1; i<=(nlstate); i++){
                   6042:         for(j=1; j<=(nlstate+ndeath);j++){
                   6043:           k=k+1;
                   6044:           mu[k][(int) age]=pmmij[i][j];
                   6045:         }
                   6046:        }
                   6047:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6048:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6049:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6050:                        
1.222     brouard  6051:        /*printf("\n%d ",(int)age);
                   6052:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6053:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6054:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6055:         }*/
1.220     brouard  6056:                        
1.222     brouard  6057:        fprintf(ficresprob,"\n%d ",(int)age);
                   6058:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6059:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6060:                        
1.222     brouard  6061:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6062:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6063:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6064:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6065:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6066:        }
                   6067:        i=0;
                   6068:        for (k=1; k<=(nlstate);k++){
                   6069:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6070:           i++;
                   6071:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6072:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6073:           for (j=1; j<=i;j++){
                   6074:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6075:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6076:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6077:           }
                   6078:         }
                   6079:        }/* end of loop for state */
                   6080:      } /* end of loop for age */
                   6081:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6082:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6083:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6084:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6085:     
                   6086:      /* Confidence intervalle of pij  */
                   6087:      /*
                   6088:        fprintf(ficgp,"\nunset parametric;unset label");
                   6089:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6090:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6091:        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);
                   6092:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6093:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6094:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6095:      */
                   6096:                
                   6097:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6098:      first1=1;first2=2;
                   6099:      for (k2=1; k2<=(nlstate);k2++){
                   6100:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6101:         if(l2==k2) continue;
                   6102:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6103:         for (k1=1; k1<=(nlstate);k1++){
                   6104:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6105:             if(l1==k1) continue;
                   6106:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6107:             if(i<=j) continue;
                   6108:             for (age=bage; age<=fage; age ++){ 
                   6109:               if ((int)age %5==0){
                   6110:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6111:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6112:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6113:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6114:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6115:                 c12=cv12/sqrt(v1*v2);
                   6116:                 /* Computing eigen value of matrix of covariance */
                   6117:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6118:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6119:                 if ((lc2 <0) || (lc1 <0) ){
                   6120:                   if(first2==1){
                   6121:                     first1=0;
                   6122:                     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);
                   6123:                   }
                   6124:                   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);
                   6125:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6126:                   /* lc2=fabs(lc2); */
                   6127:                 }
1.220     brouard  6128:                                                                
1.222     brouard  6129:                 /* Eigen vectors */
                   6130:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6131:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6132:                 v21=(lc1-v1)/cv12*v11;
                   6133:                 v12=-v21;
                   6134:                 v22=v11;
                   6135:                 tnalp=v21/v11;
                   6136:                 if(first1==1){
                   6137:                   first1=0;
                   6138:                   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);
                   6139:                 }
                   6140:                 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);
                   6141:                 /*printf(fignu*/
                   6142:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6143:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6144:                 if(first==1){
                   6145:                   first=0;
                   6146:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6147:                   fprintf(ficgp,"\nset parametric;unset label");
                   6148:                   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);
                   6149:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6150:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6151:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6152: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6153:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6154:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6155:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6156:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6157:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6158:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6159:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6160:                   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",      \
                   6161:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6162:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6163:                 }else{
                   6164:                   first=0;
                   6165:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6166:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6167:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6168:                   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", \
                   6169:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6170:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6171:                 }/* if first */
                   6172:               } /* age mod 5 */
                   6173:             } /* end loop age */
                   6174:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6175:             first=1;
                   6176:           } /*l12 */
                   6177:         } /* k12 */
                   6178:        } /*l1 */
                   6179:      }/* k1 */
                   6180:    }  /* loop on combination of covariates j1 */
                   6181:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6182:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6183:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6184:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6185:    free_vector(xp,1,npar);
                   6186:    fclose(ficresprob);
                   6187:    fclose(ficresprobcov);
                   6188:    fclose(ficresprobcor);
                   6189:    fflush(ficgp);
                   6190:    fflush(fichtmcov);
                   6191:  }
1.126     brouard  6192: 
                   6193: 
                   6194: /******************* Printing html file ***********/
1.201     brouard  6195: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6196:                  int lastpass, int stepm, int weightopt, char model[],\
                   6197:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6198:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6199:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6200:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6201:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6202: 
                   6203:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6204:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6205: </ul>");
1.237     brouard  6206:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6207: </ul>", model);
1.214     brouard  6208:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6209:    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",
                   6210:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6211:    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  6212:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6213:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6214:    fprintf(fichtm,"\
                   6215:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6216:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6217:    fprintf(fichtm,"\
1.217     brouard  6218:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6219:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6220:    fprintf(fichtm,"\
1.126     brouard  6221:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6222:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6223:    fprintf(fichtm,"\
1.217     brouard  6224:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6225:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6226:    fprintf(fichtm,"\
1.211     brouard  6227:  - (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  6228:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6229:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6230:    if(prevfcast==1){
                   6231:      fprintf(fichtm,"\
                   6232:  - Prevalence projections by age and states:                           \
1.201     brouard  6233:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6234:    }
1.126     brouard  6235: 
1.222     brouard  6236:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6237: 
1.225     brouard  6238:    m=pow(2,cptcoveff);
1.222     brouard  6239:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6240: 
1.222     brouard  6241:    jj1=0;
1.237     brouard  6242: 
                   6243:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6244:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.237     brouard  6245:      if(TKresult[nres]!= k1)
                   6246:        continue;
1.220     brouard  6247: 
1.222     brouard  6248:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6249:      jj1++;
                   6250:      if (cptcovn > 0) {
                   6251:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6252:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6253:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6254:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6255:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6256:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6257:        }
1.237     brouard  6258:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6259:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6260:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6261:       }
                   6262:        
1.230     brouard  6263:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6264:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6265:        if(invalidvarcomb[k1]){
                   6266:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6267:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6268:         continue;
                   6269:        }
                   6270:      }
                   6271:      /* aij, bij */
1.241     brouard  6272:      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-%d.svg\">%s_%d-1-%d.svg</a><br> \
                   6273: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
1.222     brouard  6274:      /* Pij */
1.241     brouard  6275:      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-%d.svg\">%s_%d-2-%d.svg</a><br> \
                   6276: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
1.222     brouard  6277:      /* Quasi-incidences */
                   6278:      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  6279:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6280:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
1.241     brouard  6281: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3-%d.svg\">%s_%d-3-%d.svg</a><br> \
                   6282: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
1.222     brouard  6283:      /* Survival functions (period) in state j */
                   6284:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6285:        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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6286: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  6287:      }
                   6288:      /* State specific survival functions (period) */
                   6289:      for(cpt=1; cpt<=nlstate;cpt++){
                   6290:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6291:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6292:  <a href=\"%s_%d-%d-%d.svg\">%s_%d%d-%d.svg</a><br> <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  6293:      }
                   6294:      /* Period (stable) prevalence in each health state */
                   6295:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6296:        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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6297: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  6298:      }
                   6299:      if(backcast==1){
                   6300:        /* Period (stable) back prevalence in each health state */
                   6301:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6302:         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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6303: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  6304:        }
1.217     brouard  6305:      }
1.222     brouard  6306:      if(prevfcast==1){
                   6307:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6308:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6309:         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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6310: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  6311:        }
                   6312:      }
1.220     brouard  6313:         
1.222     brouard  6314:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6315:        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-%d.svg\">%s_%d-%d-%d.svg</a> <br> \
                   6316: <img src=\"%s_%d-%d-%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.222     brouard  6317:      }
                   6318:      /* } /\* end i1 *\/ */
                   6319:    }/* End k1 */
                   6320:    fprintf(fichtm,"</ul>");
1.126     brouard  6321: 
1.222     brouard  6322:    fprintf(fichtm,"\
1.126     brouard  6323: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6324:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6325:  - 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  6326: But because parameters are usually highly correlated (a higher incidence of disability \
                   6327: and a higher incidence of recovery can give very close observed transition) it might \
                   6328: be very useful to look not only at linear confidence intervals estimated from the \
                   6329: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6330: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6331: covariance matrix of the one-step probabilities. \
                   6332: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6333: 
1.222     brouard  6334:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6335:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6336:    fprintf(fichtm,"\
1.126     brouard  6337:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6338:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6339: 
1.222     brouard  6340:    fprintf(fichtm,"\
1.126     brouard  6341:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6342:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6343:    fprintf(fichtm,"\
1.126     brouard  6344:  - 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): \
                   6345:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6346:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6347:    fprintf(fichtm,"\
1.126     brouard  6348:  - (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): \
                   6349:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6350:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6351:    fprintf(fichtm,"\
1.128     brouard  6352:  - 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  6353:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6354:    fprintf(fichtm,"\
1.128     brouard  6355:  - 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  6356:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6357:    fprintf(fichtm,"\
1.126     brouard  6358:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6359:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6360: 
                   6361: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6362: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6363: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6364: /*     <br>",fileres,fileres,fileres,fileres); */
                   6365: /*  else  */
                   6366: /*    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  6367:    fflush(fichtm);
                   6368:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6369: 
1.225     brouard  6370:    m=pow(2,cptcoveff);
1.222     brouard  6371:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6372: 
1.222     brouard  6373:    jj1=0;
1.237     brouard  6374: 
1.241     brouard  6375:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6376:    for(k1=1; k1<=m;k1++){
1.237     brouard  6377:      if(TKresult[nres]!= k1)
                   6378:        continue;
1.222     brouard  6379:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6380:      jj1++;
1.126     brouard  6381:      if (cptcovn > 0) {
                   6382:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6383:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6384:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6385:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6386:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6387:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6388:       }
                   6389: 
1.126     brouard  6390:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6391: 
1.222     brouard  6392:        if(invalidvarcomb[k1]){
                   6393:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6394:         continue;
                   6395:        }
1.126     brouard  6396:      }
                   6397:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6398:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
1.241     brouard  6399: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
                   6400: <img src=\"%s_%d-%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
1.126     brouard  6401:      }
                   6402:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6403: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6404: true period expectancies (those weighted with period prevalences are also\
                   6405:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6406:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6407: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6408:      /* } /\* end i1 *\/ */
                   6409:    }/* End k1 */
1.241     brouard  6410:   }/* End nres */
1.222     brouard  6411:    fprintf(fichtm,"</ul>");
                   6412:    fflush(fichtm);
1.126     brouard  6413: }
                   6414: 
                   6415: /******************* Gnuplot file **************/
1.223     brouard  6416: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6417: 
                   6418:   char dirfileres[132],optfileres[132];
1.223     brouard  6419:   char gplotcondition[132];
1.237     brouard  6420:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
1.211     brouard  6421:   int lv=0, vlv=0, kl=0;
1.130     brouard  6422:   int ng=0;
1.201     brouard  6423:   int vpopbased;
1.223     brouard  6424:   int ioffset; /* variable offset for columns */
1.235     brouard  6425:   int nres=0; /* Index of resultline */
1.219     brouard  6426: 
1.126     brouard  6427: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6428: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6429: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6430: /*   } */
                   6431: 
                   6432:   /*#ifdef windows */
                   6433:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6434:   /*#endif */
1.225     brouard  6435:   m=pow(2,cptcoveff);
1.126     brouard  6436: 
1.202     brouard  6437:   /* Contribution to likelihood */
                   6438:   /* Plot the probability implied in the likelihood */
1.223     brouard  6439:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6440:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6441:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6442:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6443: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6444:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6445: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6446:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6447:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6448:   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));
                   6449:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6450:   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));
                   6451:   for (i=1; i<= nlstate ; i ++) {
                   6452:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6453:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6454:     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);
                   6455:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6456:       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);
                   6457:     }
                   6458:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6459:   }
                   6460:   /* 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 */               
                   6461:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6462:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6463:   fprintf(ficgp,"\nset out;unset log\n");
                   6464:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6465: 
1.126     brouard  6466:   strcpy(dirfileres,optionfilefiname);
                   6467:   strcpy(optfileres,"vpl");
1.223     brouard  6468:   /* 1eme*/
1.238     brouard  6469:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6470:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6471:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6472:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6473:        if(TKresult[nres]!= k1)
                   6474:          continue;
                   6475:        /* We are interested in selected combination by the resultline */
1.246     brouard  6476:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.238     brouard  6477:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6478:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6479:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6480:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6481:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6482:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6483:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6484:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  6485:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  6486:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6487:        }
                   6488:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  6489:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  6490:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6491:        }       
1.246     brouard  6492:        /* printf("\n#\n"); */
1.238     brouard  6493:        fprintf(ficgp,"\n#\n");
                   6494:        if(invalidvarcomb[k1]){
                   6495:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6496:          continue;
                   6497:        }
1.235     brouard  6498:       
1.241     brouard  6499:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6500:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   6501:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
1.235     brouard  6502:       
1.238     brouard  6503:        for (i=1; i<= nlstate ; i ++) {
                   6504:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6505:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6506:        }
1.242     brouard  6507:        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
1.238     brouard  6508:        for (i=1; i<= nlstate ; i ++) {
                   6509:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6510:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6511:        } 
1.242     brouard  6512:        fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres); 
1.238     brouard  6513:        for (i=1; i<= nlstate ; i ++) {
                   6514:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6515:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6516:        }  
                   6517:        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));
                   6518:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6519:          /* 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); */
1.242     brouard  6520:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6521:          if(cptcoveff ==0){
1.245     brouard  6522:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  6523:          }else{
                   6524:            kl=0;
                   6525:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6526:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6527:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6528:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6529:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6530:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6531:              kl++;
1.238     brouard  6532:              /* 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 *\/ */
                   6533:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6534:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6535:              /* ''  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*/
                   6536:              if(k==cptcoveff){
1.245     brouard  6537:                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' w l lt 3",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
1.242     brouard  6538:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6539:              }else{
                   6540:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6541:                kl++;
                   6542:              }
                   6543:            } /* end covariate */
                   6544:          } /* end if no covariate */
                   6545:        } /* end if backcast */
                   6546:        fprintf(ficgp,"\nset out \n");
                   6547:       } /* nres */
1.201     brouard  6548:     } /* k1 */
                   6549:   } /* cpt */
1.235     brouard  6550: 
                   6551:   
1.126     brouard  6552:   /*2 eme*/
1.238     brouard  6553:   for (k1=1; k1<= m ; k1 ++){  
                   6554:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6555:       if(TKresult[nres]!= k1)
                   6556:        continue;
                   6557:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6558:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6559:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6560:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6561:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6562:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6563:        vlv= nbcode[Tvaraff[k]][lv];
                   6564:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6565:       }
1.237     brouard  6566:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6567:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6568:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6569:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6570:       }
1.211     brouard  6571:       fprintf(ficgp,"\n#\n");
1.223     brouard  6572:       if(invalidvarcomb[k1]){
                   6573:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6574:        continue;
                   6575:       }
1.219     brouard  6576:                        
1.241     brouard  6577:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6578:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6579:        if(vpopbased==0)
                   6580:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6581:        else
                   6582:          fprintf(ficgp,"\nreplot ");
                   6583:        for (i=1; i<= nlstate+1 ; i ++) {
                   6584:          k=2*i;
                   6585:          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);
                   6586:          for (j=1; j<= nlstate+1 ; j ++) {
                   6587:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6588:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6589:          }   
                   6590:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6591:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6592:          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);
                   6593:          for (j=1; j<= nlstate+1 ; j ++) {
                   6594:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6595:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6596:          }   
                   6597:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6598:          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);
                   6599:          for (j=1; j<= nlstate+1 ; j ++) {
                   6600:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6601:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6602:          }   
                   6603:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6604:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6605:        } /* state */
                   6606:       } /* vpopbased */
1.244     brouard  6607:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  6608:     } /* end nres */
                   6609:   } /* k1 end 2 eme*/
                   6610:        
                   6611:        
                   6612:   /*3eme*/
                   6613:   for (k1=1; k1<= m ; k1 ++){
                   6614:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.240     brouard  6615:       if(TKresult[nres]!= k1)
1.238     brouard  6616:        continue;
                   6617: 
                   6618:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6619:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6620:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6621:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6622:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6623:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6624:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6625:          vlv= nbcode[Tvaraff[k]][lv];
                   6626:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6627:        }
                   6628:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6629:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6630:        }       
                   6631:        fprintf(ficgp,"\n#\n");
                   6632:        if(invalidvarcomb[k1]){
                   6633:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6634:          continue;
                   6635:        }
                   6636:                        
                   6637:        /*       k=2+nlstate*(2*cpt-2); */
                   6638:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6639:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6640:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6641: 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.238     brouard  6642:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6643:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6644:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6645:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6646:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6647:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6648:                                
1.238     brouard  6649:        */
                   6650:        for (i=1; i< nlstate ; i ++) {
                   6651:          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);
                   6652:          /*    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  6653:                                
1.238     brouard  6654:        } 
                   6655:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6656:       }
                   6657:     } /* end nres */
                   6658:   } /* end kl 3eme */
1.126     brouard  6659:   
1.223     brouard  6660:   /* 4eme */
1.201     brouard  6661:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6662:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6663:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6664:       if(TKresult[nres]!= k1)
1.223     brouard  6665:        continue;
1.238     brouard  6666:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6667:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6668:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6669:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6670:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6671:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6672:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6673:          vlv= nbcode[Tvaraff[k]][lv];
                   6674:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6675:        }
                   6676:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6677:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6678:        }       
                   6679:        fprintf(ficgp,"\n#\n");
                   6680:        if(invalidvarcomb[k1]){
                   6681:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6682:          continue;
1.223     brouard  6683:        }
1.238     brouard  6684:       
1.241     brouard  6685:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6686:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6687: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6688:        k=3;
                   6689:        for (i=1; i<= nlstate ; i ++){
                   6690:          if(i==1){
                   6691:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6692:          }else{
                   6693:            fprintf(ficgp,", '' ");
                   6694:          }
                   6695:          l=(nlstate+ndeath)*(i-1)+1;
                   6696:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6697:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6698:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6699:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6700:        } /* nlstate */
                   6701:        fprintf(ficgp,"\nset out\n");
                   6702:       } /* end cpt state*/ 
                   6703:     } /* end nres */
                   6704:   } /* end covariate k1 */  
                   6705: 
1.220     brouard  6706: /* 5eme */
1.201     brouard  6707:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6708:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6709:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6710:       if(TKresult[nres]!= k1)
1.227     brouard  6711:        continue;
1.238     brouard  6712:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6713:        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);
                   6714:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6715:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6716:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6717:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6718:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6719:          vlv= nbcode[Tvaraff[k]][lv];
                   6720:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6721:        }
                   6722:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6723:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6724:        }       
                   6725:        fprintf(ficgp,"\n#\n");
                   6726:        if(invalidvarcomb[k1]){
                   6727:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6728:          continue;
                   6729:        }
1.227     brouard  6730:       
1.241     brouard  6731:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6732:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6733: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6734:        k=3;
                   6735:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6736:          if(j==1)
                   6737:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6738:          else
                   6739:            fprintf(ficgp,", '' ");
                   6740:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6741:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6742:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6743:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6744:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6745:        } /* nlstate */
                   6746:        fprintf(ficgp,", '' ");
                   6747:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6748:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6749:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6750:          if(j < nlstate)
                   6751:            fprintf(ficgp,"$%d +",k+l);
                   6752:          else
                   6753:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6754:        }
                   6755:        fprintf(ficgp,"\nset out\n");
                   6756:       } /* end cpt state*/ 
                   6757:     } /* end covariate */  
                   6758:   } /* end nres */
1.227     brouard  6759:   
1.220     brouard  6760: /* 6eme */
1.202     brouard  6761:   /* CV preval stable (period) for each covariate */
1.237     brouard  6762:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6763:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6764:     if(TKresult[nres]!= k1)
                   6765:       continue;
1.153     brouard  6766:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6767:       
1.211     brouard  6768:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6769:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6770:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6771:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6772:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6773:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6774:        vlv= nbcode[Tvaraff[k]][lv];
                   6775:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6776:       }
1.237     brouard  6777:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6778:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6779:       }        
1.211     brouard  6780:       fprintf(ficgp,"\n#\n");
1.223     brouard  6781:       if(invalidvarcomb[k1]){
1.227     brouard  6782:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6783:        continue;
1.223     brouard  6784:       }
1.227     brouard  6785:       
1.241     brouard  6786:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6787:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6788: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6789:       k=3; /* Offset */
1.153     brouard  6790:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6791:        if(i==1)
                   6792:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6793:        else
                   6794:          fprintf(ficgp,", '' ");
                   6795:        l=(nlstate+ndeath)*(i-1)+1;
                   6796:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6797:        for (j=2; j<= nlstate ; j ++)
                   6798:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6799:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6800:       } /* nlstate */
1.201     brouard  6801:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6802:     } /* end cpt state*/ 
                   6803:   } /* end covariate */  
1.227     brouard  6804:   
                   6805:   
1.220     brouard  6806: /* 7eme */
1.218     brouard  6807:   if(backcast == 1){
1.217     brouard  6808:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6809:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6810:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6811:       if(TKresult[nres]!= k1)
                   6812:        continue;
1.218     brouard  6813:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6814:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6815:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6816:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6817:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6818:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6819:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6820:          vlv= nbcode[Tvaraff[k]][lv];
                   6821:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6822:        }
1.237     brouard  6823:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6824:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6825:        }       
1.227     brouard  6826:        fprintf(ficgp,"\n#\n");
                   6827:        if(invalidvarcomb[k1]){
                   6828:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6829:          continue;
                   6830:        }
                   6831:        
1.241     brouard  6832:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  6833:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6834: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6835:        k=3; /* Offset */
                   6836:        for (i=1; i<= nlstate ; i ++){
                   6837:          if(i==1)
                   6838:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6839:          else
                   6840:            fprintf(ficgp,", '' ");
                   6841:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6842:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6843:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6844:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6845:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6846:          /* for (j=2; j<= nlstate ; j ++) */
                   6847:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6848:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6849:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6850:        } /* nlstate */
                   6851:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6852:       } /* end cpt state*/ 
                   6853:     } /* end covariate */  
                   6854:   } /* End if backcast */
                   6855:   
1.223     brouard  6856:   /* 8eme */
1.218     brouard  6857:   if(prevfcast==1){
                   6858:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6859:     
1.237     brouard  6860:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6861:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6862:       if(TKresult[nres]!= k1)
                   6863:        continue;
1.211     brouard  6864:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6865:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6866:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6867:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6868:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6869:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6870:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6871:          vlv= nbcode[Tvaraff[k]][lv];
                   6872:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6873:        }
1.237     brouard  6874:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6875:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6876:        }       
1.227     brouard  6877:        fprintf(ficgp,"\n#\n");
                   6878:        if(invalidvarcomb[k1]){
                   6879:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6880:          continue;
                   6881:        }
                   6882:        
                   6883:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  6884:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  6885:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  6886: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6887:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6888:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6889:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6890:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6891:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6892:          if(i==1){
                   6893:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6894:          }else{
                   6895:            fprintf(ficgp,",\\\n '' ");
                   6896:          }
                   6897:          if(cptcoveff ==0){ /* No covariate */
                   6898:            ioffset=2; /* Age is in 2 */
                   6899:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6900:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6901:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6902:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6903:            fprintf(ficgp," u %d:(", ioffset); 
                   6904:            if(i==nlstate+1)
                   6905:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6906:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6907:            else
                   6908:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6909:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6910:          }else{ /* more than 2 covariates */
                   6911:            if(cptcoveff ==1){
                   6912:              ioffset=4; /* Age is in 4 */
                   6913:            }else{
                   6914:              ioffset=6; /* Age is in 6 */
                   6915:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6916:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6917:            }   
                   6918:            fprintf(ficgp," u %d:(",ioffset); 
                   6919:            kl=0;
                   6920:            strcpy(gplotcondition,"(");
                   6921:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6922:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6923:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6924:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6925:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6926:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6927:              kl++;
                   6928:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6929:              kl++;
                   6930:              if(k <cptcoveff && cptcoveff>1)
                   6931:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6932:            }
                   6933:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6934:            /* 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 *\/ */
                   6935:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6936:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6937:            /* ''  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*/
                   6938:            if(i==nlstate+1){
                   6939:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6940:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6941:            }else{
                   6942:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6943:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6944:            }
                   6945:          } /* end if covariate */
                   6946:        } /* nlstate */
                   6947:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6948:       } /* end cpt state*/
                   6949:     } /* end covariate */
                   6950:   } /* End if prevfcast */
1.227     brouard  6951:   
                   6952:   
1.238     brouard  6953:   /* 9eme writing MLE parameters */
                   6954:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6955:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6956:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6957:     for(k=1; k <=(nlstate+ndeath); k++){
                   6958:       if (k != i) {
1.227     brouard  6959:        fprintf(ficgp,"#   current state %d\n",k);
                   6960:        for(j=1; j <=ncovmodel; j++){
                   6961:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6962:          jk++; 
                   6963:        }
                   6964:        fprintf(ficgp,"\n");
1.126     brouard  6965:       }
                   6966:     }
1.223     brouard  6967:   }
1.187     brouard  6968:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6969:   
1.145     brouard  6970:   /*goto avoid;*/
1.238     brouard  6971:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   6972:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6973:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6974:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6975:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6976:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6977:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6978:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6979:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6980:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6981:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6982:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6983:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6984:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6985:   fprintf(ficgp,"#\n");
1.223     brouard  6986:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  6987:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6988:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  6989:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6990:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6991:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6992:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6993:       if(TKresult[nres]!= jk)
                   6994:        continue;
                   6995:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6996:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6997:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6998:       }        
                   6999:       fprintf(ficgp,"\n#\n");
1.241     brouard  7000:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  7001:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7002:       if (ng==1){
                   7003:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7004:        fprintf(ficgp,"\nunset log y");
                   7005:       }else if (ng==2){
                   7006:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7007:        fprintf(ficgp,"\nset log y");
                   7008:       }else if (ng==3){
                   7009:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7010:        fprintf(ficgp,"\nset log y");
                   7011:       }else
                   7012:        fprintf(ficgp,"\nunset title ");
                   7013:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7014:       i=1;
                   7015:       for(k2=1; k2<=nlstate; k2++) {
                   7016:        k3=i;
                   7017:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7018:          if (k != k2){
                   7019:            switch( ng) {
                   7020:            case 1:
                   7021:              if(nagesqr==0)
                   7022:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7023:              else /* nagesqr =1 */
                   7024:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7025:              break;
                   7026:            case 2: /* ng=2 */
                   7027:              if(nagesqr==0)
                   7028:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7029:              else /* nagesqr =1 */
                   7030:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7031:              break;
                   7032:            case 3:
                   7033:              if(nagesqr==0)
                   7034:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7035:              else /* nagesqr =1 */
                   7036:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7037:              break;
                   7038:            }
                   7039:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  7040:            ijp=1; /* product no age */
                   7041:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   7042:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  7043:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  7044:              if(j==Tage[ij]) { /* Product by age */
                   7045:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  7046:                  if(DummyV[j]==0){
1.237     brouard  7047:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   7048:                  }else{ /* quantitative */
                   7049:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   7050:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7051:                  }
                   7052:                  ij++;
                   7053:                }
                   7054:              }else if(j==Tprod[ijp]) { /* */ 
                   7055:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   7056:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  7057:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   7058:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  7059:                      /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],nbcode[Tvard[ijp][2]][codtabm(jk,j)]); */
                   7060:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   7061:                    }else{ /* Vn is dummy and Vm is quanti */
                   7062:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   7063:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7064:                    }
                   7065:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  7066:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  7067:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   7068:                    }else{ /* Both quanti */
                   7069:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7070:                    }
                   7071:                  }
1.238     brouard  7072:                  ijp++;
1.237     brouard  7073:                }
                   7074:              } else{  /* simple covariate */
                   7075:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   7076:                if(Dummy[j]==0){
                   7077:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   7078:                }else{ /* quantitative */
                   7079:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  7080:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7081:                }
1.237     brouard  7082:              } /* end simple */
                   7083:            } /* end j */
1.223     brouard  7084:          }else{
                   7085:            i=i-ncovmodel;
                   7086:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7087:              fprintf(ficgp," (1.");
                   7088:          }
1.227     brouard  7089:          
1.223     brouard  7090:          if(ng != 1){
                   7091:            fprintf(ficgp,")/(1");
1.227     brouard  7092:            
1.223     brouard  7093:            for(k1=1; k1 <=nlstate; k1++){ 
                   7094:              if(nagesqr==0)
                   7095:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7096:              else /* nagesqr =1 */
                   7097:                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  7098:               
1.223     brouard  7099:              ij=1;
                   7100:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7101:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7102:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7103:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7104:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7105:                    ij++;
                   7106:                  }
                   7107:                }
                   7108:                else
1.225     brouard  7109:                  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  7110:              }
                   7111:              fprintf(ficgp,")");
                   7112:            }
                   7113:            fprintf(ficgp,")");
                   7114:            if(ng ==2)
                   7115:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7116:            else /* ng= 3 */
                   7117:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7118:          }else{ /* end ng <> 1 */
                   7119:            if( k !=k2) /* logit p11 is hard to draw */
                   7120:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7121:          }
                   7122:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7123:            fprintf(ficgp,",");
                   7124:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7125:            fprintf(ficgp,",");
                   7126:          i=i+ncovmodel;
                   7127:        } /* end k */
                   7128:       } /* end k2 */
                   7129:       fprintf(ficgp,"\n set out\n");
                   7130:     } /* end jk */
                   7131:   } /* end ng */
                   7132:   /* avoid: */
                   7133:   fflush(ficgp); 
1.126     brouard  7134: }  /* end gnuplot */
                   7135: 
                   7136: 
                   7137: /*************** Moving average **************/
1.219     brouard  7138: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7139:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7140:    
1.222     brouard  7141:    int i, cpt, cptcod;
                   7142:    int modcovmax =1;
                   7143:    int mobilavrange, mob;
                   7144:    int iage=0;
                   7145: 
                   7146:    double sum=0.;
                   7147:    double age;
                   7148:    double *sumnewp, *sumnewm;
                   7149:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7150:   
                   7151:   
1.225     brouard  7152:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7153:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7154: 
                   7155:    sumnewp = vector(1,ncovcombmax);
                   7156:    sumnewm = vector(1,ncovcombmax);
                   7157:    agemingood = vector(1,ncovcombmax); 
                   7158:    agemaxgood = vector(1,ncovcombmax);
                   7159: 
                   7160:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7161:      sumnewm[cptcod]=0.;
                   7162:      sumnewp[cptcod]=0.;
                   7163:      agemingood[cptcod]=0;
                   7164:      agemaxgood[cptcod]=0;
                   7165:    }
                   7166:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7167:   
                   7168:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7169:      if(mobilav==1) mobilavrange=5; /* default */
                   7170:      else mobilavrange=mobilav;
                   7171:      for (age=bage; age<=fage; age++)
                   7172:        for (i=1; i<=nlstate;i++)
                   7173:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7174:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7175:      /* We keep the original values on the extreme ages bage, fage and for 
                   7176:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7177:        we use a 5 terms etc. until the borders are no more concerned. 
                   7178:      */ 
                   7179:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7180:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7181:         for (i=1; i<=nlstate;i++){
                   7182:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7183:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7184:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7185:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7186:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7187:             }
                   7188:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7189:           }
                   7190:         }
                   7191:        }/* end age */
                   7192:      }/* end mob */
                   7193:    }else
                   7194:      return -1;
                   7195:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7196:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7197:      if(invalidvarcomb[cptcod]){
                   7198:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7199:        continue;
                   7200:      }
1.219     brouard  7201: 
1.222     brouard  7202:      agemingood[cptcod]=fage-(mob-1)/2;
                   7203:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7204:        sumnewm[cptcod]=0.;
                   7205:        for (i=1; i<=nlstate;i++){
                   7206:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7207:        }
                   7208:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7209:         agemingood[cptcod]=age;
                   7210:        }else{ /* bad */
                   7211:         for (i=1; i<=nlstate;i++){
                   7212:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7213:         } /* i */
                   7214:        } /* end bad */
                   7215:      }/* age */
                   7216:      sum=0.;
                   7217:      for (i=1; i<=nlstate;i++){
                   7218:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7219:      }
                   7220:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7221:        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);
                   7222:        /* for (i=1; i<=nlstate;i++){ */
                   7223:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7224:        /* } /\* i *\/ */
                   7225:      } /* end bad */
                   7226:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7227:      /* From youngest, finding the oldest wrong */
                   7228:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7229:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7230:        sumnewm[cptcod]=0.;
                   7231:        for (i=1; i<=nlstate;i++){
                   7232:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7233:        }
                   7234:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7235:         agemaxgood[cptcod]=age;
                   7236:        }else{ /* bad */
                   7237:         for (i=1; i<=nlstate;i++){
                   7238:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7239:         } /* i */
                   7240:        } /* end bad */
                   7241:      }/* age */
                   7242:      sum=0.;
                   7243:      for (i=1; i<=nlstate;i++){
                   7244:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7245:      }
                   7246:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7247:        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);
                   7248:        /* for (i=1; i<=nlstate;i++){ */
                   7249:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7250:        /* } /\* i *\/ */
                   7251:      } /* end bad */
                   7252:                
                   7253:      for (age=bage; age<=fage; age++){
1.235     brouard  7254:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7255:        sumnewp[cptcod]=0.;
                   7256:        sumnewm[cptcod]=0.;
                   7257:        for (i=1; i<=nlstate;i++){
                   7258:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7259:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7260:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7261:        }
                   7262:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7263:      }
                   7264:      /* printf("\n"); */
                   7265:      /* } */
                   7266:      /* brutal averaging */
                   7267:      for (i=1; i<=nlstate;i++){
                   7268:        for (age=1; age<=bage; age++){
                   7269:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7270:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7271:        }       
                   7272:        for (age=fage; age<=AGESUP; age++){
                   7273:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7274:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7275:        }
                   7276:      } /* end i status */
                   7277:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7278:        for (age=1; age<=AGESUP; age++){
                   7279:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7280:         mobaverage[(int)age][i][cptcod]=0.;
                   7281:        }
                   7282:      }
                   7283:    }/* end cptcod */
                   7284:    free_vector(sumnewm,1, ncovcombmax);
                   7285:    free_vector(sumnewp,1, ncovcombmax);
                   7286:    free_vector(agemaxgood,1, ncovcombmax);
                   7287:    free_vector(agemingood,1, ncovcombmax);
                   7288:    return 0;
                   7289:  }/* End movingaverage */
1.218     brouard  7290:  
1.126     brouard  7291: 
                   7292: /************** Forecasting ******************/
1.235     brouard  7293:  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  7294:   /* proj1, year, month, day of starting projection 
                   7295:      agemin, agemax range of age
                   7296:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7297:      anproj2 year of en of projection (same day and month as proj1).
                   7298:   */
1.235     brouard  7299:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7300:   double agec; /* generic age */
                   7301:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7302:   double *popeffectif,*popcount;
                   7303:   double ***p3mat;
1.218     brouard  7304:   /* double ***mobaverage; */
1.126     brouard  7305:   char fileresf[FILENAMELENGTH];
                   7306: 
                   7307:   agelim=AGESUP;
1.211     brouard  7308:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7309:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7310:      We still use firstpass and lastpass as another selection.
                   7311:   */
1.214     brouard  7312:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7313:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7314:  
1.201     brouard  7315:   strcpy(fileresf,"F_"); 
                   7316:   strcat(fileresf,fileresu);
1.126     brouard  7317:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7318:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7319:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7320:   }
1.235     brouard  7321:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7322:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7323: 
1.225     brouard  7324:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7325: 
                   7326: 
                   7327:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7328:   if (stepm<=12) stepsize=1;
                   7329:   if(estepm < stepm){
                   7330:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7331:   }
                   7332:   else  hstepm=estepm;   
                   7333: 
                   7334:   hstepm=hstepm/stepm; 
                   7335:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7336:                                fractional in yp1 */
                   7337:   anprojmean=yp;
                   7338:   yp2=modf((yp1*12),&yp);
                   7339:   mprojmean=yp;
                   7340:   yp1=modf((yp2*30.5),&yp);
                   7341:   jprojmean=yp;
                   7342:   if(jprojmean==0) jprojmean=1;
                   7343:   if(mprojmean==0) jprojmean=1;
                   7344: 
1.227     brouard  7345:   i1=pow(2,cptcoveff);
1.126     brouard  7346:   if (cptcovn < 1){i1=1;}
                   7347:   
                   7348:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7349:   
                   7350:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7351:   
1.126     brouard  7352: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7353:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7354:   for(k=1; k<=i1;k++){
                   7355:     if(TKresult[nres]!= k)
                   7356:       continue;
1.227     brouard  7357:     if(invalidvarcomb[k]){
                   7358:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7359:       continue;
                   7360:     }
                   7361:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7362:     for(j=1;j<=cptcoveff;j++) {
                   7363:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7364:     }
1.235     brouard  7365:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7366:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7367:     }
1.227     brouard  7368:     fprintf(ficresf," yearproj age");
                   7369:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7370:       for(i=1; i<=nlstate;i++)               
                   7371:        fprintf(ficresf," p%d%d",i,j);
                   7372:       fprintf(ficresf," wp.%d",j);
                   7373:     }
                   7374:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7375:       fprintf(ficresf,"\n");
                   7376:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7377:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7378:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7379:        nhstepm = nhstepm/hstepm; 
                   7380:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7381:        oldm=oldms;savm=savms;
1.235     brouard  7382:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7383:        
                   7384:        for (h=0; h<=nhstepm; h++){
                   7385:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7386:            fprintf(ficresf,"\n");
                   7387:            for(j=1;j<=cptcoveff;j++) 
                   7388:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7389:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7390:          } 
                   7391:          for(j=1; j<=nlstate+ndeath;j++) {
                   7392:            ppij=0.;
                   7393:            for(i=1; i<=nlstate;i++) {
                   7394:              if (mobilav==1) 
                   7395:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7396:              else {
                   7397:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7398:              }
                   7399:              if (h*hstepm/YEARM*stepm== yearp) {
                   7400:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7401:              }
                   7402:            } /* end i */
                   7403:            if (h*hstepm/YEARM*stepm==yearp) {
                   7404:              fprintf(ficresf," %.3f", ppij);
                   7405:            }
                   7406:          }/* end j */
                   7407:        } /* end h */
                   7408:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7409:       } /* end agec */
                   7410:     } /* end yearp */
                   7411:   } /* end  k */
1.219     brouard  7412:        
1.126     brouard  7413:   fclose(ficresf);
1.215     brouard  7414:   printf("End of Computing forecasting \n");
                   7415:   fprintf(ficlog,"End of Computing forecasting\n");
                   7416: 
1.126     brouard  7417: }
                   7418: 
1.218     brouard  7419: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7420: /* 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  7421: /*   /\* back1, year, month, day of starting backection  */
                   7422: /*      agemin, agemax range of age */
                   7423: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7424: /*      anback2 year of en of backection (same day and month as back1). */
                   7425: /*   *\/ */
                   7426: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7427: /*   double agec; /\* generic age *\/ */
                   7428: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7429: /*   double *popeffectif,*popcount; */
                   7430: /*   double ***p3mat; */
                   7431: /*   /\* double ***mobaverage; *\/ */
                   7432: /*   char fileresfb[FILENAMELENGTH]; */
                   7433:        
                   7434: /*   agelim=AGESUP; */
                   7435: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7436: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7437: /*      We still use firstpass and lastpass as another selection. */
                   7438: /*   *\/ */
                   7439: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7440: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7441: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7442:        
                   7443: /*   strcpy(fileresfb,"FB_");  */
                   7444: /*   strcat(fileresfb,fileresu); */
                   7445: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7446: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7447: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7448: /*   } */
                   7449: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7450: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7451:        
1.225     brouard  7452: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7453:        
                   7454: /*   /\* if (mobilav!=0) { *\/ */
                   7455: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7456: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7457: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7458: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7459: /*   /\*   } *\/ */
                   7460: /*   /\* } *\/ */
                   7461:        
                   7462: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7463: /*   if (stepm<=12) stepsize=1; */
                   7464: /*   if(estepm < stepm){ */
                   7465: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7466: /*   } */
                   7467: /*   else  hstepm=estepm;    */
                   7468:        
                   7469: /*   hstepm=hstepm/stepm;  */
                   7470: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7471: /*                                fractional in yp1 *\/ */
                   7472: /*   anprojmean=yp; */
                   7473: /*   yp2=modf((yp1*12),&yp); */
                   7474: /*   mprojmean=yp; */
                   7475: /*   yp1=modf((yp2*30.5),&yp); */
                   7476: /*   jprojmean=yp; */
                   7477: /*   if(jprojmean==0) jprojmean=1; */
                   7478: /*   if(mprojmean==0) jprojmean=1; */
                   7479:        
1.225     brouard  7480: /*   i1=cptcoveff; */
1.218     brouard  7481: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7482:   
1.218     brouard  7483: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7484:   
1.218     brouard  7485: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7486:        
                   7487: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7488: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7489: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7490: /*       k=k+1; */
                   7491: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7492: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7493: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7494: /*       } */
                   7495: /*       fprintf(ficresfb," yearbproj age"); */
                   7496: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7497: /*                             for(i=1; i<=nlstate;i++)               */
                   7498: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7499: /*                             fprintf(ficresfb," p.%d",j); */
                   7500: /*       } */
                   7501: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7502: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7503: /*                             fprintf(ficresfb,"\n"); */
                   7504: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7505: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7506: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7507: /*                                     nhstepm = nhstepm/hstepm;  */
                   7508: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7509: /*                                     oldm=oldms;savm=savms; */
                   7510: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7511: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7512: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7513: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7514: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7515: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7516: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7517: /*                                             }  */
                   7518: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7519: /*                                                     ppij=0.; */
                   7520: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7521: /*                                                             if (mobilav==1)  */
                   7522: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7523: /*                                                             else { */
                   7524: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7525: /*                                                             } */
                   7526: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7527: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7528: /*                                                             } */
                   7529: /*                                                     } /\* end i *\/ */
                   7530: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7531: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7532: /*                                                     } */
                   7533: /*                                             }/\* end j *\/ */
                   7534: /*                                     } /\* end h *\/ */
                   7535: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7536: /*                             } /\* end agec *\/ */
                   7537: /*       } /\* end yearp *\/ */
                   7538: /*     } /\* end cptcod *\/ */
                   7539: /*   } /\* end  cptcov *\/ */
                   7540:        
                   7541: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7542:        
                   7543: /*   fclose(ficresfb); */
                   7544: /*   printf("End of Computing Back forecasting \n"); */
                   7545: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7546:        
1.218     brouard  7547: /* } */
1.217     brouard  7548: 
1.126     brouard  7549: /************** Forecasting *****not tested NB*************/
1.227     brouard  7550: /* 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  7551:   
1.227     brouard  7552: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7553: /*   int *popage; */
                   7554: /*   double calagedatem, agelim, kk1, kk2; */
                   7555: /*   double *popeffectif,*popcount; */
                   7556: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7557: /*   /\* double ***mobaverage; *\/ */
                   7558: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7559: 
1.227     brouard  7560: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7561: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7562: /*   agelim=AGESUP; */
                   7563: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7564:   
1.227     brouard  7565: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7566:   
                   7567:   
1.227     brouard  7568: /*   strcpy(filerespop,"POP_");  */
                   7569: /*   strcat(filerespop,fileresu); */
                   7570: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7571: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7572: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7573: /*   } */
                   7574: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7575: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7576: 
1.227     brouard  7577: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7578: 
1.227     brouard  7579: /*   /\* if (mobilav!=0) { *\/ */
                   7580: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7581: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7582: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7583: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7584: /*   /\*   } *\/ */
                   7585: /*   /\* } *\/ */
1.126     brouard  7586: 
1.227     brouard  7587: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7588: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7589:   
1.227     brouard  7590: /*   agelim=AGESUP; */
1.126     brouard  7591:   
1.227     brouard  7592: /*   hstepm=1; */
                   7593: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7594:        
1.227     brouard  7595: /*   if (popforecast==1) { */
                   7596: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7597: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7598: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7599: /*     }  */
                   7600: /*     popage=ivector(0,AGESUP); */
                   7601: /*     popeffectif=vector(0,AGESUP); */
                   7602: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7603:     
1.227     brouard  7604: /*     i=1;    */
                   7605: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7606:     
1.227     brouard  7607: /*     imx=i; */
                   7608: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7609: /*   } */
1.218     brouard  7610:   
1.227     brouard  7611: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7612: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7613: /*       k=k+1; */
                   7614: /*       fprintf(ficrespop,"\n#******"); */
                   7615: /*       for(j=1;j<=cptcoveff;j++) { */
                   7616: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7617: /*       } */
                   7618: /*       fprintf(ficrespop,"******\n"); */
                   7619: /*       fprintf(ficrespop,"# Age"); */
                   7620: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7621: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7622:       
1.227     brouard  7623: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7624: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7625:        
1.227     brouard  7626: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7627: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7628: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7629:          
1.227     brouard  7630: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7631: /*       oldm=oldms;savm=savms; */
                   7632: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7633:          
1.227     brouard  7634: /*       for (h=0; h<=nhstepm; h++){ */
                   7635: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7636: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7637: /*         }  */
                   7638: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7639: /*           kk1=0.;kk2=0; */
                   7640: /*           for(i=1; i<=nlstate;i++) {               */
                   7641: /*             if (mobilav==1)  */
                   7642: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7643: /*             else { */
                   7644: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7645: /*             } */
                   7646: /*           } */
                   7647: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7648: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7649: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7650: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7651: /*           } */
                   7652: /*         } */
                   7653: /*         for(i=1; i<=nlstate;i++){ */
                   7654: /*           kk1=0.; */
                   7655: /*           for(j=1; j<=nlstate;j++){ */
                   7656: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7657: /*           } */
                   7658: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7659: /*         } */
1.218     brouard  7660:            
1.227     brouard  7661: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7662: /*           for(j=1; j<=nlstate;j++)  */
                   7663: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7664: /*       } */
                   7665: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7666: /*     } */
                   7667: /*       } */
1.218     brouard  7668:       
1.227     brouard  7669: /*       /\******\/ */
1.218     brouard  7670:       
1.227     brouard  7671: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7672: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7673: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7674: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7675: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7676:          
1.227     brouard  7677: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7678: /*       oldm=oldms;savm=savms; */
                   7679: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7680: /*       for (h=0; h<=nhstepm; h++){ */
                   7681: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7682: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7683: /*         }  */
                   7684: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7685: /*           kk1=0.;kk2=0; */
                   7686: /*           for(i=1; i<=nlstate;i++) {               */
                   7687: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7688: /*           } */
                   7689: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7690: /*         } */
                   7691: /*       } */
                   7692: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7693: /*     } */
                   7694: /*       } */
                   7695: /*     }  */
                   7696: /*   } */
1.218     brouard  7697:   
1.227     brouard  7698: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7699:   
1.227     brouard  7700: /*   if (popforecast==1) { */
                   7701: /*     free_ivector(popage,0,AGESUP); */
                   7702: /*     free_vector(popeffectif,0,AGESUP); */
                   7703: /*     free_vector(popcount,0,AGESUP); */
                   7704: /*   } */
                   7705: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7706: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7707: /*   fclose(ficrespop); */
                   7708: /* } /\* End of popforecast *\/ */
1.218     brouard  7709:  
1.126     brouard  7710: int fileappend(FILE *fichier, char *optionfich)
                   7711: {
                   7712:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7713:     printf("Problem with file: %s\n", optionfich);
                   7714:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7715:     return (0);
                   7716:   }
                   7717:   fflush(fichier);
                   7718:   return (1);
                   7719: }
                   7720: 
                   7721: 
                   7722: /**************** function prwizard **********************/
                   7723: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7724: {
                   7725: 
                   7726:   /* Wizard to print covariance matrix template */
                   7727: 
1.164     brouard  7728:   char ca[32], cb[32];
                   7729:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7730:   int numlinepar;
                   7731: 
                   7732:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7733:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7734:   for(i=1; i <=nlstate; i++){
                   7735:     jj=0;
                   7736:     for(j=1; j <=nlstate+ndeath; j++){
                   7737:       if(j==i) continue;
                   7738:       jj++;
                   7739:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7740:       printf("%1d%1d",i,j);
                   7741:       fprintf(ficparo,"%1d%1d",i,j);
                   7742:       for(k=1; k<=ncovmodel;k++){
                   7743:        /*        printf(" %lf",param[i][j][k]); */
                   7744:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7745:        printf(" 0.");
                   7746:        fprintf(ficparo," 0.");
                   7747:       }
                   7748:       printf("\n");
                   7749:       fprintf(ficparo,"\n");
                   7750:     }
                   7751:   }
                   7752:   printf("# Scales (for hessian or gradient estimation)\n");
                   7753:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7754:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7755:   for(i=1; i <=nlstate; i++){
                   7756:     jj=0;
                   7757:     for(j=1; j <=nlstate+ndeath; j++){
                   7758:       if(j==i) continue;
                   7759:       jj++;
                   7760:       fprintf(ficparo,"%1d%1d",i,j);
                   7761:       printf("%1d%1d",i,j);
                   7762:       fflush(stdout);
                   7763:       for(k=1; k<=ncovmodel;k++){
                   7764:        /*      printf(" %le",delti3[i][j][k]); */
                   7765:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7766:        printf(" 0.");
                   7767:        fprintf(ficparo," 0.");
                   7768:       }
                   7769:       numlinepar++;
                   7770:       printf("\n");
                   7771:       fprintf(ficparo,"\n");
                   7772:     }
                   7773:   }
                   7774:   printf("# Covariance matrix\n");
                   7775: /* # 121 Var(a12)\n\ */
                   7776: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7777: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7778: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7779: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7780: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7781: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7782: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7783:   fflush(stdout);
                   7784:   fprintf(ficparo,"# Covariance matrix\n");
                   7785:   /* # 121 Var(a12)\n\ */
                   7786:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7787:   /* #   ...\n\ */
                   7788:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7789:   
                   7790:   for(itimes=1;itimes<=2;itimes++){
                   7791:     jj=0;
                   7792:     for(i=1; i <=nlstate; i++){
                   7793:       for(j=1; j <=nlstate+ndeath; j++){
                   7794:        if(j==i) continue;
                   7795:        for(k=1; k<=ncovmodel;k++){
                   7796:          jj++;
                   7797:          ca[0]= k+'a'-1;ca[1]='\0';
                   7798:          if(itimes==1){
                   7799:            printf("#%1d%1d%d",i,j,k);
                   7800:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7801:          }else{
                   7802:            printf("%1d%1d%d",i,j,k);
                   7803:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7804:            /*  printf(" %.5le",matcov[i][j]); */
                   7805:          }
                   7806:          ll=0;
                   7807:          for(li=1;li <=nlstate; li++){
                   7808:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7809:              if(lj==li) continue;
                   7810:              for(lk=1;lk<=ncovmodel;lk++){
                   7811:                ll++;
                   7812:                if(ll<=jj){
                   7813:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7814:                  if(ll<jj){
                   7815:                    if(itimes==1){
                   7816:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7817:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7818:                    }else{
                   7819:                      printf(" 0.");
                   7820:                      fprintf(ficparo," 0.");
                   7821:                    }
                   7822:                  }else{
                   7823:                    if(itimes==1){
                   7824:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7825:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7826:                    }else{
                   7827:                      printf(" 0.");
                   7828:                      fprintf(ficparo," 0.");
                   7829:                    }
                   7830:                  }
                   7831:                }
                   7832:              } /* end lk */
                   7833:            } /* end lj */
                   7834:          } /* end li */
                   7835:          printf("\n");
                   7836:          fprintf(ficparo,"\n");
                   7837:          numlinepar++;
                   7838:        } /* end k*/
                   7839:       } /*end j */
                   7840:     } /* end i */
                   7841:   } /* end itimes */
                   7842: 
                   7843: } /* end of prwizard */
                   7844: /******************* Gompertz Likelihood ******************************/
                   7845: double gompertz(double x[])
                   7846: { 
                   7847:   double A,B,L=0.0,sump=0.,num=0.;
                   7848:   int i,n=0; /* n is the size of the sample */
                   7849: 
1.220     brouard  7850:   for (i=1;i<=imx ; i++) {
1.126     brouard  7851:     sump=sump+weight[i];
                   7852:     /*    sump=sump+1;*/
                   7853:     num=num+1;
                   7854:   }
                   7855:  
                   7856:  
                   7857:   /* for (i=0; i<=imx; i++) 
                   7858:      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]);*/
                   7859: 
                   7860:   for (i=1;i<=imx ; i++)
                   7861:     {
                   7862:       if (cens[i] == 1 && wav[i]>1)
                   7863:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7864:       
                   7865:       if (cens[i] == 0 && wav[i]>1)
                   7866:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7867:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7868:       
                   7869:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7870:       if (wav[i] > 1 ) { /* ??? */
                   7871:        L=L+A*weight[i];
                   7872:        /*      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]);*/
                   7873:       }
                   7874:     }
                   7875: 
                   7876:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7877:  
                   7878:   return -2*L*num/sump;
                   7879: }
                   7880: 
1.136     brouard  7881: #ifdef GSL
                   7882: /******************* Gompertz_f Likelihood ******************************/
                   7883: double gompertz_f(const gsl_vector *v, void *params)
                   7884: { 
                   7885:   double A,B,LL=0.0,sump=0.,num=0.;
                   7886:   double *x= (double *) v->data;
                   7887:   int i,n=0; /* n is the size of the sample */
                   7888: 
                   7889:   for (i=0;i<=imx-1 ; i++) {
                   7890:     sump=sump+weight[i];
                   7891:     /*    sump=sump+1;*/
                   7892:     num=num+1;
                   7893:   }
                   7894:  
                   7895:  
                   7896:   /* for (i=0; i<=imx; i++) 
                   7897:      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]);*/
                   7898:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7899:   for (i=1;i<=imx ; i++)
                   7900:     {
                   7901:       if (cens[i] == 1 && wav[i]>1)
                   7902:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7903:       
                   7904:       if (cens[i] == 0 && wav[i]>1)
                   7905:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7906:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7907:       
                   7908:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7909:       if (wav[i] > 1 ) { /* ??? */
                   7910:        LL=LL+A*weight[i];
                   7911:        /*      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]);*/
                   7912:       }
                   7913:     }
                   7914: 
                   7915:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7916:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7917:  
                   7918:   return -2*LL*num/sump;
                   7919: }
                   7920: #endif
                   7921: 
1.126     brouard  7922: /******************* Printing html file ***********/
1.201     brouard  7923: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7924:                  int lastpass, int stepm, int weightopt, char model[],\
                   7925:                  int imx,  double p[],double **matcov,double agemortsup){
                   7926:   int i,k;
                   7927: 
                   7928:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7929:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7930:   for (i=1;i<=2;i++) 
                   7931:     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  7932:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7933:   fprintf(fichtm,"</ul>");
                   7934: 
                   7935: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7936: 
                   7937:  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>");
                   7938: 
                   7939:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7940:    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]);
                   7941: 
                   7942:  
                   7943:   fflush(fichtm);
                   7944: }
                   7945: 
                   7946: /******************* Gnuplot file **************/
1.201     brouard  7947: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7948: 
                   7949:   char dirfileres[132],optfileres[132];
1.164     brouard  7950: 
1.126     brouard  7951:   int ng;
                   7952: 
                   7953: 
                   7954:   /*#ifdef windows */
                   7955:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7956:     /*#endif */
                   7957: 
                   7958: 
                   7959:   strcpy(dirfileres,optionfilefiname);
                   7960:   strcpy(optfileres,"vpl");
1.199     brouard  7961:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7962:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7963:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7964:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7965:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7966: 
                   7967: } 
                   7968: 
1.136     brouard  7969: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7970: {
1.126     brouard  7971: 
1.136     brouard  7972:   /*-------- data file ----------*/
                   7973:   FILE *fic;
                   7974:   char dummy[]="                         ";
1.240     brouard  7975:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  7976:   int lstra;
1.136     brouard  7977:   int linei, month, year,iout;
                   7978:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7979:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7980:   char *stratrunc;
1.223     brouard  7981: 
1.240     brouard  7982:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   7983:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  7984: 
1.240     brouard  7985:   for(v=1; v <=ncovcol;v++){
                   7986:     DummyV[v]=0;
                   7987:     FixedV[v]=0;
                   7988:   }
                   7989:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   7990:     DummyV[v]=1;
                   7991:     FixedV[v]=0;
                   7992:   }
                   7993:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   7994:     DummyV[v]=0;
                   7995:     FixedV[v]=1;
                   7996:   }
                   7997:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7998:     DummyV[v]=1;
                   7999:     FixedV[v]=1;
                   8000:   }
                   8001:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   8002:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   8003:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   8004:   }
1.126     brouard  8005: 
1.136     brouard  8006:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  8007:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   8008:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  8009:   }
1.126     brouard  8010: 
1.136     brouard  8011:   i=1;
                   8012:   linei=0;
                   8013:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   8014:     linei=linei+1;
                   8015:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   8016:       if(line[j] == '\t')
                   8017:        line[j] = ' ';
                   8018:     }
                   8019:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   8020:       ;
                   8021:     };
                   8022:     line[j+1]=0;  /* Trims blanks at end of line */
                   8023:     if(line[0]=='#'){
                   8024:       fprintf(ficlog,"Comment line\n%s\n",line);
                   8025:       printf("Comment line\n%s\n",line);
                   8026:       continue;
                   8027:     }
                   8028:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  8029:     strcpy(line, linetmp);
1.223     brouard  8030:     
                   8031:     /* Loops on waves */
                   8032:     for (j=maxwav;j>=1;j--){
                   8033:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  8034:        cutv(stra, strb, line, ' '); 
                   8035:        if(strb[0]=='.') { /* Missing value */
                   8036:          lval=-1;
                   8037:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   8038:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   8039:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   8040:            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);
                   8041:            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);
                   8042:            return 1;
                   8043:          }
                   8044:        }else{
                   8045:          errno=0;
                   8046:          /* what_kind_of_number(strb); */
                   8047:          dval=strtod(strb,&endptr); 
                   8048:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   8049:          /* if(strb != endptr && *endptr == '\0') */
                   8050:          /*    dval=dlval; */
                   8051:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8052:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8053:            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);
                   8054:            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);
                   8055:            return 1;
                   8056:          }
                   8057:          cotqvar[j][iv][i]=dval; 
                   8058:          cotvar[j][ntv+iv][i]=dval; 
                   8059:        }
                   8060:        strcpy(line,stra);
1.223     brouard  8061:       }/* end loop ntqv */
1.225     brouard  8062:       
1.223     brouard  8063:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  8064:        cutv(stra, strb, line, ' '); 
                   8065:        if(strb[0]=='.') { /* Missing value */
                   8066:          lval=-1;
                   8067:        }else{
                   8068:          errno=0;
                   8069:          lval=strtol(strb,&endptr,10); 
                   8070:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8071:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8072:            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);
                   8073:            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);
                   8074:            return 1;
                   8075:          }
                   8076:        }
                   8077:        if(lval <-1 || lval >1){
                   8078:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8079:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8080:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8081:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8082:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8083:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8084:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8085:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8086:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8087:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8088:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8089:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8090:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8091:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8092:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8093:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8094:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8095:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8096:          return 1;
                   8097:        }
                   8098:        cotvar[j][iv][i]=(double)(lval);
                   8099:        strcpy(line,stra);
1.223     brouard  8100:       }/* end loop ntv */
1.225     brouard  8101:       
1.223     brouard  8102:       /* Statuses  at wave */
1.137     brouard  8103:       cutv(stra, strb, line, ' '); 
1.223     brouard  8104:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8105:        lval=-1;
1.136     brouard  8106:       }else{
1.238     brouard  8107:        errno=0;
                   8108:        lval=strtol(strb,&endptr,10); 
                   8109:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8110:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8111:          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);
                   8112:          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);
                   8113:          return 1;
                   8114:        }
1.136     brouard  8115:       }
1.225     brouard  8116:       
1.136     brouard  8117:       s[j][i]=lval;
1.225     brouard  8118:       
1.223     brouard  8119:       /* Date of Interview */
1.136     brouard  8120:       strcpy(line,stra);
                   8121:       cutv(stra, strb,line,' ');
1.169     brouard  8122:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8123:       }
1.169     brouard  8124:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8125:        month=99;
                   8126:        year=9999;
1.136     brouard  8127:       }else{
1.225     brouard  8128:        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);
                   8129:        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);
                   8130:        return 1;
1.136     brouard  8131:       }
                   8132:       anint[j][i]= (double) year; 
                   8133:       mint[j][i]= (double)month; 
                   8134:       strcpy(line,stra);
1.223     brouard  8135:     } /* End loop on waves */
1.225     brouard  8136:     
1.223     brouard  8137:     /* Date of death */
1.136     brouard  8138:     cutv(stra, strb,line,' '); 
1.169     brouard  8139:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8140:     }
1.169     brouard  8141:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8142:       month=99;
                   8143:       year=9999;
                   8144:     }else{
1.141     brouard  8145:       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  8146:       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);
                   8147:       return 1;
1.136     brouard  8148:     }
                   8149:     andc[i]=(double) year; 
                   8150:     moisdc[i]=(double) month; 
                   8151:     strcpy(line,stra);
                   8152:     
1.223     brouard  8153:     /* Date of birth */
1.136     brouard  8154:     cutv(stra, strb,line,' '); 
1.169     brouard  8155:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8156:     }
1.169     brouard  8157:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8158:       month=99;
                   8159:       year=9999;
                   8160:     }else{
1.141     brouard  8161:       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);
                   8162:       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  8163:       return 1;
1.136     brouard  8164:     }
                   8165:     if (year==9999) {
1.141     brouard  8166:       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);
                   8167:       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  8168:       return 1;
                   8169:       
1.136     brouard  8170:     }
                   8171:     annais[i]=(double)(year);
                   8172:     moisnais[i]=(double)(month); 
                   8173:     strcpy(line,stra);
1.225     brouard  8174:     
1.223     brouard  8175:     /* Sample weight */
1.136     brouard  8176:     cutv(stra, strb,line,' '); 
                   8177:     errno=0;
                   8178:     dval=strtod(strb,&endptr); 
                   8179:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8180:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8181:       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  8182:       fflush(ficlog);
                   8183:       return 1;
                   8184:     }
                   8185:     weight[i]=dval; 
                   8186:     strcpy(line,stra);
1.225     brouard  8187:     
1.223     brouard  8188:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8189:       cutv(stra, strb, line, ' '); 
                   8190:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8191:        lval=-1;
1.223     brouard  8192:       }else{
1.225     brouard  8193:        errno=0;
                   8194:        /* what_kind_of_number(strb); */
                   8195:        dval=strtod(strb,&endptr);
                   8196:        /* if(strb != endptr && *endptr == '\0') */
                   8197:        /*   dval=dlval; */
                   8198:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8199:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8200:          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);
                   8201:          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);
                   8202:          return 1;
                   8203:        }
                   8204:        coqvar[iv][i]=dval; 
1.226     brouard  8205:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8206:       }
                   8207:       strcpy(line,stra);
                   8208:     }/* end loop nqv */
1.136     brouard  8209:     
1.223     brouard  8210:     /* Covariate values */
1.136     brouard  8211:     for (j=ncovcol;j>=1;j--){
                   8212:       cutv(stra, strb,line,' '); 
1.223     brouard  8213:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8214:        lval=-1;
1.136     brouard  8215:       }else{
1.225     brouard  8216:        errno=0;
                   8217:        lval=strtol(strb,&endptr,10); 
                   8218:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8219:          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);
                   8220:          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);
                   8221:          return 1;
                   8222:        }
1.136     brouard  8223:       }
                   8224:       if(lval <-1 || lval >1){
1.225     brouard  8225:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8226:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8227:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8228:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8229:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8230:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8231:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8232:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8233:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8234:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8235:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8236:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8237:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8238:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8239:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8240:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8241:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8242:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8243:        return 1;
1.136     brouard  8244:       }
                   8245:       covar[j][i]=(double)(lval);
                   8246:       strcpy(line,stra);
                   8247:     }  
                   8248:     lstra=strlen(stra);
1.225     brouard  8249:     
1.136     brouard  8250:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8251:       stratrunc = &(stra[lstra-9]);
                   8252:       num[i]=atol(stratrunc);
                   8253:     }
                   8254:     else
                   8255:       num[i]=atol(stra);
                   8256:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8257:       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;}*/
                   8258:     
                   8259:     i=i+1;
                   8260:   } /* End loop reading  data */
1.225     brouard  8261:   
1.136     brouard  8262:   *imax=i-1; /* Number of individuals */
                   8263:   fclose(fic);
1.225     brouard  8264:   
1.136     brouard  8265:   return (0);
1.164     brouard  8266:   /* endread: */
1.225     brouard  8267:   printf("Exiting readdata: ");
                   8268:   fclose(fic);
                   8269:   return (1);
1.223     brouard  8270: }
1.126     brouard  8271: 
1.234     brouard  8272: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8273:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8274:   while (*p2 == ' ')
1.234     brouard  8275:     p2++; 
                   8276:   /* while ((*p1++ = *p2++) !=0) */
                   8277:   /*   ; */
                   8278:   /* do */
                   8279:   /*   while (*p2 == ' ') */
                   8280:   /*     p2++; */
                   8281:   /* while (*p1++ == *p2++); */
                   8282:   *stri=p2; 
1.145     brouard  8283: }
                   8284: 
1.235     brouard  8285: int decoderesult ( char resultline[], int nres)
1.230     brouard  8286: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8287: {
1.235     brouard  8288:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8289:   char resultsav[MAXLINE];
1.234     brouard  8290:   int resultmodel[MAXLINE];
                   8291:   int modelresult[MAXLINE];
1.230     brouard  8292:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8293: 
1.234     brouard  8294:   removefirstspace(&resultline);
1.233     brouard  8295:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8296: 
                   8297:   if (strstr(resultline,"v") !=0){
                   8298:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8299:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8300:     return 1;
                   8301:   }
                   8302:   trimbb(resultsav, resultline);
                   8303:   if (strlen(resultsav) >1){
                   8304:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8305:   }
1.234     brouard  8306:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8307:     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);
                   8308:     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);
                   8309:   }
                   8310:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8311:     if(nbocc(resultsav,'=') >1){
                   8312:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8313:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8314:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8315:     }else
                   8316:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8317:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8318:     
1.230     brouard  8319:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8320:     Tvarsel[k]=atoi(strc);
                   8321:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8322:     /* cptcovsel++;     */
                   8323:     if (nbocc(stra,'=') >0)
                   8324:       strcpy(resultsav,stra); /* and analyzes it */
                   8325:   }
1.235     brouard  8326:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8327:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8328:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8329:       match=0;
1.236     brouard  8330:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8331:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8332:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8333:          match=1;
                   8334:          break;
                   8335:        }
                   8336:       }
                   8337:       if(match == 0){
                   8338:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8339:       }
                   8340:     }
                   8341:   }
1.235     brouard  8342:   /* Checking for missing or useless values in comparison of current model needs */
                   8343:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8344:     match=0;
1.235     brouard  8345:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8346:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8347:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8348:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8349:          ++match;
                   8350:        }
                   8351:       }
                   8352:     }
                   8353:     if(match == 0){
                   8354:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8355:     }else if(match > 1){
                   8356:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8357:     }
                   8358:   }
1.235     brouard  8359:       
1.234     brouard  8360:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8361:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8362:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8363:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8364:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8365:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8366:   /*    1 0 0 0 */
                   8367:   /*    2 1 0 0 */
                   8368:   /*    3 0 1 0 */ 
                   8369:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8370:   /*    5 0 0 1 */
                   8371:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8372:   /*    7 0 1 1 */
                   8373:   /*    8 1 1 1 */
1.237     brouard  8374:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8375:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8376:   /* V5*age V5 known which value for nres?  */
                   8377:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8378:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8379:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8380:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8381:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8382:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8383:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8384:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8385:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8386:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8387:       k4++;;
                   8388:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8389:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8390:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8391:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8392:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8393:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8394:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8395:       k4q++;;
                   8396:     }
                   8397:   }
1.234     brouard  8398:   
1.235     brouard  8399:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8400:   return (0);
                   8401: }
1.235     brouard  8402: 
1.230     brouard  8403: int decodemodel( char model[], int lastobs)
                   8404:  /**< This routine decodes the model and returns:
1.224     brouard  8405:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8406:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8407:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8408:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8409:        * - cptcovage number of covariates with age*products =2
                   8410:        * - cptcovs number of simple covariates
                   8411:        * - 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
                   8412:        *     which is a new column after the 9 (ncovcol) variables. 
                   8413:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8414:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8415:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8416:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8417:        */
1.136     brouard  8418: {
1.238     brouard  8419:   int i, j, k, ks, v;
1.227     brouard  8420:   int  j1, k1, k2, k3, k4;
1.136     brouard  8421:   char modelsav[80];
1.145     brouard  8422:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8423:   char *strpt;
1.136     brouard  8424: 
1.145     brouard  8425:   /*removespace(model);*/
1.136     brouard  8426:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8427:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8428:     if (strstr(model,"AGE") !=0){
1.192     brouard  8429:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8430:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8431:       return 1;
                   8432:     }
1.141     brouard  8433:     if (strstr(model,"v") !=0){
                   8434:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8435:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8436:       return 1;
                   8437:     }
1.187     brouard  8438:     strcpy(modelsav,model); 
                   8439:     if ((strpt=strstr(model,"age*age")) !=0){
                   8440:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8441:       if(strpt != model){
1.234     brouard  8442:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8443:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8444:  corresponding column of parameters.\n",model);
1.234     brouard  8445:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8446:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8447:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8448:        return 1;
1.225     brouard  8449:       }
1.187     brouard  8450:       nagesqr=1;
                   8451:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8452:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8453:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8454:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8455:       else 
1.234     brouard  8456:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8457:     }else
                   8458:       nagesqr=0;
                   8459:     if (strlen(modelsav) >1){
                   8460:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8461:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8462:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8463:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8464:                     * cst, age and age*age 
                   8465:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8466:       /* including age products which are counted in cptcovage.
                   8467:        * but the covariates which are products must be treated 
                   8468:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8469:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8470:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8471:       
                   8472:       
1.187     brouard  8473:       /*   Design
                   8474:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8475:        *  <          ncovcol=8                >
                   8476:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8477:        *   k=  1    2      3       4     5       6      7        8
                   8478:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8479:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8480:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8481:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8482:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8483:        *  Tage[++cptcovage]=k
                   8484:        *       if products, new covar are created after ncovcol with k1
                   8485:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8486:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8487:        *  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
                   8488:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8489:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8490:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8491:        *  <          ncovcol=8                >
                   8492:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8493:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8494:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8495:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8496:        * p Tprod[1]@2={                         6, 5}
                   8497:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8498:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8499:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8500:        *How to reorganize?
                   8501:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8502:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8503:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8504:        * Struct []
                   8505:        */
1.225     brouard  8506:       
1.187     brouard  8507:       /* This loop fills the array Tvar from the string 'model'.*/
                   8508:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8509:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8510:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8511:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8512:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8513:       /*       k=1 Tvar[1]=2 (from V2) */
                   8514:       /*       k=5 Tvar[5] */
                   8515:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8516:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8517:       /*       } */
1.198     brouard  8518:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8519:       /*
                   8520:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8521:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8522:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8523:       }
1.187     brouard  8524:       cptcovage=0;
                   8525:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8526:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8527:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8528:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8529:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8530:        /*scanf("%d",i);*/
                   8531:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8532:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8533:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8534:            /* covar is not filled and then is empty */
                   8535:            cptcovprod--;
                   8536:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8537:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8538:            Typevar[k]=1;  /* 1 for age product */
                   8539:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8540:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8541:            /*printf("stre=%s ", stre);*/
                   8542:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8543:            cptcovprod--;
                   8544:            cutl(stre,strb,strc,'V');
                   8545:            Tvar[k]=atoi(stre);
                   8546:            Typevar[k]=1;  /* 1 for age product */
                   8547:            cptcovage++;
                   8548:            Tage[cptcovage]=k;
                   8549:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8550:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8551:            cptcovn++;
                   8552:            cptcovprodnoage++;k1++;
                   8553:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8554:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8555:                                                because this model-covariate is a construction we invent a new column
                   8556:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8557:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8558:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8559:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8560:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8561:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8562:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8563:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8564:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8565:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8566:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8567:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8568:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8569:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8570:            for (i=1; i<=lastobs;i++){
                   8571:              /* Computes the new covariate which is a product of
                   8572:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8573:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8574:            }
                   8575:          } /* End age is not in the model */
                   8576:        } /* End if model includes a product */
                   8577:        else { /* no more sum */
                   8578:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8579:          /*  scanf("%d",i);*/
                   8580:          cutl(strd,strc,strb,'V');
                   8581:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8582:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8583:          Tvar[k]=atoi(strd);
                   8584:          Typevar[k]=0;  /* 0 for simple covariates */
                   8585:        }
                   8586:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8587:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8588:                                  scanf("%d",i);*/
1.187     brouard  8589:       } /* end of loop + on total covariates */
                   8590:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8591:   } /* end if strlen(model == 0) */
1.136     brouard  8592:   
                   8593:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8594:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8595:   
1.136     brouard  8596:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8597:      printf("cptcovprod=%d ", cptcovprod);
                   8598:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8599:      scanf("%d ",i);*/
                   8600: 
                   8601: 
1.230     brouard  8602: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8603:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8604: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8605:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8606:    k =           1    2   3     4       5       6      7      8        9
                   8607:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8608:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8609:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8610:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8611:          Tmodelind[combination of covar]=k;
1.225     brouard  8612: */  
                   8613: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8614:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8615:   /* 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  8616:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8617:   printf("Model=%s\n\
                   8618: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8619: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8620: 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);
                   8621:   fprintf(ficlog,"Model=%s\n\
                   8622: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8623: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8624: 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);
1.240     brouard  8625:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8626:   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 */
                   8627:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8628:       Fixed[k]= 0;
                   8629:       Dummy[k]= 0;
1.225     brouard  8630:       ncoveff++;
1.232     brouard  8631:       ncovf++;
1.234     brouard  8632:       nsd++;
                   8633:       modell[k].maintype= FTYPE;
                   8634:       TvarsD[nsd]=Tvar[k];
                   8635:       TvarsDind[nsd]=k;
                   8636:       TvarF[ncovf]=Tvar[k];
                   8637:       TvarFind[ncovf]=k;
                   8638:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8639:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8640:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8641:       Fixed[k]= 0;
                   8642:       Dummy[k]= 0;
                   8643:       ncoveff++;
                   8644:       ncovf++;
                   8645:       modell[k].maintype= FTYPE;
                   8646:       TvarF[ncovf]=Tvar[k];
                   8647:       TvarFind[ncovf]=k;
1.230     brouard  8648:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8649:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8650:     }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  8651:       Fixed[k]= 0;
                   8652:       Dummy[k]= 1;
1.230     brouard  8653:       nqfveff++;
1.234     brouard  8654:       modell[k].maintype= FTYPE;
                   8655:       modell[k].subtype= FQ;
                   8656:       nsq++;
                   8657:       TvarsQ[nsq]=Tvar[k];
                   8658:       TvarsQind[nsq]=k;
1.232     brouard  8659:       ncovf++;
1.234     brouard  8660:       TvarF[ncovf]=Tvar[k];
                   8661:       TvarFind[ncovf]=k;
1.231     brouard  8662:       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  8663:       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.242     brouard  8664:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8665:       Fixed[k]= 1;
                   8666:       Dummy[k]= 0;
1.225     brouard  8667:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8668:       modell[k].maintype= VTYPE;
                   8669:       modell[k].subtype= VD;
                   8670:       nsd++;
                   8671:       TvarsD[nsd]=Tvar[k];
                   8672:       TvarsDind[nsd]=k;
                   8673:       ncovv++; /* Only simple time varying variables */
                   8674:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8675:       TvarVind[ncovv]=k; /* TvarVind[2]=2  TvarVind[3]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  8676:       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 */
                   8677:       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  8678:       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);
                   8679:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8680:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8681:       Fixed[k]= 1;
                   8682:       Dummy[k]= 1;
                   8683:       nqtveff++;
                   8684:       modell[k].maintype= VTYPE;
                   8685:       modell[k].subtype= VQ;
                   8686:       ncovv++; /* Only simple time varying variables */
                   8687:       nsq++;
                   8688:       TvarsQ[nsq]=Tvar[k];
                   8689:       TvarsQind[nsq]=k;
                   8690:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8691:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  8692:       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 */
                   8693:       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  8694:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8695:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8696:       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  8697:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8698:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8699:       ncova++;
                   8700:       TvarA[ncova]=Tvar[k];
                   8701:       TvarAind[ncova]=k;
1.231     brouard  8702:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8703:        Fixed[k]= 2;
                   8704:        Dummy[k]= 2;
                   8705:        modell[k].maintype= ATYPE;
                   8706:        modell[k].subtype= APFD;
                   8707:        /* ncoveff++; */
1.227     brouard  8708:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8709:        Fixed[k]= 2;
                   8710:        Dummy[k]= 3;
                   8711:        modell[k].maintype= ATYPE;
                   8712:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8713:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8714:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8715:        Fixed[k]= 3;
                   8716:        Dummy[k]= 2;
                   8717:        modell[k].maintype= ATYPE;
                   8718:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8719:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8720:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8721:        Fixed[k]= 3;
                   8722:        Dummy[k]= 3;
                   8723:        modell[k].maintype= ATYPE;
                   8724:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8725:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8726:       }
                   8727:     }else if (Typevar[k] == 2) {  /* product without age */
                   8728:       k1=Tposprod[k];
                   8729:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8730:        if(Tvard[k1][2] <=ncovcol){
                   8731:          Fixed[k]= 1;
                   8732:          Dummy[k]= 0;
                   8733:          modell[k].maintype= FTYPE;
                   8734:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8735:          ncovf++; /* Fixed variables without age */
                   8736:          TvarF[ncovf]=Tvar[k];
                   8737:          TvarFind[ncovf]=k;
                   8738:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8739:          Fixed[k]= 0;  /* or 2 ?*/
                   8740:          Dummy[k]= 1;
                   8741:          modell[k].maintype= FTYPE;
                   8742:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8743:          ncovf++; /* Varying variables without age */
                   8744:          TvarF[ncovf]=Tvar[k];
                   8745:          TvarFind[ncovf]=k;
                   8746:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8747:          Fixed[k]= 1;
                   8748:          Dummy[k]= 0;
                   8749:          modell[k].maintype= VTYPE;
                   8750:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8751:          ncovv++; /* Varying variables without age */
                   8752:          TvarV[ncovv]=Tvar[k];
                   8753:          TvarVind[ncovv]=k;
                   8754:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8755:          Fixed[k]= 1;
                   8756:          Dummy[k]= 1;
                   8757:          modell[k].maintype= VTYPE;
                   8758:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8759:          ncovv++; /* Varying variables without age */
                   8760:          TvarV[ncovv]=Tvar[k];
                   8761:          TvarVind[ncovv]=k;
                   8762:        }
1.227     brouard  8763:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8764:        if(Tvard[k1][2] <=ncovcol){
                   8765:          Fixed[k]= 0;  /* or 2 ?*/
                   8766:          Dummy[k]= 1;
                   8767:          modell[k].maintype= FTYPE;
                   8768:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8769:          ncovf++; /* Fixed variables without age */
                   8770:          TvarF[ncovf]=Tvar[k];
                   8771:          TvarFind[ncovf]=k;
                   8772:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8773:          Fixed[k]= 1;
                   8774:          Dummy[k]= 1;
                   8775:          modell[k].maintype= VTYPE;
                   8776:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8777:          ncovv++; /* Varying variables without age */
                   8778:          TvarV[ncovv]=Tvar[k];
                   8779:          TvarVind[ncovv]=k;
                   8780:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8781:          Fixed[k]= 1;
                   8782:          Dummy[k]= 1;
                   8783:          modell[k].maintype= VTYPE;
                   8784:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8785:          ncovv++; /* Varying variables without age */
                   8786:          TvarV[ncovv]=Tvar[k];
                   8787:          TvarVind[ncovv]=k;
                   8788:          ncovv++; /* Varying variables without age */
                   8789:          TvarV[ncovv]=Tvar[k];
                   8790:          TvarVind[ncovv]=k;
                   8791:        }
1.227     brouard  8792:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8793:        if(Tvard[k1][2] <=ncovcol){
                   8794:          Fixed[k]= 1;
                   8795:          Dummy[k]= 1;
                   8796:          modell[k].maintype= VTYPE;
                   8797:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8798:          ncovv++; /* Varying variables without age */
                   8799:          TvarV[ncovv]=Tvar[k];
                   8800:          TvarVind[ncovv]=k;
                   8801:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8802:          Fixed[k]= 1;
                   8803:          Dummy[k]= 1;
                   8804:          modell[k].maintype= VTYPE;
                   8805:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8806:          ncovv++; /* Varying variables without age */
                   8807:          TvarV[ncovv]=Tvar[k];
                   8808:          TvarVind[ncovv]=k;
                   8809:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8810:          Fixed[k]= 1;
                   8811:          Dummy[k]= 0;
                   8812:          modell[k].maintype= VTYPE;
                   8813:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8814:          ncovv++; /* Varying variables without age */
                   8815:          TvarV[ncovv]=Tvar[k];
                   8816:          TvarVind[ncovv]=k;
                   8817:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8818:          Fixed[k]= 1;
                   8819:          Dummy[k]= 1;
                   8820:          modell[k].maintype= VTYPE;
                   8821:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8822:          ncovv++; /* Varying variables without age */
                   8823:          TvarV[ncovv]=Tvar[k];
                   8824:          TvarVind[ncovv]=k;
                   8825:        }
1.227     brouard  8826:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8827:        if(Tvard[k1][2] <=ncovcol){
                   8828:          Fixed[k]= 1;
                   8829:          Dummy[k]= 1;
                   8830:          modell[k].maintype= VTYPE;
                   8831:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8832:          ncovv++; /* Varying variables without age */
                   8833:          TvarV[ncovv]=Tvar[k];
                   8834:          TvarVind[ncovv]=k;
                   8835:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8836:          Fixed[k]= 1;
                   8837:          Dummy[k]= 1;
                   8838:          modell[k].maintype= VTYPE;
                   8839:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8840:          ncovv++; /* Varying variables without age */
                   8841:          TvarV[ncovv]=Tvar[k];
                   8842:          TvarVind[ncovv]=k;
                   8843:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8844:          Fixed[k]= 1;
                   8845:          Dummy[k]= 1;
                   8846:          modell[k].maintype= VTYPE;
                   8847:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8848:          ncovv++; /* Varying variables without age */
                   8849:          TvarV[ncovv]=Tvar[k];
                   8850:          TvarVind[ncovv]=k;
                   8851:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8852:          Fixed[k]= 1;
                   8853:          Dummy[k]= 1;
                   8854:          modell[k].maintype= VTYPE;
                   8855:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8856:          ncovv++; /* Varying variables without age */
                   8857:          TvarV[ncovv]=Tvar[k];
                   8858:          TvarVind[ncovv]=k;
                   8859:        }
1.227     brouard  8860:       }else{
1.240     brouard  8861:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8862:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8863:       } /*end k1*/
1.225     brouard  8864:     }else{
1.226     brouard  8865:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8866:       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  8867:     }
1.227     brouard  8868:     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  8869:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8870:     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]);
                   8871:   }
                   8872:   /* Searching for doublons in the model */
                   8873:   for(k1=1; k1<= cptcovt;k1++){
                   8874:     for(k2=1; k2 <k1;k2++){
                   8875:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8876:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8877:          if(Tvar[k1]==Tvar[k2]){
                   8878:            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]]);
                   8879:            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);
                   8880:            return(1);
                   8881:          }
                   8882:        }else if (Typevar[k1] ==2){
                   8883:          k3=Tposprod[k1];
                   8884:          k4=Tposprod[k2];
                   8885:          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])) ){
                   8886:            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]]);
                   8887:            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);
                   8888:            return(1);
                   8889:          }
                   8890:        }
1.227     brouard  8891:       }
                   8892:     }
1.225     brouard  8893:   }
                   8894:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8895:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8896:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8897:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8898:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8899:   /*endread:*/
1.225     brouard  8900:   printf("Exiting decodemodel: ");
                   8901:   return (1);
1.136     brouard  8902: }
                   8903: 
1.169     brouard  8904: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  8905: {/* Check ages at death */
1.136     brouard  8906:   int i, m;
1.218     brouard  8907:   int firstone=0;
                   8908:   
1.136     brouard  8909:   for (i=1; i<=imx; i++) {
                   8910:     for(m=2; (m<= maxwav); m++) {
                   8911:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8912:        anint[m][i]=9999;
1.216     brouard  8913:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8914:          s[m][i]=-1;
1.136     brouard  8915:       }
                   8916:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8917:        *nberr = *nberr + 1;
1.218     brouard  8918:        if(firstone == 0){
                   8919:          firstone=1;
                   8920:        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);
                   8921:        }
                   8922:        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  8923:        s[m][i]=-1;
                   8924:       }
                   8925:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8926:        (*nberr)++;
1.136     brouard  8927:        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]); 
                   8928:        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]); 
                   8929:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8930:       }
                   8931:     }
                   8932:   }
                   8933: 
                   8934:   for (i=1; i<=imx; i++)  {
                   8935:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8936:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8937:       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  8938:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8939:          if(agedc[i]>0){
                   8940:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8941:              agev[m][i]=agedc[i];
1.214     brouard  8942:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8943:            }else {
1.136     brouard  8944:              if ((int)andc[i]!=9999){
                   8945:                nbwarn++;
                   8946:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8947:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8948:                agev[m][i]=-1;
                   8949:              }
                   8950:            }
1.169     brouard  8951:          } /* agedc > 0 */
1.214     brouard  8952:        } /* end if */
1.136     brouard  8953:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8954:                                 years but with the precision of a month */
                   8955:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8956:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8957:            agev[m][i]=1;
                   8958:          else if(agev[m][i] < *agemin){ 
                   8959:            *agemin=agev[m][i];
                   8960:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8961:          }
                   8962:          else if(agev[m][i] >*agemax){
                   8963:            *agemax=agev[m][i];
1.156     brouard  8964:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8965:          }
                   8966:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8967:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8968:        } /* en if 9*/
1.136     brouard  8969:        else { /* =9 */
1.214     brouard  8970:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8971:          agev[m][i]=1;
                   8972:          s[m][i]=-1;
                   8973:        }
                   8974:       }
1.214     brouard  8975:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8976:        agev[m][i]=1;
1.214     brouard  8977:       else{
                   8978:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8979:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8980:        agev[m][i]=0;
                   8981:       }
                   8982:     } /* End for lastpass */
                   8983:   }
1.136     brouard  8984:     
                   8985:   for (i=1; i<=imx; i++)  {
                   8986:     for(m=firstpass; (m<=lastpass); m++){
                   8987:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8988:        (*nberr)++;
1.136     brouard  8989:        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);     
                   8990:        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);     
                   8991:        return 1;
                   8992:       }
                   8993:     }
                   8994:   }
                   8995: 
                   8996:   /*for (i=1; i<=imx; i++){
                   8997:   for (m=firstpass; (m<lastpass); m++){
                   8998:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8999: }
                   9000: 
                   9001: }*/
                   9002: 
                   9003: 
1.139     brouard  9004:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   9005:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  9006: 
                   9007:   return (0);
1.164     brouard  9008:  /* endread:*/
1.136     brouard  9009:     printf("Exiting calandcheckages: ");
                   9010:     return (1);
                   9011: }
                   9012: 
1.172     brouard  9013: #if defined(_MSC_VER)
                   9014: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   9015: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   9016: //#include "stdafx.h"
                   9017: //#include <stdio.h>
                   9018: //#include <tchar.h>
                   9019: //#include <windows.h>
                   9020: //#include <iostream>
                   9021: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   9022: 
                   9023: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   9024: 
                   9025: BOOL IsWow64()
                   9026: {
                   9027:        BOOL bIsWow64 = FALSE;
                   9028: 
                   9029:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   9030:        //  (HANDLE, PBOOL);
                   9031: 
                   9032:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   9033: 
                   9034:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   9035:        const char funcName[] = "IsWow64Process";
                   9036:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   9037:                GetProcAddress(module, funcName);
                   9038: 
                   9039:        if (NULL != fnIsWow64Process)
                   9040:        {
                   9041:                if (!fnIsWow64Process(GetCurrentProcess(),
                   9042:                        &bIsWow64))
                   9043:                        //throw std::exception("Unknown error");
                   9044:                        printf("Unknown error\n");
                   9045:        }
                   9046:        return bIsWow64 != FALSE;
                   9047: }
                   9048: #endif
1.177     brouard  9049: 
1.191     brouard  9050: void syscompilerinfo(int logged)
1.167     brouard  9051:  {
                   9052:    /* #include "syscompilerinfo.h"*/
1.185     brouard  9053:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   9054:    /* /GS /W3 /Gy
                   9055:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   9056:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   9057:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  9058:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   9059:    */ 
                   9060:    /* 64 bits */
1.185     brouard  9061:    /*
                   9062:      /GS /W3 /Gy
                   9063:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   9064:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   9065:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   9066:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   9067:    /* Optimization are useless and O3 is slower than O2 */
                   9068:    /*
                   9069:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   9070:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   9071:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   9072:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   9073:    */
1.186     brouard  9074:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  9075:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   9076:       /PDB:"visual studio
                   9077:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   9078:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   9079:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   9080:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   9081:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   9082:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   9083:       uiAccess='false'"
                   9084:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   9085:       /NOLOGO /TLBID:1
                   9086:    */
1.177     brouard  9087: #if defined __INTEL_COMPILER
1.178     brouard  9088: #if defined(__GNUC__)
                   9089:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9090: #endif
1.177     brouard  9091: #elif defined(__GNUC__) 
1.179     brouard  9092: #ifndef  __APPLE__
1.174     brouard  9093: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9094: #endif
1.177     brouard  9095:    struct utsname sysInfo;
1.178     brouard  9096:    int cross = CROSS;
                   9097:    if (cross){
                   9098:           printf("Cross-");
1.191     brouard  9099:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9100:    }
1.174     brouard  9101: #endif
                   9102: 
1.171     brouard  9103: #include <stdint.h>
1.178     brouard  9104: 
1.191     brouard  9105:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9106: #if defined(__clang__)
1.191     brouard  9107:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9108: #endif
                   9109: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9110:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9111: #endif
                   9112: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9113:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9114: #endif
                   9115: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9116:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9117: #endif
                   9118: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9119:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9120: #endif
                   9121: #if defined(_MSC_VER)
1.191     brouard  9122:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9123: #endif
                   9124: #if defined(__PGI)
1.191     brouard  9125:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9126: #endif
                   9127: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9128:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9129: #endif
1.191     brouard  9130:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9131:    
1.167     brouard  9132: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9133: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9134:     // Windows (x64 and x86)
1.191     brouard  9135:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9136: #elif __unix__ // all unices, not all compilers
                   9137:     // Unix
1.191     brouard  9138:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9139: #elif __linux__
                   9140:     // linux
1.191     brouard  9141:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9142: #elif __APPLE__
1.174     brouard  9143:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9144:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9145: #endif
                   9146: 
                   9147: /*  __MINGW32__          */
                   9148: /*  __CYGWIN__  */
                   9149: /* __MINGW64__  */
                   9150: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9151: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9152: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9153: /* _WIN64  // Defined for applications for Win64. */
                   9154: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9155: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9156: 
1.167     brouard  9157: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9158:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9159: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9160:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9161: #else
1.191     brouard  9162:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9163: #endif
                   9164: 
1.169     brouard  9165: #if defined(__GNUC__)
                   9166: # if defined(__GNUC_PATCHLEVEL__)
                   9167: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9168:                             + __GNUC_MINOR__ * 100 \
                   9169:                             + __GNUC_PATCHLEVEL__)
                   9170: # else
                   9171: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9172:                             + __GNUC_MINOR__ * 100)
                   9173: # endif
1.174     brouard  9174:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9175:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9176: 
                   9177:    if (uname(&sysInfo) != -1) {
                   9178:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9179:         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  9180:    }
                   9181:    else
                   9182:       perror("uname() error");
1.179     brouard  9183:    //#ifndef __INTEL_COMPILER 
                   9184: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9185:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9186:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9187: #endif
1.169     brouard  9188: #endif
1.172     brouard  9189: 
                   9190:    //   void main()
                   9191:    //   {
1.169     brouard  9192: #if defined(_MSC_VER)
1.174     brouard  9193:    if (IsWow64()){
1.191     brouard  9194:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9195:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9196:    }
                   9197:    else{
1.191     brouard  9198:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9199:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9200:    }
1.172     brouard  9201:    //     printf("\nPress Enter to continue...");
                   9202:    //     getchar();
                   9203:    //   }
                   9204: 
1.169     brouard  9205: #endif
                   9206:    
1.167     brouard  9207: 
1.219     brouard  9208: }
1.136     brouard  9209: 
1.219     brouard  9210: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9211:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9212:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9213:   /* double ftolpl = 1.e-10; */
1.180     brouard  9214:   double age, agebase, agelim;
1.203     brouard  9215:   double tot;
1.180     brouard  9216: 
1.202     brouard  9217:   strcpy(filerespl,"PL_");
                   9218:   strcat(filerespl,fileresu);
                   9219:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9220:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9221:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9222:   }
1.227     brouard  9223:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9224:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9225:   pstamp(ficrespl);
1.203     brouard  9226:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9227:   fprintf(ficrespl,"#Age ");
                   9228:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9229:   fprintf(ficrespl,"\n");
1.180     brouard  9230:   
1.219     brouard  9231:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9232: 
1.219     brouard  9233:   agebase=ageminpar;
                   9234:   agelim=agemaxpar;
1.180     brouard  9235: 
1.227     brouard  9236:   /* i1=pow(2,ncoveff); */
1.234     brouard  9237:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9238:   if (cptcovn < 1){i1=1;}
1.180     brouard  9239: 
1.238     brouard  9240:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9241:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9242:       if(TKresult[nres]!= k)
                   9243:        continue;
1.235     brouard  9244: 
1.238     brouard  9245:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9246:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9247:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9248:       /* k=k+1; */
                   9249:       /* to clean */
                   9250:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9251:       fprintf(ficrespl,"#******");
                   9252:       printf("#******");
                   9253:       fprintf(ficlog,"#******");
                   9254:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9255:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9256:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9257:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9258:       }
                   9259:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9260:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9261:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9262:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9263:       }
                   9264:       fprintf(ficrespl,"******\n");
                   9265:       printf("******\n");
                   9266:       fprintf(ficlog,"******\n");
                   9267:       if(invalidvarcomb[k]){
                   9268:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9269:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9270:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9271:        continue;
                   9272:       }
1.219     brouard  9273: 
1.238     brouard  9274:       fprintf(ficrespl,"#Age ");
                   9275:       for(j=1;j<=cptcoveff;j++) {
                   9276:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9277:       }
                   9278:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9279:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9280:     
1.238     brouard  9281:       for (age=agebase; age<=agelim; age++){
                   9282:        /* for (age=agebase; age<=agebase; age++){ */
                   9283:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9284:        fprintf(ficrespl,"%.0f ",age );
                   9285:        for(j=1;j<=cptcoveff;j++)
                   9286:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9287:        tot=0.;
                   9288:        for(i=1; i<=nlstate;i++){
                   9289:          tot +=  prlim[i][i];
                   9290:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9291:        }
                   9292:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9293:       } /* Age */
                   9294:       /* was end of cptcod */
                   9295:     } /* cptcov */
                   9296:   } /* nres */
1.219     brouard  9297:   return 0;
1.180     brouard  9298: }
                   9299: 
1.218     brouard  9300: 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){
                   9301:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9302:        
                   9303:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9304:    * at any age between ageminpar and agemaxpar
                   9305:         */
1.235     brouard  9306:   int i, j, k, i1, nres=0 ;
1.217     brouard  9307:   /* double ftolpl = 1.e-10; */
                   9308:   double age, agebase, agelim;
                   9309:   double tot;
1.218     brouard  9310:   /* double ***mobaverage; */
                   9311:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9312: 
                   9313:   strcpy(fileresplb,"PLB_");
                   9314:   strcat(fileresplb,fileresu);
                   9315:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9316:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9317:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9318:   }
                   9319:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9320:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9321:   pstamp(ficresplb);
                   9322:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9323:   fprintf(ficresplb,"#Age ");
                   9324:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9325:   fprintf(ficresplb,"\n");
                   9326:   
1.218     brouard  9327:   
                   9328:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9329:   
                   9330:   agebase=ageminpar;
                   9331:   agelim=agemaxpar;
                   9332:   
                   9333:   
1.227     brouard  9334:   i1=pow(2,cptcoveff);
1.218     brouard  9335:   if (cptcovn < 1){i1=1;}
1.227     brouard  9336:   
1.238     brouard  9337:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9338:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9339:       if(TKresult[nres]!= k)
                   9340:        continue;
                   9341:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9342:       fprintf(ficresplb,"#******");
                   9343:       printf("#******");
                   9344:       fprintf(ficlog,"#******");
                   9345:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9346:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9347:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9348:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9349:       }
                   9350:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9351:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9352:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9353:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9354:       }
                   9355:       fprintf(ficresplb,"******\n");
                   9356:       printf("******\n");
                   9357:       fprintf(ficlog,"******\n");
                   9358:       if(invalidvarcomb[k]){
                   9359:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9360:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9361:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9362:        continue;
                   9363:       }
1.218     brouard  9364:     
1.238     brouard  9365:       fprintf(ficresplb,"#Age ");
                   9366:       for(j=1;j<=cptcoveff;j++) {
                   9367:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9368:       }
                   9369:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9370:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9371:     
                   9372:     
1.238     brouard  9373:       for (age=agebase; age<=agelim; age++){
                   9374:        /* for (age=agebase; age<=agebase; age++){ */
                   9375:        if(mobilavproj > 0){
                   9376:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9377:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9378:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9379:        }else if (mobilavproj == 0){
                   9380:          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);
                   9381:          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);
                   9382:          exit(1);
                   9383:        }else{
                   9384:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9385:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9386:        }
                   9387:        fprintf(ficresplb,"%.0f ",age );
                   9388:        for(j=1;j<=cptcoveff;j++)
                   9389:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9390:        tot=0.;
                   9391:        for(i=1; i<=nlstate;i++){
                   9392:          tot +=  bprlim[i][i];
                   9393:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9394:        }
                   9395:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9396:       } /* Age */
                   9397:       /* was end of cptcod */
                   9398:     } /* end of any combination */
                   9399:   } /* end of nres */  
1.218     brouard  9400:   /* hBijx(p, bage, fage); */
                   9401:   /* fclose(ficrespijb); */
                   9402:   
                   9403:   return 0;
1.217     brouard  9404: }
1.218     brouard  9405:  
1.180     brouard  9406: int hPijx(double *p, int bage, int fage){
                   9407:     /*------------- h Pij x at various ages ------------*/
                   9408: 
                   9409:   int stepsize;
                   9410:   int agelim;
                   9411:   int hstepm;
                   9412:   int nhstepm;
1.235     brouard  9413:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9414: 
                   9415:   double agedeb;
                   9416:   double ***p3mat;
                   9417: 
1.201     brouard  9418:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9419:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9420:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9421:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9422:     }
                   9423:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9424:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9425:   
                   9426:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9427:     /*if (stepm<=24) stepsize=2;*/
                   9428: 
                   9429:     agelim=AGESUP;
                   9430:     hstepm=stepsize*YEARM; /* Every year of age */
                   9431:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9432:                
1.180     brouard  9433:     /* hstepm=1;   aff par mois*/
                   9434:     pstamp(ficrespij);
                   9435:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9436:     i1= pow(2,cptcoveff);
1.218     brouard  9437:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9438:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9439:                /*      k=k+1;  */
1.235     brouard  9440:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9441:     for(k=1; k<=i1;k++){
                   9442:       if(TKresult[nres]!= k)
                   9443:        continue;
1.183     brouard  9444:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9445:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9446:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9447:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9448:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9449:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9450:       }
1.183     brouard  9451:       fprintf(ficrespij,"******\n");
                   9452:       
                   9453:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9454:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9455:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9456:        
                   9457:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9458:        
1.183     brouard  9459:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9460:        oldm=oldms;savm=savms;
1.235     brouard  9461:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9462:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9463:        for(i=1; i<=nlstate;i++)
                   9464:          for(j=1; j<=nlstate+ndeath;j++)
                   9465:            fprintf(ficrespij," %1d-%1d",i,j);
                   9466:        fprintf(ficrespij,"\n");
                   9467:        for (h=0; h<=nhstepm; h++){
                   9468:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9469:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9470:          for(i=1; i<=nlstate;i++)
                   9471:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9472:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9473:          fprintf(ficrespij,"\n");
                   9474:        }
1.183     brouard  9475:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9476:        fprintf(ficrespij,"\n");
                   9477:       }
1.180     brouard  9478:       /*}*/
                   9479:     }
1.218     brouard  9480:     return 0;
1.180     brouard  9481: }
1.218     brouard  9482:  
                   9483:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9484:     /*------------- h Bij x at various ages ------------*/
                   9485: 
                   9486:   int stepsize;
1.218     brouard  9487:   /* int agelim; */
                   9488:        int ageminl;
1.217     brouard  9489:   int hstepm;
                   9490:   int nhstepm;
1.238     brouard  9491:   int h, i, i1, j, k, nres;
1.218     brouard  9492:        
1.217     brouard  9493:   double agedeb;
                   9494:   double ***p3mat;
1.218     brouard  9495:        
                   9496:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9497:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9498:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9499:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9500:   }
                   9501:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9502:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9503:   
                   9504:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9505:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9506:   
1.218     brouard  9507:   /* agelim=AGESUP; */
                   9508:   ageminl=30;
                   9509:   hstepm=stepsize*YEARM; /* Every year of age */
                   9510:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9511:   
                   9512:   /* hstepm=1;   aff par mois*/
                   9513:   pstamp(ficrespijb);
                   9514:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9515:   i1= pow(2,cptcoveff);
1.218     brouard  9516:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9517:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9518:   /*   k=k+1;  */
1.238     brouard  9519:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9520:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9521:       if(TKresult[nres]!= k)
                   9522:        continue;
                   9523:       fprintf(ficrespijb,"\n#****** ");
                   9524:       for(j=1;j<=cptcoveff;j++)
                   9525:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9526:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9527:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9528:       }
                   9529:       fprintf(ficrespijb,"******\n");
                   9530:       if(invalidvarcomb[k]){
                   9531:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9532:        continue;
                   9533:       }
                   9534:       
                   9535:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9536:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9537:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9538:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9539:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9540:        
                   9541:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9542:        
                   9543:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9544:        /* oldm=oldms;savm=savms; */
                   9545:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9546:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9547:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9548:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9549:        for(i=1; i<=nlstate;i++)
                   9550:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9551:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9552:        fprintf(ficrespijb,"\n");
1.238     brouard  9553:        for (h=0; h<=nhstepm; h++){
                   9554:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9555:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9556:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9557:          for(i=1; i<=nlstate;i++)
                   9558:            for(j=1; j<=nlstate+ndeath;j++)
                   9559:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9560:          fprintf(ficrespijb,"\n");
                   9561:        }
                   9562:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9563:        fprintf(ficrespijb,"\n");
                   9564:       } /* end age deb */
                   9565:     } /* end combination */
                   9566:   } /* end nres */
1.218     brouard  9567:   return 0;
                   9568:  } /*  hBijx */
1.217     brouard  9569: 
1.180     brouard  9570: 
1.136     brouard  9571: /***********************************************/
                   9572: /**************** Main Program *****************/
                   9573: /***********************************************/
                   9574: 
                   9575: int main(int argc, char *argv[])
                   9576: {
                   9577: #ifdef GSL
                   9578:   const gsl_multimin_fminimizer_type *T;
                   9579:   size_t iteri = 0, it;
                   9580:   int rval = GSL_CONTINUE;
                   9581:   int status = GSL_SUCCESS;
                   9582:   double ssval;
                   9583: #endif
                   9584:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9585:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9586:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9587:   int jj, ll, li, lj, lk;
1.136     brouard  9588:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9589:   int num_filled;
1.136     brouard  9590:   int itimes;
                   9591:   int NDIM=2;
                   9592:   int vpopbased=0;
1.235     brouard  9593:   int nres=0;
1.136     brouard  9594: 
1.164     brouard  9595:   char ca[32], cb[32];
1.136     brouard  9596:   /*  FILE *fichtm; *//* Html File */
                   9597:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9598:   struct stat info;
1.191     brouard  9599:   double agedeb=0.;
1.194     brouard  9600: 
                   9601:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9602:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9603: 
1.165     brouard  9604:   double fret;
1.191     brouard  9605:   double dum=0.; /* Dummy variable */
1.136     brouard  9606:   double ***p3mat;
1.218     brouard  9607:   /* double ***mobaverage; */
1.164     brouard  9608: 
                   9609:   char line[MAXLINE];
1.197     brouard  9610:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9611: 
1.234     brouard  9612:   char  modeltemp[MAXLINE];
1.230     brouard  9613:   char resultline[MAXLINE];
                   9614:   
1.136     brouard  9615:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9616:   char *tok, *val; /* pathtot */
1.136     brouard  9617:   int firstobs=1, lastobs=10;
1.195     brouard  9618:   int c,  h , cpt, c2;
1.191     brouard  9619:   int jl=0;
                   9620:   int i1, j1, jk, stepsize=0;
1.194     brouard  9621:   int count=0;
                   9622: 
1.164     brouard  9623:   int *tab; 
1.136     brouard  9624:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9625:   int backcast=0;
1.136     brouard  9626:   int mobilav=0,popforecast=0;
1.191     brouard  9627:   int hstepm=0, nhstepm=0;
1.136     brouard  9628:   int agemortsup;
                   9629:   float  sumlpop=0.;
                   9630:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9631:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9632: 
1.191     brouard  9633:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9634:   double ftolpl=FTOL;
                   9635:   double **prlim;
1.217     brouard  9636:   double **bprlim;
1.136     brouard  9637:   double ***param; /* Matrix of parameters */
                   9638:   double  *p;
                   9639:   double **matcov; /* Matrix of covariance */
1.203     brouard  9640:   double **hess; /* Hessian matrix */
1.136     brouard  9641:   double ***delti3; /* Scale */
                   9642:   double *delti; /* Scale */
                   9643:   double ***eij, ***vareij;
                   9644:   double **varpl; /* Variances of prevalence limits by age */
                   9645:   double *epj, vepp;
1.164     brouard  9646: 
1.136     brouard  9647:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9648:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9649: 
1.136     brouard  9650:   double **ximort;
1.145     brouard  9651:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9652:   int *dcwave;
                   9653: 
1.164     brouard  9654:   char z[1]="c";
1.136     brouard  9655: 
                   9656:   /*char  *strt;*/
                   9657:   char strtend[80];
1.126     brouard  9658: 
1.164     brouard  9659: 
1.126     brouard  9660: /*   setlocale (LC_ALL, ""); */
                   9661: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9662: /*   textdomain (PACKAGE); */
                   9663: /*   setlocale (LC_CTYPE, ""); */
                   9664: /*   setlocale (LC_MESSAGES, ""); */
                   9665: 
                   9666:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9667:   rstart_time = time(NULL);  
                   9668:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9669:   start_time = *localtime(&rstart_time);
1.126     brouard  9670:   curr_time=start_time;
1.157     brouard  9671:   /*tml = *localtime(&start_time.tm_sec);*/
                   9672:   /* strcpy(strstart,asctime(&tml)); */
                   9673:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9674: 
                   9675: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9676: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9677: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9678: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9679: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9680: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9681: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9682: /*   strt=asctime(&tmg); */
                   9683: /*   printf("Time(after) =%s",strstart);  */
                   9684: /*  (void) time (&time_value);
                   9685: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9686: *  tm = *localtime(&time_value);
                   9687: *  strstart=asctime(&tm);
                   9688: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9689: */
                   9690: 
                   9691:   nberr=0; /* Number of errors and warnings */
                   9692:   nbwarn=0;
1.184     brouard  9693: #ifdef WIN32
                   9694:   _getcwd(pathcd, size);
                   9695: #else
1.126     brouard  9696:   getcwd(pathcd, size);
1.184     brouard  9697: #endif
1.191     brouard  9698:   syscompilerinfo(0);
1.196     brouard  9699:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9700:   if(argc <=1){
                   9701:     printf("\nEnter the parameter file name: ");
1.205     brouard  9702:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9703:       printf("ERROR Empty parameter file name\n");
                   9704:       goto end;
                   9705:     }
1.126     brouard  9706:     i=strlen(pathr);
                   9707:     if(pathr[i-1]=='\n')
                   9708:       pathr[i-1]='\0';
1.156     brouard  9709:     i=strlen(pathr);
1.205     brouard  9710:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9711:       pathr[i-1]='\0';
1.205     brouard  9712:     }
                   9713:     i=strlen(pathr);
                   9714:     if( i==0 ){
                   9715:       printf("ERROR Empty parameter file name\n");
                   9716:       goto end;
                   9717:     }
                   9718:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9719:       printf("Pathr |%s|\n",pathr);
                   9720:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9721:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9722:       strcpy (pathtot, val);
                   9723:       if(pathr[0] == '\0') break; /* Dirty */
                   9724:     }
                   9725:   }
                   9726:   else{
                   9727:     strcpy(pathtot,argv[1]);
                   9728:   }
                   9729:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9730:   /*cygwin_split_path(pathtot,path,optionfile);
                   9731:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9732:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9733: 
                   9734:   /* Split argv[0], imach program to get pathimach */
                   9735:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9736:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9737:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9738:  /*   strcpy(pathimach,argv[0]); */
                   9739:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9740:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9741:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9742: #ifdef WIN32
                   9743:   _chdir(path); /* Can be a relative path */
                   9744:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9745: #else
1.126     brouard  9746:   chdir(path); /* Can be a relative path */
1.184     brouard  9747:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9748: #endif
                   9749:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9750:   strcpy(command,"mkdir ");
                   9751:   strcat(command,optionfilefiname);
                   9752:   if((outcmd=system(command)) != 0){
1.169     brouard  9753:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9754:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9755:     /* fclose(ficlog); */
                   9756: /*     exit(1); */
                   9757:   }
                   9758: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9759: /*     perror("mkdir"); */
                   9760: /*   } */
                   9761: 
                   9762:   /*-------- arguments in the command line --------*/
                   9763: 
1.186     brouard  9764:   /* Main Log file */
1.126     brouard  9765:   strcat(filelog, optionfilefiname);
                   9766:   strcat(filelog,".log");    /* */
                   9767:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9768:     printf("Problem with logfile %s\n",filelog);
                   9769:     goto end;
                   9770:   }
                   9771:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9772:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9773:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9774:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9775:  path=%s \n\
                   9776:  optionfile=%s\n\
                   9777:  optionfilext=%s\n\
1.156     brouard  9778:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9779: 
1.197     brouard  9780:   syscompilerinfo(1);
1.167     brouard  9781: 
1.126     brouard  9782:   printf("Local time (at start):%s",strstart);
                   9783:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9784:   fflush(ficlog);
                   9785: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9786: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9787: 
                   9788:   /* */
                   9789:   strcpy(fileres,"r");
                   9790:   strcat(fileres, optionfilefiname);
1.201     brouard  9791:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9792:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9793:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9794: 
1.186     brouard  9795:   /* Main ---------arguments file --------*/
1.126     brouard  9796: 
                   9797:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9798:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9799:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9800:     fflush(ficlog);
1.149     brouard  9801:     /* goto end; */
                   9802:     exit(70); 
1.126     brouard  9803:   }
                   9804: 
                   9805: 
                   9806: 
                   9807:   strcpy(filereso,"o");
1.201     brouard  9808:   strcat(filereso,fileresu);
1.126     brouard  9809:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9810:     printf("Problem with Output resultfile: %s\n", filereso);
                   9811:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9812:     fflush(ficlog);
                   9813:     goto end;
                   9814:   }
                   9815: 
                   9816:   /* Reads comments: lines beginning with '#' */
                   9817:   numlinepar=0;
1.197     brouard  9818: 
                   9819:     /* First parameter line */
                   9820:   while(fgets(line, MAXLINE, ficpar)) {
                   9821:     /* If line starts with a # it is a comment */
                   9822:     if (line[0] == '#') {
                   9823:       numlinepar++;
                   9824:       fputs(line,stdout);
                   9825:       fputs(line,ficparo);
                   9826:       fputs(line,ficlog);
                   9827:       continue;
                   9828:     }else
                   9829:       break;
                   9830:   }
                   9831:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9832:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9833:     if (num_filled != 5) {
                   9834:       printf("Should be 5 parameters\n");
                   9835:     }
1.126     brouard  9836:     numlinepar++;
1.197     brouard  9837:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9838:   }
                   9839:   /* Second parameter line */
                   9840:   while(fgets(line, MAXLINE, ficpar)) {
                   9841:     /* If line starts with a # it is a comment */
                   9842:     if (line[0] == '#') {
                   9843:       numlinepar++;
                   9844:       fputs(line,stdout);
                   9845:       fputs(line,ficparo);
                   9846:       fputs(line,ficlog);
                   9847:       continue;
                   9848:     }else
                   9849:       break;
                   9850:   }
1.223     brouard  9851:   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", \
                   9852:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9853:     if (num_filled != 11) {
                   9854:       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  9855:       printf("but line=%s\n",line);
1.197     brouard  9856:     }
1.223     brouard  9857:     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  9858:   }
1.203     brouard  9859:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9860:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9861:   /* Third parameter line */
                   9862:   while(fgets(line, MAXLINE, ficpar)) {
                   9863:     /* If line starts with a # it is a comment */
                   9864:     if (line[0] == '#') {
                   9865:       numlinepar++;
                   9866:       fputs(line,stdout);
                   9867:       fputs(line,ficparo);
                   9868:       fputs(line,ficlog);
                   9869:       continue;
                   9870:     }else
                   9871:       break;
                   9872:   }
1.201     brouard  9873:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9874:     if (num_filled == 0)
                   9875:             model[0]='\0';
                   9876:     else if (num_filled != 1){
1.197     brouard  9877:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9878:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9879:       model[0]='\0';
                   9880:       goto end;
                   9881:     }
                   9882:     else{
                   9883:       if (model[0]=='+'){
                   9884:        for(i=1; i<=strlen(model);i++)
                   9885:          modeltemp[i-1]=model[i];
1.201     brouard  9886:        strcpy(model,modeltemp); 
1.197     brouard  9887:       }
                   9888:     }
1.199     brouard  9889:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9890:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9891:   }
                   9892:   /* 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); */
                   9893:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9894:   /* 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  9895:   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);
                   9896:   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  9897:   fflush(ficlog);
1.190     brouard  9898:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9899:   if(model[0]=='#'){
1.187     brouard  9900:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9901:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9902:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9903:     if(mle != -1){
                   9904:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9905:       exit(1);
                   9906:     }
                   9907:   }
1.126     brouard  9908:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9909:     ungetc(c,ficpar);
                   9910:     fgets(line, MAXLINE, ficpar);
                   9911:     numlinepar++;
1.195     brouard  9912:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9913:       z[0]=line[1];
                   9914:     }
                   9915:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9916:     fputs(line, stdout);
                   9917:     //puts(line);
1.126     brouard  9918:     fputs(line,ficparo);
                   9919:     fputs(line,ficlog);
                   9920:   }
                   9921:   ungetc(c,ficpar);
                   9922: 
                   9923:    
1.145     brouard  9924:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9925:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9926:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9927:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9928:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9929:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9930:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9931:   */
                   9932:   if (strlen(model)>1) 
1.187     brouard  9933:     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  9934:   else
1.187     brouard  9935:     ncovmodel=2; /* Constant and age */
1.133     brouard  9936:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9937:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9938:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9939:     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);
                   9940:     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);
                   9941:     fflush(stdout);
                   9942:     fclose (ficlog);
                   9943:     goto end;
                   9944:   }
1.126     brouard  9945:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9946:   delti=delti3[1][1];
                   9947:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9948:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  9949: /* We could also provide initial parameters values giving by simple logistic regression 
                   9950:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   9951:       /* for(i=1;i<nlstate;i++){ */
                   9952:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   9953:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   9954:       /* } */
1.126     brouard  9955:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9956:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9957:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9958:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9959:     fclose (ficparo);
                   9960:     fclose (ficlog);
                   9961:     goto end;
                   9962:     exit(0);
1.248     brouard  9963:   } else if(mle==-2) { /* Guessing from means */
                   9964:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   9965:     printf(" You chose mle=-2, look at file %s for a template of covariance matrix \n",filereso);
                   9966:     fprintf(ficlog," You chose mle=-2, look at file %s for a template of covariance matrix \n",filereso);
                   9967:    
1.220     brouard  9968:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9969:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9970:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9971:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9972:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9973:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9974:     hess=matrix(1,npar,1,npar);
1.220     brouard  9975:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9976:     /* Read guessed parameters */
1.126     brouard  9977:     /* Reads comments: lines beginning with '#' */
                   9978:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9979:       ungetc(c,ficpar);
                   9980:       fgets(line, MAXLINE, ficpar);
                   9981:       numlinepar++;
1.141     brouard  9982:       fputs(line,stdout);
1.126     brouard  9983:       fputs(line,ficparo);
                   9984:       fputs(line,ficlog);
                   9985:     }
                   9986:     ungetc(c,ficpar);
                   9987:     
                   9988:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9989:     for(i=1; i <=nlstate; i++){
1.234     brouard  9990:       j=0;
1.126     brouard  9991:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9992:        if(jj==i) continue;
                   9993:        j++;
                   9994:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9995:        if ((i1 != i) || (j1 != jj)){
                   9996:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9997: It might be a problem of design; if ncovcol and the model are correct\n \
                   9998: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9999:          exit(1);
                   10000:        }
                   10001:        fprintf(ficparo,"%1d%1d",i1,j1);
                   10002:        if(mle==1)
                   10003:          printf("%1d%1d",i,jj);
                   10004:        fprintf(ficlog,"%1d%1d",i,jj);
                   10005:        for(k=1; k<=ncovmodel;k++){
                   10006:          fscanf(ficpar," %lf",&param[i][j][k]);
                   10007:          if(mle==1){
                   10008:            printf(" %lf",param[i][j][k]);
                   10009:            fprintf(ficlog," %lf",param[i][j][k]);
                   10010:          }
                   10011:          else
                   10012:            fprintf(ficlog," %lf",param[i][j][k]);
                   10013:          fprintf(ficparo," %lf",param[i][j][k]);
                   10014:        }
                   10015:        fscanf(ficpar,"\n");
                   10016:        numlinepar++;
                   10017:        if(mle==1)
                   10018:          printf("\n");
                   10019:        fprintf(ficlog,"\n");
                   10020:        fprintf(ficparo,"\n");
1.126     brouard  10021:       }
                   10022:     }  
                   10023:     fflush(ficlog);
1.234     brouard  10024:     
1.145     brouard  10025:     /* Reads scales values */
1.126     brouard  10026:     p=param[1][1];
                   10027:     
                   10028:     /* Reads comments: lines beginning with '#' */
                   10029:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10030:       ungetc(c,ficpar);
                   10031:       fgets(line, MAXLINE, ficpar);
                   10032:       numlinepar++;
1.141     brouard  10033:       fputs(line,stdout);
1.126     brouard  10034:       fputs(line,ficparo);
                   10035:       fputs(line,ficlog);
                   10036:     }
                   10037:     ungetc(c,ficpar);
                   10038: 
                   10039:     for(i=1; i <=nlstate; i++){
                   10040:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  10041:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   10042:        if ( (i1-i) * (j1-j) != 0){
                   10043:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   10044:          exit(1);
                   10045:        }
                   10046:        printf("%1d%1d",i,j);
                   10047:        fprintf(ficparo,"%1d%1d",i1,j1);
                   10048:        fprintf(ficlog,"%1d%1d",i1,j1);
                   10049:        for(k=1; k<=ncovmodel;k++){
                   10050:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   10051:          printf(" %le",delti3[i][j][k]);
                   10052:          fprintf(ficparo," %le",delti3[i][j][k]);
                   10053:          fprintf(ficlog," %le",delti3[i][j][k]);
                   10054:        }
                   10055:        fscanf(ficpar,"\n");
                   10056:        numlinepar++;
                   10057:        printf("\n");
                   10058:        fprintf(ficparo,"\n");
                   10059:        fprintf(ficlog,"\n");
1.126     brouard  10060:       }
                   10061:     }
                   10062:     fflush(ficlog);
1.234     brouard  10063:     
1.145     brouard  10064:     /* Reads covariance matrix */
1.126     brouard  10065:     delti=delti3[1][1];
1.220     brouard  10066:                
                   10067:                
1.126     brouard  10068:     /* 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  10069:                
1.126     brouard  10070:     /* Reads comments: lines beginning with '#' */
                   10071:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10072:       ungetc(c,ficpar);
                   10073:       fgets(line, MAXLINE, ficpar);
                   10074:       numlinepar++;
1.141     brouard  10075:       fputs(line,stdout);
1.126     brouard  10076:       fputs(line,ficparo);
                   10077:       fputs(line,ficlog);
                   10078:     }
                   10079:     ungetc(c,ficpar);
1.220     brouard  10080:                
1.126     brouard  10081:     matcov=matrix(1,npar,1,npar);
1.203     brouard  10082:     hess=matrix(1,npar,1,npar);
1.131     brouard  10083:     for(i=1; i <=npar; i++)
                   10084:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  10085:                
1.194     brouard  10086:     /* Scans npar lines */
1.126     brouard  10087:     for(i=1; i <=npar; i++){
1.226     brouard  10088:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  10089:       if(count != 3){
1.226     brouard  10090:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10091: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10092: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10093:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10094: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10095: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10096:        exit(1);
1.220     brouard  10097:       }else{
1.226     brouard  10098:        if(mle==1)
                   10099:          printf("%1d%1d%d",i1,j1,jk);
                   10100:       }
                   10101:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10102:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10103:       for(j=1; j <=i; j++){
1.226     brouard  10104:        fscanf(ficpar," %le",&matcov[i][j]);
                   10105:        if(mle==1){
                   10106:          printf(" %.5le",matcov[i][j]);
                   10107:        }
                   10108:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10109:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10110:       }
                   10111:       fscanf(ficpar,"\n");
                   10112:       numlinepar++;
                   10113:       if(mle==1)
1.220     brouard  10114:                                printf("\n");
1.126     brouard  10115:       fprintf(ficlog,"\n");
                   10116:       fprintf(ficparo,"\n");
                   10117:     }
1.194     brouard  10118:     /* End of read covariance matrix npar lines */
1.126     brouard  10119:     for(i=1; i <=npar; i++)
                   10120:       for(j=i+1;j<=npar;j++)
1.226     brouard  10121:        matcov[i][j]=matcov[j][i];
1.126     brouard  10122:     
                   10123:     if(mle==1)
                   10124:       printf("\n");
                   10125:     fprintf(ficlog,"\n");
                   10126:     
                   10127:     fflush(ficlog);
                   10128:     
                   10129:     /*-------- Rewriting parameter file ----------*/
                   10130:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10131:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10132:     strcat(rfileres,".");    /* */
                   10133:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10134:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10135:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10136:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10137:     }
                   10138:     fprintf(ficres,"#%s\n",version);
                   10139:   }    /* End of mle != -3 */
1.218     brouard  10140:   
1.186     brouard  10141:   /*  Main data
                   10142:    */
1.126     brouard  10143:   n= lastobs;
                   10144:   num=lvector(1,n);
                   10145:   moisnais=vector(1,n);
                   10146:   annais=vector(1,n);
                   10147:   moisdc=vector(1,n);
                   10148:   andc=vector(1,n);
1.220     brouard  10149:   weight=vector(1,n);
1.126     brouard  10150:   agedc=vector(1,n);
                   10151:   cod=ivector(1,n);
1.220     brouard  10152:   for(i=1;i<=n;i++){
1.234     brouard  10153:     num[i]=0;
                   10154:     moisnais[i]=0;
                   10155:     annais[i]=0;
                   10156:     moisdc[i]=0;
                   10157:     andc[i]=0;
                   10158:     agedc[i]=0;
                   10159:     cod[i]=0;
                   10160:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10161:   }
1.126     brouard  10162:   mint=matrix(1,maxwav,1,n);
                   10163:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10164:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10165:   tab=ivector(1,NCOVMAX);
1.144     brouard  10166:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10167:   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  10168: 
1.136     brouard  10169:   /* Reads data from file datafile */
                   10170:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10171:     goto end;
                   10172: 
                   10173:   /* Calculation of the number of parameters from char model */
1.234     brouard  10174:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10175:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10176:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10177:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10178:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10179:   */
                   10180:   
                   10181:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10182:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10183:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10184:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10185:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10186:   TvarF=ivector(1,NCOVMAX); /*  */
                   10187:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10188:   TvarV=ivector(1,NCOVMAX); /*  */
                   10189:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10190:   TvarA=ivector(1,NCOVMAX); /*  */
                   10191:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10192:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10193:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10194:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10195:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10196:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10197:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10198:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10199:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10200: 
1.230     brouard  10201:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10202:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10203:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10204:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10205:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10206:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10207:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10208:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10209:   */
                   10210:   /* For model-covariate k tells which data-covariate to use but
                   10211:     because this model-covariate is a construction we invent a new column
                   10212:     ncovcol + k1
                   10213:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10214:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10215:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10216:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10217:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10218:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10219:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10220:   */
1.145     brouard  10221:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10222:   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  10223:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10224:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10225:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10226:                         4 covariates (3 plus signs)
                   10227:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10228:                      */  
1.230     brouard  10229:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10230:                                * individual dummy, fixed or varying:
                   10231:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10232:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10233:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10234:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10235:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10236:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10237:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10238:                                * individual quantitative, fixed or varying:
                   10239:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10240:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10241:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10242: /* Main decodemodel */
                   10243: 
1.187     brouard  10244: 
1.223     brouard  10245:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10246:     goto end;
                   10247: 
1.137     brouard  10248:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10249:     nbwarn++;
                   10250:     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); 
                   10251:     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); 
                   10252:   }
1.136     brouard  10253:     /*  if(mle==1){*/
1.137     brouard  10254:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10255:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10256:   }
                   10257: 
                   10258:     /*-calculation of age at interview from date of interview and age at death -*/
                   10259:   agev=matrix(1,maxwav,1,imx);
                   10260: 
                   10261:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10262:     goto end;
                   10263: 
1.126     brouard  10264: 
1.136     brouard  10265:   agegomp=(int)agemin;
                   10266:   free_vector(moisnais,1,n);
                   10267:   free_vector(annais,1,n);
1.126     brouard  10268:   /* free_matrix(mint,1,maxwav,1,n);
                   10269:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10270:   /* free_vector(moisdc,1,n); */
                   10271:   /* free_vector(andc,1,n); */
1.145     brouard  10272:   /* */
                   10273:   
1.126     brouard  10274:   wav=ivector(1,imx);
1.214     brouard  10275:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10276:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10277:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10278:   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.*/
                   10279:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10280:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10281:    
                   10282:   /* Concatenates waves */
1.214     brouard  10283:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10284:      Death is a valid wave (if date is known).
                   10285:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10286:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10287:      and mw[mi+1][i]. dh depends on stepm.
                   10288:   */
                   10289: 
1.126     brouard  10290:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  10291:   /* Concatenates waves */
1.145     brouard  10292:  
1.215     brouard  10293:   free_vector(moisdc,1,n);
                   10294:   free_vector(andc,1,n);
                   10295: 
1.126     brouard  10296:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10297:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10298:   ncodemax[1]=1;
1.145     brouard  10299:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10300:   cptcoveff=0;
1.220     brouard  10301:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10302:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10303:   }
                   10304:   
                   10305:   ncovcombmax=pow(2,cptcoveff);
                   10306:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10307:   for(i=1;i<ncovcombmax;i++)
                   10308:     invalidvarcomb[i]=0;
                   10309:   
1.211     brouard  10310:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10311:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10312:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10313:   
1.200     brouard  10314:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10315:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10316:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10317:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10318:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10319:    * (currently 0 or 1) in the data.
                   10320:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10321:    * corresponding modality (h,j).
                   10322:    */
                   10323: 
1.145     brouard  10324:   h=0;
                   10325:   /*if (cptcovn > 0) */
1.126     brouard  10326:   m=pow(2,cptcoveff);
                   10327:  
1.144     brouard  10328:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10329:           * For k=4 covariates, h goes from 1 to m=2**k
                   10330:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10331:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10332:           *     h\k   1     2     3     4
1.143     brouard  10333:           *______________________________  
                   10334:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10335:           *     2     2     1     1     1
                   10336:           *     3 i=2 1     2     1     1
                   10337:           *     4     2     2     1     1
                   10338:           *     5 i=3 1 i=2 1     2     1
                   10339:           *     6     2     1     2     1
                   10340:           *     7 i=4 1     2     2     1
                   10341:           *     8     2     2     2     1
1.197     brouard  10342:           *     9 i=5 1 i=3 1 i=2 1     2
                   10343:           *    10     2     1     1     2
                   10344:           *    11 i=6 1     2     1     2
                   10345:           *    12     2     2     1     2
                   10346:           *    13 i=7 1 i=4 1     2     2    
                   10347:           *    14     2     1     2     2
                   10348:           *    15 i=8 1     2     2     2
                   10349:           *    16     2     2     2     2
1.143     brouard  10350:           */
1.212     brouard  10351:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10352:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10353:      * and the value of each covariate?
                   10354:      * V1=1, V2=1, V3=2, V4=1 ?
                   10355:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10356:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10357:      * In order to get the real value in the data, we use nbcode
                   10358:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10359:      * We are keeping this crazy system in order to be able (in the future?) 
                   10360:      * to have more than 2 values (0 or 1) for a covariate.
                   10361:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10362:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10363:      *              bbbbbbbb
                   10364:      *              76543210     
                   10365:      *   h-1        00000101 (6-1=5)
1.219     brouard  10366:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10367:      *           &
                   10368:      *     1        00000001 (1)
1.219     brouard  10369:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10370:      *          +1= 00000001 =1 
1.211     brouard  10371:      *
                   10372:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10373:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10374:      *    >>k'            11
                   10375:      *          &   00000001
                   10376:      *            = 00000001
                   10377:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10378:      * Reverse h=6 and m=16?
                   10379:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10380:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10381:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10382:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10383:      * V3=decodtabm(14,3,2**4)=2
                   10384:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10385:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10386:      *          &1 000000001
                   10387:      *           = 000000001
                   10388:      *         +1= 000000010 =2
                   10389:      *                  2211
                   10390:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10391:      *                  V3=2
1.220     brouard  10392:                 * codtabm and decodtabm are identical
1.211     brouard  10393:      */
                   10394: 
1.145     brouard  10395: 
                   10396:  free_ivector(Ndum,-1,NCOVMAX);
                   10397: 
                   10398: 
1.126     brouard  10399:     
1.186     brouard  10400:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10401:   strcpy(optionfilegnuplot,optionfilefiname);
                   10402:   if(mle==-3)
1.201     brouard  10403:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10404:   strcat(optionfilegnuplot,".gp");
                   10405: 
                   10406:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10407:     printf("Problem with file %s",optionfilegnuplot);
                   10408:   }
                   10409:   else{
1.204     brouard  10410:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10411:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10412:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10413:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10414:   }
                   10415:   /*  fclose(ficgp);*/
1.186     brouard  10416: 
                   10417: 
                   10418:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10419: 
                   10420:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10421:   if(mle==-3)
1.201     brouard  10422:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10423:   strcat(optionfilehtm,".htm");
                   10424:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10425:     printf("Problem with %s \n",optionfilehtm);
                   10426:     exit(0);
1.126     brouard  10427:   }
                   10428: 
                   10429:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10430:   strcat(optionfilehtmcov,"-cov.htm");
                   10431:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10432:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10433:   }
                   10434:   else{
                   10435:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10436: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10437: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10438:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10439:   }
                   10440: 
1.213     brouard  10441:   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  10442: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10443: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10444: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10445: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10446: \n\
                   10447: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10448:  <ul><li><h4>Parameter files</h4>\n\
                   10449:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10450:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10451:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10452:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10453:  - Date and time at start: %s</ul>\n",\
                   10454:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10455:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10456:          fileres,fileres,\
                   10457:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10458:   fflush(fichtm);
                   10459: 
                   10460:   strcpy(pathr,path);
                   10461:   strcat(pathr,optionfilefiname);
1.184     brouard  10462: #ifdef WIN32
                   10463:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10464: #else
1.126     brouard  10465:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10466: #endif
                   10467:          
1.126     brouard  10468:   
1.220     brouard  10469:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10470:                 and for any valid combination of covariates
1.126     brouard  10471:      and prints on file fileres'p'. */
1.250   ! brouard  10472:   freqsummary(fileres, p, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  10473:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10474: 
                   10475:   fprintf(fichtm,"\n");
                   10476:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10477: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10478: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10479:          imx,agemin,agemax,jmin,jmax,jmean);
                   10480:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10481:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10482:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10483:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10484:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10485: 
1.126     brouard  10486:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10487:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10488:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10489: 
                   10490:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10491:   /* For mortality only */
1.126     brouard  10492:   if (mle==-3){
1.136     brouard  10493:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  10494:     for(i=1;i<=NDIM;i++)
                   10495:       for(j=1;j<=NDIM;j++)
                   10496:        ximort[i][j]=0.;
1.186     brouard  10497:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10498:     cens=ivector(1,n);
                   10499:     ageexmed=vector(1,n);
                   10500:     agecens=vector(1,n);
                   10501:     dcwave=ivector(1,n);
1.223     brouard  10502:                
1.126     brouard  10503:     for (i=1; i<=imx; i++){
                   10504:       dcwave[i]=-1;
                   10505:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10506:        if (s[m][i]>nlstate) {
                   10507:          dcwave[i]=m;
                   10508:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10509:          break;
                   10510:        }
1.126     brouard  10511:     }
1.226     brouard  10512:     
1.126     brouard  10513:     for (i=1; i<=imx; i++) {
                   10514:       if (wav[i]>0){
1.226     brouard  10515:        ageexmed[i]=agev[mw[1][i]][i];
                   10516:        j=wav[i];
                   10517:        agecens[i]=1.; 
                   10518:        
                   10519:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10520:          agecens[i]=agev[mw[j][i]][i];
                   10521:          cens[i]= 1;
                   10522:        }else if (ageexmed[i]< 1) 
                   10523:          cens[i]= -1;
                   10524:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10525:          cens[i]=0 ;
1.126     brouard  10526:       }
                   10527:       else cens[i]=-1;
                   10528:     }
                   10529:     
                   10530:     for (i=1;i<=NDIM;i++) {
                   10531:       for (j=1;j<=NDIM;j++)
1.226     brouard  10532:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10533:     }
                   10534:     
1.145     brouard  10535:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10536:     /*printf("%lf %lf", p[1], p[2]);*/
                   10537:     
                   10538:     
1.136     brouard  10539: #ifdef GSL
                   10540:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10541: #else
1.126     brouard  10542:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10543: #endif
1.201     brouard  10544:     strcpy(filerespow,"POW-MORT_"); 
                   10545:     strcat(filerespow,fileresu);
1.126     brouard  10546:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10547:       printf("Problem with resultfile: %s\n", filerespow);
                   10548:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10549:     }
1.136     brouard  10550: #ifdef GSL
                   10551:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10552: #else
1.126     brouard  10553:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10554: #endif
1.126     brouard  10555:     /*  for (i=1;i<=nlstate;i++)
                   10556:        for(j=1;j<=nlstate+ndeath;j++)
                   10557:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10558:     */
                   10559:     fprintf(ficrespow,"\n");
1.136     brouard  10560: #ifdef GSL
                   10561:     /* gsl starts here */ 
                   10562:     T = gsl_multimin_fminimizer_nmsimplex;
                   10563:     gsl_multimin_fminimizer *sfm = NULL;
                   10564:     gsl_vector *ss, *x;
                   10565:     gsl_multimin_function minex_func;
                   10566: 
                   10567:     /* Initial vertex size vector */
                   10568:     ss = gsl_vector_alloc (NDIM);
                   10569:     
                   10570:     if (ss == NULL){
                   10571:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10572:     }
                   10573:     /* Set all step sizes to 1 */
                   10574:     gsl_vector_set_all (ss, 0.001);
                   10575: 
                   10576:     /* Starting point */
1.126     brouard  10577:     
1.136     brouard  10578:     x = gsl_vector_alloc (NDIM);
                   10579:     
                   10580:     if (x == NULL){
                   10581:       gsl_vector_free(ss);
                   10582:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10583:     }
                   10584:   
                   10585:     /* Initialize method and iterate */
                   10586:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10587:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10588:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10589:     gsl_vector_set(x, 0, p[1]);
                   10590:     gsl_vector_set(x, 1, p[2]);
                   10591: 
                   10592:     minex_func.f = &gompertz_f;
                   10593:     minex_func.n = NDIM;
                   10594:     minex_func.params = (void *)&p; /* ??? */
                   10595:     
                   10596:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10597:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10598:     
                   10599:     printf("Iterations beginning .....\n\n");
                   10600:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10601: 
                   10602:     iteri=0;
                   10603:     while (rval == GSL_CONTINUE){
                   10604:       iteri++;
                   10605:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10606:       
                   10607:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10608:       fflush(0);
                   10609:       
                   10610:       if (status) 
                   10611:         break;
                   10612:       
                   10613:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10614:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10615:       
                   10616:       if (rval == GSL_SUCCESS)
                   10617:         printf ("converged to a local maximum at\n");
                   10618:       
                   10619:       printf("%5d ", iteri);
                   10620:       for (it = 0; it < NDIM; it++){
                   10621:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10622:       }
                   10623:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10624:     }
                   10625:     
                   10626:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10627:     
                   10628:     gsl_vector_free(x); /* initial values */
                   10629:     gsl_vector_free(ss); /* inital step size */
                   10630:     for (it=0; it<NDIM; it++){
                   10631:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10632:       fprintf(ficrespow," %.12lf", p[it]);
                   10633:     }
                   10634:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10635: #endif
                   10636: #ifdef POWELL
                   10637:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10638: #endif  
1.126     brouard  10639:     fclose(ficrespow);
                   10640:     
1.203     brouard  10641:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10642: 
                   10643:     for(i=1; i <=NDIM; i++)
                   10644:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10645:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10646:     
                   10647:     printf("\nCovariance matrix\n ");
1.203     brouard  10648:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10649:     for(i=1; i <=NDIM; i++) {
                   10650:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10651:                                printf("%f ",matcov[i][j]);
                   10652:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10653:       }
1.203     brouard  10654:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10655:     }
                   10656:     
                   10657:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10658:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10659:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10660:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10661:     }
1.126     brouard  10662:     lsurv=vector(1,AGESUP);
                   10663:     lpop=vector(1,AGESUP);
                   10664:     tpop=vector(1,AGESUP);
                   10665:     lsurv[agegomp]=100000;
                   10666:     
                   10667:     for (k=agegomp;k<=AGESUP;k++) {
                   10668:       agemortsup=k;
                   10669:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10670:     }
                   10671:     
                   10672:     for (k=agegomp;k<agemortsup;k++)
                   10673:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10674:     
                   10675:     for (k=agegomp;k<agemortsup;k++){
                   10676:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10677:       sumlpop=sumlpop+lpop[k];
                   10678:     }
                   10679:     
                   10680:     tpop[agegomp]=sumlpop;
                   10681:     for (k=agegomp;k<(agemortsup-3);k++){
                   10682:       /*  tpop[k+1]=2;*/
                   10683:       tpop[k+1]=tpop[k]-lpop[k];
                   10684:     }
                   10685:     
                   10686:     
                   10687:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10688:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10689:       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]);
                   10690:     
                   10691:     
                   10692:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10693:                ageminpar=50;
                   10694:                agemaxpar=100;
1.194     brouard  10695:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10696:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10697: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10698: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10699:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10700: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10701: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10702:     }else{
                   10703:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10704:                        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  10705:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10706:                }
1.201     brouard  10707:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10708:                     stepm, weightopt,\
                   10709:                     model,imx,p,matcov,agemortsup);
                   10710:     
                   10711:     free_vector(lsurv,1,AGESUP);
                   10712:     free_vector(lpop,1,AGESUP);
                   10713:     free_vector(tpop,1,AGESUP);
1.220     brouard  10714:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10715:     free_ivector(cens,1,n);
                   10716:     free_vector(agecens,1,n);
                   10717:     free_ivector(dcwave,1,n);
1.220     brouard  10718: #ifdef GSL
1.136     brouard  10719: #endif
1.186     brouard  10720:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10721:   /* Standard  */
                   10722:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10723:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10724:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10725:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10726:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10727:     for (k=1; k<=npar;k++)
                   10728:       printf(" %d %8.5f",k,p[k]);
                   10729:     printf("\n");
1.205     brouard  10730:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10731:       /* mlikeli uses func not funcone */
1.247     brouard  10732:       /* for(i=1;i<nlstate;i++){ */
                   10733:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   10734:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   10735:       /* } */
1.205     brouard  10736:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10737:     }
                   10738:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10739:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10740:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10741:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10742:     }
                   10743:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10744:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10745:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10746:     for (k=1; k<=npar;k++)
                   10747:       printf(" %d %8.5f",k,p[k]);
                   10748:     printf("\n");
                   10749:     
                   10750:     /*--------- results files --------------*/
1.224     brouard  10751:     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  10752:     
                   10753:     
                   10754:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10755:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10756:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10757:     for(i=1,jk=1; i <=nlstate; i++){
                   10758:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10759:        if (k != i) {
                   10760:          printf("%d%d ",i,k);
                   10761:          fprintf(ficlog,"%d%d ",i,k);
                   10762:          fprintf(ficres,"%1d%1d ",i,k);
                   10763:          for(j=1; j <=ncovmodel; j++){
                   10764:            printf("%12.7f ",p[jk]);
                   10765:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10766:            fprintf(ficres,"%12.7f ",p[jk]);
                   10767:            jk++; 
                   10768:          }
                   10769:          printf("\n");
                   10770:          fprintf(ficlog,"\n");
                   10771:          fprintf(ficres,"\n");
                   10772:        }
1.126     brouard  10773:       }
                   10774:     }
1.203     brouard  10775:     if(mle != 0){
                   10776:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10777:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10778:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10779:       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");
                   10780:       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");
                   10781:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10782:        for(k=1; k <=(nlstate+ndeath); k++){
                   10783:          if (k != i) {
                   10784:            printf("%d%d ",i,k);
                   10785:            fprintf(ficlog,"%d%d ",i,k);
                   10786:            for(j=1; j <=ncovmodel; j++){
                   10787:              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]));
                   10788:              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]));
                   10789:              jk++; 
                   10790:            }
                   10791:            printf("\n");
                   10792:            fprintf(ficlog,"\n");
                   10793:          }
                   10794:        }
1.193     brouard  10795:       }
1.203     brouard  10796:     } /* end of hesscov and Wald tests */
1.225     brouard  10797:     
1.203     brouard  10798:     /*  */
1.126     brouard  10799:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10800:     printf("# Scales (for hessian or gradient estimation)\n");
                   10801:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10802:     for(i=1,jk=1; i <=nlstate; i++){
                   10803:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10804:        if (j!=i) {
                   10805:          fprintf(ficres,"%1d%1d",i,j);
                   10806:          printf("%1d%1d",i,j);
                   10807:          fprintf(ficlog,"%1d%1d",i,j);
                   10808:          for(k=1; k<=ncovmodel;k++){
                   10809:            printf(" %.5e",delti[jk]);
                   10810:            fprintf(ficlog," %.5e",delti[jk]);
                   10811:            fprintf(ficres," %.5e",delti[jk]);
                   10812:            jk++;
                   10813:          }
                   10814:          printf("\n");
                   10815:          fprintf(ficlog,"\n");
                   10816:          fprintf(ficres,"\n");
                   10817:        }
1.126     brouard  10818:       }
                   10819:     }
                   10820:     
                   10821:     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  10822:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10823:       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");
                   10824:     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");
                   10825:     /* # 121 Var(a12)\n\ */
                   10826:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10827:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10828:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10829:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10830:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10831:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10832:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10833:     
                   10834:     
                   10835:     /* Just to have a covariance matrix which will be more understandable
                   10836:        even is we still don't want to manage dictionary of variables
                   10837:     */
                   10838:     for(itimes=1;itimes<=2;itimes++){
                   10839:       jj=0;
                   10840:       for(i=1; i <=nlstate; i++){
1.225     brouard  10841:        for(j=1; j <=nlstate+ndeath; j++){
                   10842:          if(j==i) continue;
                   10843:          for(k=1; k<=ncovmodel;k++){
                   10844:            jj++;
                   10845:            ca[0]= k+'a'-1;ca[1]='\0';
                   10846:            if(itimes==1){
                   10847:              if(mle>=1)
                   10848:                printf("#%1d%1d%d",i,j,k);
                   10849:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10850:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10851:            }else{
                   10852:              if(mle>=1)
                   10853:                printf("%1d%1d%d",i,j,k);
                   10854:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10855:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10856:            }
                   10857:            ll=0;
                   10858:            for(li=1;li <=nlstate; li++){
                   10859:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10860:                if(lj==li) continue;
                   10861:                for(lk=1;lk<=ncovmodel;lk++){
                   10862:                  ll++;
                   10863:                  if(ll<=jj){
                   10864:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10865:                    if(ll<jj){
                   10866:                      if(itimes==1){
                   10867:                        if(mle>=1)
                   10868:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10869:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10870:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10871:                      }else{
                   10872:                        if(mle>=1)
                   10873:                          printf(" %.5e",matcov[jj][ll]); 
                   10874:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10875:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10876:                      }
                   10877:                    }else{
                   10878:                      if(itimes==1){
                   10879:                        if(mle>=1)
                   10880:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10881:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10882:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10883:                      }else{
                   10884:                        if(mle>=1)
                   10885:                          printf(" %.7e",matcov[jj][ll]); 
                   10886:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10887:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10888:                      }
                   10889:                    }
                   10890:                  }
                   10891:                } /* end lk */
                   10892:              } /* end lj */
                   10893:            } /* end li */
                   10894:            if(mle>=1)
                   10895:              printf("\n");
                   10896:            fprintf(ficlog,"\n");
                   10897:            fprintf(ficres,"\n");
                   10898:            numlinepar++;
                   10899:          } /* end k*/
                   10900:        } /*end j */
1.126     brouard  10901:       } /* end i */
                   10902:     } /* end itimes */
                   10903:     
                   10904:     fflush(ficlog);
                   10905:     fflush(ficres);
1.225     brouard  10906:     while(fgets(line, MAXLINE, ficpar)) {
                   10907:       /* If line starts with a # it is a comment */
                   10908:       if (line[0] == '#') {
                   10909:        numlinepar++;
                   10910:        fputs(line,stdout);
                   10911:        fputs(line,ficparo);
                   10912:        fputs(line,ficlog);
                   10913:        continue;
                   10914:       }else
                   10915:        break;
                   10916:     }
                   10917:     
1.209     brouard  10918:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10919:     /*   ungetc(c,ficpar); */
                   10920:     /*   fgets(line, MAXLINE, ficpar); */
                   10921:     /*   fputs(line,stdout); */
                   10922:     /*   fputs(line,ficparo); */
                   10923:     /* } */
                   10924:     /* ungetc(c,ficpar); */
1.126     brouard  10925:     
                   10926:     estepm=0;
1.209     brouard  10927:     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  10928:       
                   10929:       if (num_filled != 6) {
                   10930:        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);
                   10931:        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);
                   10932:        goto end;
                   10933:       }
                   10934:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10935:     }
                   10936:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10937:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10938:     
1.209     brouard  10939:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10940:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10941:     if (fage <= 2) {
                   10942:       bage = ageminpar;
                   10943:       fage = agemaxpar;
                   10944:     }
                   10945:     
                   10946:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10947:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10948:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10949:                
1.186     brouard  10950:     /* Other stuffs, more or less useful */    
1.126     brouard  10951:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10952:       ungetc(c,ficpar);
                   10953:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10954:       fputs(line,stdout);
1.126     brouard  10955:       fputs(line,ficparo);
                   10956:     }
                   10957:     ungetc(c,ficpar);
                   10958:     
                   10959:     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);
                   10960:     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);
                   10961:     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);
                   10962:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10963:     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);
                   10964:     
                   10965:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10966:       ungetc(c,ficpar);
                   10967:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10968:       fputs(line,stdout);
1.126     brouard  10969:       fputs(line,ficparo);
                   10970:     }
                   10971:     ungetc(c,ficpar);
                   10972:     
                   10973:     
                   10974:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10975:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10976:     
                   10977:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10978:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10979:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10980:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10981:     
                   10982:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10983:       ungetc(c,ficpar);
                   10984:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10985:       fputs(line,stdout);
1.238     brouard  10986:       fputs(line,ficres);
1.126     brouard  10987:       fputs(line,ficparo);
                   10988:     }
                   10989:     ungetc(c,ficpar);
                   10990:     
                   10991:     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);
                   10992:     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);
                   10993:     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);
                   10994:     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);
                   10995:     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);
                   10996:     /* day and month of proj2 are not used but only year anproj2.*/
                   10997:     
1.217     brouard  10998:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10999:       ungetc(c,ficpar);
                   11000:       fgets(line, MAXLINE, ficpar);
                   11001:       fputs(line,stdout);
                   11002:       fputs(line,ficparo);
1.238     brouard  11003:       fputs(line,ficres);
1.217     brouard  11004:     }
                   11005:     ungetc(c,ficpar);
                   11006:     
                   11007:     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  11008:     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);
                   11009:     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);
                   11010:     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  11011:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  11012:     
1.230     brouard  11013:     /* Results */
1.235     brouard  11014:     nresult=0;
1.230     brouard  11015:     while(fgets(line, MAXLINE, ficpar)) {
                   11016:       /* If line starts with a # it is a comment */
                   11017:       if (line[0] == '#') {
                   11018:        numlinepar++;
                   11019:        fputs(line,stdout);
                   11020:        fputs(line,ficparo);
                   11021:        fputs(line,ficlog);
1.238     brouard  11022:        fputs(line,ficres);
1.230     brouard  11023:        continue;
                   11024:       }else
                   11025:        break;
                   11026:     }
1.240     brouard  11027:     if (!feof(ficpar))
1.230     brouard  11028:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240     brouard  11029:       if (num_filled == 0){
1.230     brouard  11030:        resultline[0]='\0';
1.240     brouard  11031:       break;
                   11032:       } else if (num_filled != 1){
1.230     brouard  11033:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   11034:       }
1.235     brouard  11035:       nresult++; /* Sum of resultlines */
                   11036:       printf("Result %d: result=%s\n",nresult, resultline);
                   11037:       if(nresult > MAXRESULTLINES){
                   11038:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   11039:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   11040:        goto end;
                   11041:       }
                   11042:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  11043:       fprintf(ficparo,"result: %s\n",resultline);
                   11044:       fprintf(ficres,"result: %s\n",resultline);
                   11045:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  11046:       while(fgets(line, MAXLINE, ficpar)) {
                   11047:        /* If line starts with a # it is a comment */
                   11048:        if (line[0] == '#') {
                   11049:          numlinepar++;
                   11050:          fputs(line,stdout);
                   11051:          fputs(line,ficparo);
1.238     brouard  11052:          fputs(line,ficres);
1.230     brouard  11053:          fputs(line,ficlog);
                   11054:          continue;
                   11055:        }else
                   11056:          break;
                   11057:       }
                   11058:       if (feof(ficpar))
                   11059:        break;
                   11060:       else{ /* Processess output results for this combination of covariate values */
                   11061:       }                                   
1.240     brouard  11062:     } /* end while */
1.230     brouard  11063: 
                   11064: 
1.126     brouard  11065:     
1.230     brouard  11066:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  11067:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  11068:     
                   11069:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  11070:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  11071:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11072: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11073: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  11074:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11075: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11076: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  11077:     }else{
1.218     brouard  11078:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  11079:     }
                   11080:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  11081:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   11082:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  11083:                
1.225     brouard  11084:     /*------------ free_vector  -------------*/
                   11085:     /*  chdir(path); */
1.220     brouard  11086:                
1.215     brouard  11087:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   11088:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   11089:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   11090:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  11091:     free_lvector(num,1,n);
                   11092:     free_vector(agedc,1,n);
                   11093:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   11094:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   11095:     fclose(ficparo);
                   11096:     fclose(ficres);
1.220     brouard  11097:                
                   11098:                
1.186     brouard  11099:     /* Other results (useful)*/
1.220     brouard  11100:                
                   11101:                
1.126     brouard  11102:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11103:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11104:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11105:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11106:     fclose(ficrespl);
                   11107: 
                   11108:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11109:     /*#include "hpijx.h"*/
                   11110:     hPijx(p, bage, fage);
1.145     brouard  11111:     fclose(ficrespij);
1.227     brouard  11112:     
1.220     brouard  11113:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11114:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11115:     k=1;
1.126     brouard  11116:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11117:     
1.219     brouard  11118:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11119:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11120:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11121:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11122:        for(k=1;k<=ncovcombmax;k++)
                   11123:          probs[i][j][k]=0.;
1.219     brouard  11124:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11125:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11126:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11127:       for(i=1;i<=AGESUP;i++)
                   11128:        for(j=1;j<=nlstate;j++)
                   11129:          for(k=1;k<=ncovcombmax;k++)
                   11130:            mobaverages[i][j][k]=0.;
1.219     brouard  11131:       mobaverage=mobaverages;
                   11132:       if (mobilav!=0) {
1.235     brouard  11133:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  11134:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11135:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11136:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11137:        }
1.219     brouard  11138:       }
                   11139:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11140:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11141:       else if (mobilavproj !=0) {
1.235     brouard  11142:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  11143:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11144:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11145:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11146:        }
1.219     brouard  11147:       }
                   11148:     }/* end if moving average */
1.227     brouard  11149:     
1.126     brouard  11150:     /*---------- Forecasting ------------------*/
                   11151:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11152:     if(prevfcast==1){
                   11153:       /*    if(stepm ==1){*/
1.225     brouard  11154:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11155:     }
1.217     brouard  11156:     if(backcast==1){
1.219     brouard  11157:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11158:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11159:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11160: 
                   11161:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11162: 
                   11163:       bprlim=matrix(1,nlstate,1,nlstate);
                   11164:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11165:       fclose(ficresplb);
                   11166: 
1.222     brouard  11167:       hBijx(p, bage, fage, mobaverage);
                   11168:       fclose(ficrespijb);
1.219     brouard  11169:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11170: 
                   11171:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11172:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11173:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11174:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11175:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11176:     }
1.217     brouard  11177:     
1.186     brouard  11178:  
                   11179:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11180: 
1.215     brouard  11181:     free_ivector(wav,1,imx);
                   11182:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11183:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11184:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11185:                
                   11186:                
1.127     brouard  11187:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11188:                
1.201     brouard  11189:     strcpy(filerese,"E_");
                   11190:     strcat(filerese,fileresu);
1.126     brouard  11191:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11192:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11193:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11194:     }
1.208     brouard  11195:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11196:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11197: 
                   11198:     pstamp(ficreseij);
1.219     brouard  11199:                
1.235     brouard  11200:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11201:     if (cptcovn < 1){i1=1;}
                   11202:     
                   11203:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11204:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11205:       if(TKresult[nres]!= k)
                   11206:        continue;
1.219     brouard  11207:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11208:       printf("\n#****** ");
1.225     brouard  11209:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11210:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11211:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11212:       }
                   11213:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11214:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11215:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11216:       }
                   11217:       fprintf(ficreseij,"******\n");
1.235     brouard  11218:       printf("******\n");
1.219     brouard  11219:       
                   11220:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11221:       oldm=oldms;savm=savms;
1.235     brouard  11222:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11223:       
1.219     brouard  11224:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11225:     }
                   11226:     fclose(ficreseij);
1.208     brouard  11227:     printf("done evsij\n");fflush(stdout);
                   11228:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11229:                
1.227     brouard  11230:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11231:                
                   11232:                
1.201     brouard  11233:     strcpy(filerest,"T_");
                   11234:     strcat(filerest,fileresu);
1.127     brouard  11235:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11236:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11237:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11238:     }
1.208     brouard  11239:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11240:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11241:                
1.126     brouard  11242: 
1.201     brouard  11243:     strcpy(fileresstde,"STDE_");
                   11244:     strcat(fileresstde,fileresu);
1.126     brouard  11245:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11246:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11247:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11248:     }
1.227     brouard  11249:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11250:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11251: 
1.201     brouard  11252:     strcpy(filerescve,"CVE_");
                   11253:     strcat(filerescve,fileresu);
1.126     brouard  11254:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11255:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11256:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11257:     }
1.227     brouard  11258:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11259:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11260: 
1.201     brouard  11261:     strcpy(fileresv,"V_");
                   11262:     strcat(fileresv,fileresu);
1.126     brouard  11263:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11264:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11265:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11266:     }
1.227     brouard  11267:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11268:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11269: 
1.145     brouard  11270:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11271:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11272:           
1.235     brouard  11273:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11274:     if (cptcovn < 1){i1=1;}
                   11275:     
                   11276:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11277:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11278:       if(TKresult[nres]!= k)
                   11279:        continue;
1.242     brouard  11280:       printf("\n#****** Result for:");
                   11281:       fprintf(ficrest,"\n#****** Result for:");
                   11282:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11283:       for(j=1;j<=cptcoveff;j++){ 
                   11284:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11285:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11286:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11287:       }
1.235     brouard  11288:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11289:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11290:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11291:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11292:       }        
1.208     brouard  11293:       fprintf(ficrest,"******\n");
1.227     brouard  11294:       fprintf(ficlog,"******\n");
                   11295:       printf("******\n");
1.208     brouard  11296:       
                   11297:       fprintf(ficresstdeij,"\n#****** ");
                   11298:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11299:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11300:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11301:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11302:       }
1.235     brouard  11303:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11304:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11305:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11306:       }        
1.208     brouard  11307:       fprintf(ficresstdeij,"******\n");
                   11308:       fprintf(ficrescveij,"******\n");
                   11309:       
                   11310:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11311:       /* pstamp(ficresvij); */
1.225     brouard  11312:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11313:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11314:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11315:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11316:       }        
1.208     brouard  11317:       fprintf(ficresvij,"******\n");
                   11318:       
                   11319:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11320:       oldm=oldms;savm=savms;
1.235     brouard  11321:       printf(" cvevsij ");
                   11322:       fprintf(ficlog, " cvevsij ");
                   11323:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11324:       printf(" end cvevsij \n ");
                   11325:       fprintf(ficlog, " end cvevsij \n ");
                   11326:       
                   11327:       /*
                   11328:        */
                   11329:       /* goto endfree; */
                   11330:       
                   11331:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11332:       pstamp(ficrest);
                   11333:       
                   11334:       
                   11335:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11336:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11337:        cptcod= 0; /* To be deleted */
                   11338:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11339:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11340:        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  11341:        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 ");
                   11342:        if(vpopbased==1)
                   11343:          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);
                   11344:        else
                   11345:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11346:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11347:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11348:        fprintf(ficrest,"\n");
                   11349:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11350:        epj=vector(1,nlstate+1);
                   11351:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11352:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11353:        for(age=bage; age <=fage ;age++){
1.235     brouard  11354:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11355:          if (vpopbased==1) {
                   11356:            if(mobilav ==0){
                   11357:              for(i=1; i<=nlstate;i++)
                   11358:                prlim[i][i]=probs[(int)age][i][k];
                   11359:            }else{ /* mobilav */ 
                   11360:              for(i=1; i<=nlstate;i++)
                   11361:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11362:            }
                   11363:          }
1.219     brouard  11364:          
1.227     brouard  11365:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11366:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11367:          /* printf(" age %4.0f ",age); */
                   11368:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11369:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11370:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11371:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11372:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11373:            }
                   11374:            epj[nlstate+1] +=epj[j];
                   11375:          }
                   11376:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11377:          
1.227     brouard  11378:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11379:            for(j=1;j <=nlstate;j++)
                   11380:              vepp += vareij[i][j][(int)age];
                   11381:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11382:          for(j=1;j <=nlstate;j++){
                   11383:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11384:          }
                   11385:          fprintf(ficrest,"\n");
                   11386:        }
1.208     brouard  11387:       } /* End vpopbased */
                   11388:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11389:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11390:       free_vector(epj,1,nlstate+1);
1.235     brouard  11391:       printf("done selection\n");fflush(stdout);
                   11392:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11393:       
1.145     brouard  11394:       /*}*/
1.235     brouard  11395:     } /* End k selection */
1.227     brouard  11396: 
                   11397:     printf("done State-specific expectancies\n");fflush(stdout);
                   11398:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11399: 
1.126     brouard  11400:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11401:     
1.201     brouard  11402:     strcpy(fileresvpl,"VPL_");
                   11403:     strcat(fileresvpl,fileresu);
1.126     brouard  11404:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11405:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11406:       exit(0);
                   11407:     }
1.208     brouard  11408:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11409:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11410:     
1.145     brouard  11411:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11412:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11413:     
1.235     brouard  11414:     i1=pow(2,cptcoveff);
                   11415:     if (cptcovn < 1){i1=1;}
                   11416: 
                   11417:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11418:     for(k=1; k<=i1;k++){
                   11419:       if(TKresult[nres]!= k)
                   11420:        continue;
1.227     brouard  11421:       fprintf(ficresvpl,"\n#****** ");
                   11422:       printf("\n#****** ");
                   11423:       fprintf(ficlog,"\n#****** ");
                   11424:       for(j=1;j<=cptcoveff;j++) {
                   11425:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11426:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11427:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11428:       }
1.235     brouard  11429:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11430:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11431:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11432:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11433:       }        
1.227     brouard  11434:       fprintf(ficresvpl,"******\n");
                   11435:       printf("******\n");
                   11436:       fprintf(ficlog,"******\n");
                   11437:       
                   11438:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11439:       oldm=oldms;savm=savms;
1.235     brouard  11440:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11441:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11442:       /*}*/
1.126     brouard  11443:     }
1.227     brouard  11444:     
1.126     brouard  11445:     fclose(ficresvpl);
1.208     brouard  11446:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11447:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11448:     
                   11449:     free_vector(weight,1,n);
                   11450:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11451:     free_imatrix(s,1,maxwav+1,1,n);
                   11452:     free_matrix(anint,1,maxwav,1,n); 
                   11453:     free_matrix(mint,1,maxwav,1,n);
                   11454:     free_ivector(cod,1,n);
                   11455:     free_ivector(tab,1,NCOVMAX);
                   11456:     fclose(ficresstdeij);
                   11457:     fclose(ficrescveij);
                   11458:     fclose(ficresvij);
                   11459:     fclose(ficrest);
                   11460:     fclose(ficpar);
                   11461:     
                   11462:     
1.126     brouard  11463:     /*---------- End : free ----------------*/
1.219     brouard  11464:     if (mobilav!=0 ||mobilavproj !=0)
                   11465:       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  11466:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11467:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11468:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11469:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11470:   /* endfree:*/
                   11471:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11472:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11473:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11474:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11475:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11476:   free_matrix(coqvar,1,maxwav,1,n);
                   11477:   free_matrix(covar,0,NCOVMAX,1,n);
                   11478:   free_matrix(matcov,1,npar,1,npar);
                   11479:   free_matrix(hess,1,npar,1,npar);
                   11480:   /*free_vector(delti,1,npar);*/
                   11481:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11482:   free_matrix(agev,1,maxwav,1,imx);
                   11483:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11484:   
                   11485:   free_ivector(ncodemax,1,NCOVMAX);
                   11486:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11487:   free_ivector(Dummy,-1,NCOVMAX);
                   11488:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11489:   free_ivector(DummyV,1,NCOVMAX);
                   11490:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11491:   free_ivector(Typevar,-1,NCOVMAX);
                   11492:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11493:   free_ivector(TvarsQ,1,NCOVMAX);
                   11494:   free_ivector(TvarsQind,1,NCOVMAX);
                   11495:   free_ivector(TvarsD,1,NCOVMAX);
                   11496:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11497:   free_ivector(TvarFD,1,NCOVMAX);
                   11498:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11499:   free_ivector(TvarF,1,NCOVMAX);
                   11500:   free_ivector(TvarFind,1,NCOVMAX);
                   11501:   free_ivector(TvarV,1,NCOVMAX);
                   11502:   free_ivector(TvarVind,1,NCOVMAX);
                   11503:   free_ivector(TvarA,1,NCOVMAX);
                   11504:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11505:   free_ivector(TvarFQ,1,NCOVMAX);
                   11506:   free_ivector(TvarFQind,1,NCOVMAX);
                   11507:   free_ivector(TvarVD,1,NCOVMAX);
                   11508:   free_ivector(TvarVDind,1,NCOVMAX);
                   11509:   free_ivector(TvarVQ,1,NCOVMAX);
                   11510:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11511:   free_ivector(Tvarsel,1,NCOVMAX);
                   11512:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11513:   free_ivector(Tposprod,1,NCOVMAX);
                   11514:   free_ivector(Tprod,1,NCOVMAX);
                   11515:   free_ivector(Tvaraff,1,NCOVMAX);
                   11516:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11517:   free_ivector(Tage,1,NCOVMAX);
                   11518:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11519:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11520:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11521:   
                   11522:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11523:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11524:   fflush(fichtm);
                   11525:   fflush(ficgp);
                   11526:   
1.227     brouard  11527:   
1.126     brouard  11528:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11529:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11530:     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  11531:   }else{
                   11532:     printf("End of Imach\n");
                   11533:     fprintf(ficlog,"End of Imach\n");
                   11534:   }
                   11535:   printf("See log file on %s\n",filelog);
                   11536:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11537:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11538:   rend_time = time(NULL);  
                   11539:   end_time = *localtime(&rend_time);
                   11540:   /* tml = *localtime(&end_time.tm_sec); */
                   11541:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11542:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11543:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11544:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11545:   
1.157     brouard  11546:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11547:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11548:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11549:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11550: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11551:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11552:   fclose(fichtm);
                   11553:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11554:   fclose(fichtmcov);
                   11555:   fclose(ficgp);
                   11556:   fclose(ficlog);
                   11557:   /*------ End -----------*/
1.227     brouard  11558:   
                   11559:   
                   11560:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11561: #ifdef WIN32
1.227     brouard  11562:   if (_chdir(pathcd) != 0)
                   11563:     printf("Can't move to directory %s!\n",path);
                   11564:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11565: #else
1.227     brouard  11566:     if(chdir(pathcd) != 0)
                   11567:       printf("Can't move to directory %s!\n", path);
                   11568:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11569: #endif 
1.126     brouard  11570:     printf("Current directory %s!\n",pathcd);
                   11571:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11572:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11573: #ifdef _WIN32
1.126     brouard  11574:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11575: #endif
                   11576:   if(!stat(plotcmd,&info)){
1.158     brouard  11577:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11578:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11579:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11580:     }else
                   11581:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11582: #ifdef __unix
1.126     brouard  11583:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11584:     if(!stat(plotcmd,&info)){
1.158     brouard  11585:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11586:     }else
                   11587:       strcpy(pplotcmd,plotcmd);
                   11588: #endif
                   11589:   }else
                   11590:     strcpy(pplotcmd,plotcmd);
                   11591:   
                   11592:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11593:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11594:   
1.126     brouard  11595:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11596:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11597:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11598:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11599:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11600:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11601:   }
1.158     brouard  11602:   printf(" Successful, please wait...");
1.126     brouard  11603:   while (z[0] != 'q') {
                   11604:     /* chdir(path); */
1.154     brouard  11605:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11606:     scanf("%s",z);
                   11607: /*     if (z[0] == 'c') system("./imach"); */
                   11608:     if (z[0] == 'e') {
1.158     brouard  11609: #ifdef __APPLE__
1.152     brouard  11610:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11611: #elif __linux
                   11612:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11613: #else
1.152     brouard  11614:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11615: #endif
                   11616:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11617:       system(pplotcmd);
1.126     brouard  11618:     }
                   11619:     else if (z[0] == 'g') system(plotcmd);
                   11620:     else if (z[0] == 'q') exit(0);
                   11621:   }
1.227     brouard  11622: end:
1.126     brouard  11623:   while (z[0] != 'q') {
1.195     brouard  11624:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11625:     scanf("%s",z);
                   11626:   }
                   11627: }

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