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

1.257   ! brouard     1: /* $Id: imach.c,v 1.256 2017/03/27 05:50:23 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.257   ! brouard     4:   Revision 1.256  2017/03/27 05:50:23  brouard
        !             5:   Summary: Temporary
        !             6: 
1.256     brouard     7:   Revision 1.255  2017/03/08 16:02:28  brouard
                      8:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                      9: 
1.255     brouard    10:   Revision 1.254  2017/03/08 07:13:00  brouard
                     11:   Summary: Fixing data parameter line
                     12: 
1.254     brouard    13:   Revision 1.253  2016/12/15 11:59:41  brouard
                     14:   Summary: 0.99 in progress
                     15: 
1.253     brouard    16:   Revision 1.252  2016/09/15 21:15:37  brouard
                     17:   *** empty log message ***
                     18: 
1.252     brouard    19:   Revision 1.251  2016/09/15 15:01:13  brouard
                     20:   Summary: not working
                     21: 
1.251     brouard    22:   Revision 1.250  2016/09/08 16:07:27  brouard
                     23:   Summary: continue
                     24: 
1.250     brouard    25:   Revision 1.249  2016/09/07 17:14:18  brouard
                     26:   Summary: Starting values from frequencies
                     27: 
1.249     brouard    28:   Revision 1.248  2016/09/07 14:10:18  brouard
                     29:   *** empty log message ***
                     30: 
1.248     brouard    31:   Revision 1.247  2016/09/02 11:11:21  brouard
                     32:   *** empty log message ***
                     33: 
1.247     brouard    34:   Revision 1.246  2016/09/02 08:49:22  brouard
                     35:   *** empty log message ***
                     36: 
1.246     brouard    37:   Revision 1.245  2016/09/02 07:25:01  brouard
                     38:   *** empty log message ***
                     39: 
1.245     brouard    40:   Revision 1.244  2016/09/02 07:17:34  brouard
                     41:   *** empty log message ***
                     42: 
1.244     brouard    43:   Revision 1.243  2016/09/02 06:45:35  brouard
                     44:   *** empty log message ***
                     45: 
1.243     brouard    46:   Revision 1.242  2016/08/30 15:01:20  brouard
                     47:   Summary: Fixing a lots
                     48: 
1.242     brouard    49:   Revision 1.241  2016/08/29 17:17:25  brouard
                     50:   Summary: gnuplot problem in Back projection to fix
                     51: 
1.241     brouard    52:   Revision 1.240  2016/08/29 07:53:18  brouard
                     53:   Summary: Better
                     54: 
1.240     brouard    55:   Revision 1.239  2016/08/26 15:51:03  brouard
                     56:   Summary: Improvement in Powell output in order to copy and paste
                     57: 
                     58:   Author:
                     59: 
1.239     brouard    60:   Revision 1.238  2016/08/26 14:23:35  brouard
                     61:   Summary: Starting tests of 0.99
                     62: 
1.238     brouard    63:   Revision 1.237  2016/08/26 09:20:19  brouard
                     64:   Summary: to valgrind
                     65: 
1.237     brouard    66:   Revision 1.236  2016/08/25 10:50:18  brouard
                     67:   *** empty log message ***
                     68: 
1.236     brouard    69:   Revision 1.235  2016/08/25 06:59:23  brouard
                     70:   *** empty log message ***
                     71: 
1.235     brouard    72:   Revision 1.234  2016/08/23 16:51:20  brouard
                     73:   *** empty log message ***
                     74: 
1.234     brouard    75:   Revision 1.233  2016/08/23 07:40:50  brouard
                     76:   Summary: not working
                     77: 
1.233     brouard    78:   Revision 1.232  2016/08/22 14:20:21  brouard
                     79:   Summary: not working
                     80: 
1.232     brouard    81:   Revision 1.231  2016/08/22 07:17:15  brouard
                     82:   Summary: not working
                     83: 
1.231     brouard    84:   Revision 1.230  2016/08/22 06:55:53  brouard
                     85:   Summary: Not working
                     86: 
1.230     brouard    87:   Revision 1.229  2016/07/23 09:45:53  brouard
                     88:   Summary: Completing for func too
                     89: 
1.229     brouard    90:   Revision 1.228  2016/07/22 17:45:30  brouard
                     91:   Summary: Fixing some arrays, still debugging
                     92: 
1.227     brouard    93:   Revision 1.226  2016/07/12 18:42:34  brouard
                     94:   Summary: temp
                     95: 
1.226     brouard    96:   Revision 1.225  2016/07/12 08:40:03  brouard
                     97:   Summary: saving but not running
                     98: 
1.225     brouard    99:   Revision 1.224  2016/07/01 13:16:01  brouard
                    100:   Summary: Fixes
                    101: 
1.224     brouard   102:   Revision 1.223  2016/02/19 09:23:35  brouard
                    103:   Summary: temporary
                    104: 
1.223     brouard   105:   Revision 1.222  2016/02/17 08:14:50  brouard
                    106:   Summary: Probably last 0.98 stable version 0.98r6
                    107: 
1.222     brouard   108:   Revision 1.221  2016/02/15 23:35:36  brouard
                    109:   Summary: minor bug
                    110: 
1.220     brouard   111:   Revision 1.219  2016/02/15 00:48:12  brouard
                    112:   *** empty log message ***
                    113: 
1.219     brouard   114:   Revision 1.218  2016/02/12 11:29:23  brouard
                    115:   Summary: 0.99 Back projections
                    116: 
1.218     brouard   117:   Revision 1.217  2015/12/23 17:18:31  brouard
                    118:   Summary: Experimental backcast
                    119: 
1.217     brouard   120:   Revision 1.216  2015/12/18 17:32:11  brouard
                    121:   Summary: 0.98r4 Warning and status=-2
                    122: 
                    123:   Version 0.98r4 is now:
                    124:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    125:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    126:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    127: 
1.216     brouard   128:   Revision 1.215  2015/12/16 08:52:24  brouard
                    129:   Summary: 0.98r4 working
                    130: 
1.215     brouard   131:   Revision 1.214  2015/12/16 06:57:54  brouard
                    132:   Summary: temporary not working
                    133: 
1.214     brouard   134:   Revision 1.213  2015/12/11 18:22:17  brouard
                    135:   Summary: 0.98r4
                    136: 
1.213     brouard   137:   Revision 1.212  2015/11/21 12:47:24  brouard
                    138:   Summary: minor typo
                    139: 
1.212     brouard   140:   Revision 1.211  2015/11/21 12:41:11  brouard
                    141:   Summary: 0.98r3 with some graph of projected cross-sectional
                    142: 
                    143:   Author: Nicolas Brouard
                    144: 
1.211     brouard   145:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   146:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   147:   Summary: Adding ftolpl parameter
                    148:   Author: N Brouard
                    149: 
                    150:   We had difficulties to get smoothed confidence intervals. It was due
                    151:   to the period prevalence which wasn't computed accurately. The inner
                    152:   parameter ftolpl is now an outer parameter of the .imach parameter
                    153:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    154:   computation are long.
                    155: 
1.209     brouard   156:   Revision 1.208  2015/11/17 14:31:57  brouard
                    157:   Summary: temporary
                    158: 
1.208     brouard   159:   Revision 1.207  2015/10/27 17:36:57  brouard
                    160:   *** empty log message ***
                    161: 
1.207     brouard   162:   Revision 1.206  2015/10/24 07:14:11  brouard
                    163:   *** empty log message ***
                    164: 
1.206     brouard   165:   Revision 1.205  2015/10/23 15:50:53  brouard
                    166:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    167: 
1.205     brouard   168:   Revision 1.204  2015/10/01 16:20:26  brouard
                    169:   Summary: Some new graphs of contribution to likelihood
                    170: 
1.204     brouard   171:   Revision 1.203  2015/09/30 17:45:14  brouard
                    172:   Summary: looking at better estimation of the hessian
                    173: 
                    174:   Also a better criteria for convergence to the period prevalence And
                    175:   therefore adding the number of years needed to converge. (The
                    176:   prevalence in any alive state shold sum to one
                    177: 
1.203     brouard   178:   Revision 1.202  2015/09/22 19:45:16  brouard
                    179:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    180: 
1.202     brouard   181:   Revision 1.201  2015/09/15 17:34:58  brouard
                    182:   Summary: 0.98r0
                    183: 
                    184:   - Some new graphs like suvival functions
                    185:   - Some bugs fixed like model=1+age+V2.
                    186: 
1.201     brouard   187:   Revision 1.200  2015/09/09 16:53:55  brouard
                    188:   Summary: Big bug thanks to Flavia
                    189: 
                    190:   Even model=1+age+V2. did not work anymore
                    191: 
1.200     brouard   192:   Revision 1.199  2015/09/07 14:09:23  brouard
                    193:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    194: 
1.199     brouard   195:   Revision 1.198  2015/09/03 07:14:39  brouard
                    196:   Summary: 0.98q5 Flavia
                    197: 
1.198     brouard   198:   Revision 1.197  2015/09/01 18:24:39  brouard
                    199:   *** empty log message ***
                    200: 
1.197     brouard   201:   Revision 1.196  2015/08/18 23:17:52  brouard
                    202:   Summary: 0.98q5
                    203: 
1.196     brouard   204:   Revision 1.195  2015/08/18 16:28:39  brouard
                    205:   Summary: Adding a hack for testing purpose
                    206: 
                    207:   After reading the title, ftol and model lines, if the comment line has
                    208:   a q, starting with #q, the answer at the end of the run is quit. It
                    209:   permits to run test files in batch with ctest. The former workaround was
                    210:   $ echo q | imach foo.imach
                    211: 
1.195     brouard   212:   Revision 1.194  2015/08/18 13:32:00  brouard
                    213:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    214: 
1.194     brouard   215:   Revision 1.193  2015/08/04 07:17:42  brouard
                    216:   Summary: 0.98q4
                    217: 
1.193     brouard   218:   Revision 1.192  2015/07/16 16:49:02  brouard
                    219:   Summary: Fixing some outputs
                    220: 
1.192     brouard   221:   Revision 1.191  2015/07/14 10:00:33  brouard
                    222:   Summary: Some fixes
                    223: 
1.191     brouard   224:   Revision 1.190  2015/05/05 08:51:13  brouard
                    225:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    226: 
                    227:   Fix 1+age+.
                    228: 
1.190     brouard   229:   Revision 1.189  2015/04/30 14:45:16  brouard
                    230:   Summary: 0.98q2
                    231: 
1.189     brouard   232:   Revision 1.188  2015/04/30 08:27:53  brouard
                    233:   *** empty log message ***
                    234: 
1.188     brouard   235:   Revision 1.187  2015/04/29 09:11:15  brouard
                    236:   *** empty log message ***
                    237: 
1.187     brouard   238:   Revision 1.186  2015/04/23 12:01:52  brouard
                    239:   Summary: V1*age is working now, version 0.98q1
                    240: 
                    241:   Some codes had been disabled in order to simplify and Vn*age was
                    242:   working in the optimization phase, ie, giving correct MLE parameters,
                    243:   but, as usual, outputs were not correct and program core dumped.
                    244: 
1.186     brouard   245:   Revision 1.185  2015/03/11 13:26:42  brouard
                    246:   Summary: Inclusion of compile and links command line for Intel Compiler
                    247: 
1.185     brouard   248:   Revision 1.184  2015/03/11 11:52:39  brouard
                    249:   Summary: Back from Windows 8. Intel Compiler
                    250: 
1.184     brouard   251:   Revision 1.183  2015/03/10 20:34:32  brouard
                    252:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    253: 
                    254:   We use directest instead of original Powell test; probably no
                    255:   incidence on the results, but better justifications;
                    256:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    257:   wrong results.
                    258: 
1.183     brouard   259:   Revision 1.182  2015/02/12 08:19:57  brouard
                    260:   Summary: Trying to keep directest which seems simpler and more general
                    261:   Author: Nicolas Brouard
                    262: 
1.182     brouard   263:   Revision 1.181  2015/02/11 23:22:24  brouard
                    264:   Summary: Comments on Powell added
                    265: 
                    266:   Author:
                    267: 
1.181     brouard   268:   Revision 1.180  2015/02/11 17:33:45  brouard
                    269:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    270: 
1.180     brouard   271:   Revision 1.179  2015/01/04 09:57:06  brouard
                    272:   Summary: back to OS/X
                    273: 
1.179     brouard   274:   Revision 1.178  2015/01/04 09:35:48  brouard
                    275:   *** empty log message ***
                    276: 
1.178     brouard   277:   Revision 1.177  2015/01/03 18:40:56  brouard
                    278:   Summary: Still testing ilc32 on OSX
                    279: 
1.177     brouard   280:   Revision 1.176  2015/01/03 16:45:04  brouard
                    281:   *** empty log message ***
                    282: 
1.176     brouard   283:   Revision 1.175  2015/01/03 16:33:42  brouard
                    284:   *** empty log message ***
                    285: 
1.175     brouard   286:   Revision 1.174  2015/01/03 16:15:49  brouard
                    287:   Summary: Still in cross-compilation
                    288: 
1.174     brouard   289:   Revision 1.173  2015/01/03 12:06:26  brouard
                    290:   Summary: trying to detect cross-compilation
                    291: 
1.173     brouard   292:   Revision 1.172  2014/12/27 12:07:47  brouard
                    293:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    294: 
1.172     brouard   295:   Revision 1.171  2014/12/23 13:26:59  brouard
                    296:   Summary: Back from Visual C
                    297: 
                    298:   Still problem with utsname.h on Windows
                    299: 
1.171     brouard   300:   Revision 1.170  2014/12/23 11:17:12  brouard
                    301:   Summary: Cleaning some \%% back to %%
                    302: 
                    303:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    304: 
1.170     brouard   305:   Revision 1.169  2014/12/22 23:08:31  brouard
                    306:   Summary: 0.98p
                    307: 
                    308:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    309: 
1.169     brouard   310:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   311:   Summary: update
1.169     brouard   312: 
1.168     brouard   313:   Revision 1.167  2014/12/22 13:50:56  brouard
                    314:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    315: 
                    316:   Testing on Linux 64
                    317: 
1.167     brouard   318:   Revision 1.166  2014/12/22 11:40:47  brouard
                    319:   *** empty log message ***
                    320: 
1.166     brouard   321:   Revision 1.165  2014/12/16 11:20:36  brouard
                    322:   Summary: After compiling on Visual C
                    323: 
                    324:   * imach.c (Module): Merging 1.61 to 1.162
                    325: 
1.165     brouard   326:   Revision 1.164  2014/12/16 10:52:11  brouard
                    327:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    328: 
                    329:   * imach.c (Module): Merging 1.61 to 1.162
                    330: 
1.164     brouard   331:   Revision 1.163  2014/12/16 10:30:11  brouard
                    332:   * imach.c (Module): Merging 1.61 to 1.162
                    333: 
1.163     brouard   334:   Revision 1.162  2014/09/25 11:43:39  brouard
                    335:   Summary: temporary backup 0.99!
                    336: 
1.162     brouard   337:   Revision 1.1  2014/09/16 11:06:58  brouard
                    338:   Summary: With some code (wrong) for nlopt
                    339: 
                    340:   Author:
                    341: 
                    342:   Revision 1.161  2014/09/15 20:41:41  brouard
                    343:   Summary: Problem with macro SQR on Intel compiler
                    344: 
1.161     brouard   345:   Revision 1.160  2014/09/02 09:24:05  brouard
                    346:   *** empty log message ***
                    347: 
1.160     brouard   348:   Revision 1.159  2014/09/01 10:34:10  brouard
                    349:   Summary: WIN32
                    350:   Author: Brouard
                    351: 
1.159     brouard   352:   Revision 1.158  2014/08/27 17:11:51  brouard
                    353:   *** empty log message ***
                    354: 
1.158     brouard   355:   Revision 1.157  2014/08/27 16:26:55  brouard
                    356:   Summary: Preparing windows Visual studio version
                    357:   Author: Brouard
                    358: 
                    359:   In order to compile on Visual studio, time.h is now correct and time_t
                    360:   and tm struct should be used. difftime should be used but sometimes I
                    361:   just make the differences in raw time format (time(&now).
                    362:   Trying to suppress #ifdef LINUX
                    363:   Add xdg-open for __linux in order to open default browser.
                    364: 
1.157     brouard   365:   Revision 1.156  2014/08/25 20:10:10  brouard
                    366:   *** empty log message ***
                    367: 
1.156     brouard   368:   Revision 1.155  2014/08/25 18:32:34  brouard
                    369:   Summary: New compile, minor changes
                    370:   Author: Brouard
                    371: 
1.155     brouard   372:   Revision 1.154  2014/06/20 17:32:08  brouard
                    373:   Summary: Outputs now all graphs of convergence to period prevalence
                    374: 
1.154     brouard   375:   Revision 1.153  2014/06/20 16:45:46  brouard
                    376:   Summary: If 3 live state, convergence to period prevalence on same graph
                    377:   Author: Brouard
                    378: 
1.153     brouard   379:   Revision 1.152  2014/06/18 17:54:09  brouard
                    380:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    381: 
1.152     brouard   382:   Revision 1.151  2014/06/18 16:43:30  brouard
                    383:   *** empty log message ***
                    384: 
1.151     brouard   385:   Revision 1.150  2014/06/18 16:42:35  brouard
                    386:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    387:   Author: brouard
                    388: 
1.150     brouard   389:   Revision 1.149  2014/06/18 15:51:14  brouard
                    390:   Summary: Some fixes in parameter files errors
                    391:   Author: Nicolas Brouard
                    392: 
1.149     brouard   393:   Revision 1.148  2014/06/17 17:38:48  brouard
                    394:   Summary: Nothing new
                    395:   Author: Brouard
                    396: 
                    397:   Just a new packaging for OS/X version 0.98nS
                    398: 
1.148     brouard   399:   Revision 1.147  2014/06/16 10:33:11  brouard
                    400:   *** empty log message ***
                    401: 
1.147     brouard   402:   Revision 1.146  2014/06/16 10:20:28  brouard
                    403:   Summary: Merge
                    404:   Author: Brouard
                    405: 
                    406:   Merge, before building revised version.
                    407: 
1.146     brouard   408:   Revision 1.145  2014/06/10 21:23:15  brouard
                    409:   Summary: Debugging with valgrind
                    410:   Author: Nicolas Brouard
                    411: 
                    412:   Lot of changes in order to output the results with some covariates
                    413:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    414:   improve the code.
                    415:   No more memory valgrind error but a lot has to be done in order to
                    416:   continue the work of splitting the code into subroutines.
                    417:   Also, decodemodel has been improved. Tricode is still not
                    418:   optimal. nbcode should be improved. Documentation has been added in
                    419:   the source code.
                    420: 
1.144     brouard   421:   Revision 1.143  2014/01/26 09:45:38  brouard
                    422:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    423: 
                    424:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    425:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    426: 
1.143     brouard   427:   Revision 1.142  2014/01/26 03:57:36  brouard
                    428:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    429: 
                    430:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    431: 
1.142     brouard   432:   Revision 1.141  2014/01/26 02:42:01  brouard
                    433:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    434: 
1.141     brouard   435:   Revision 1.140  2011/09/02 10:37:54  brouard
                    436:   Summary: times.h is ok with mingw32 now.
                    437: 
1.140     brouard   438:   Revision 1.139  2010/06/14 07:50:17  brouard
                    439:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    440:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    441: 
1.139     brouard   442:   Revision 1.138  2010/04/30 18:19:40  brouard
                    443:   *** empty log message ***
                    444: 
1.138     brouard   445:   Revision 1.137  2010/04/29 18:11:38  brouard
                    446:   (Module): Checking covariates for more complex models
                    447:   than V1+V2. A lot of change to be done. Unstable.
                    448: 
1.137     brouard   449:   Revision 1.136  2010/04/26 20:30:53  brouard
                    450:   (Module): merging some libgsl code. Fixing computation
                    451:   of likelione (using inter/intrapolation if mle = 0) in order to
                    452:   get same likelihood as if mle=1.
                    453:   Some cleaning of code and comments added.
                    454: 
1.136     brouard   455:   Revision 1.135  2009/10/29 15:33:14  brouard
                    456:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    457: 
1.135     brouard   458:   Revision 1.134  2009/10/29 13:18:53  brouard
                    459:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    460: 
1.134     brouard   461:   Revision 1.133  2009/07/06 10:21:25  brouard
                    462:   just nforces
                    463: 
1.133     brouard   464:   Revision 1.132  2009/07/06 08:22:05  brouard
                    465:   Many tings
                    466: 
1.132     brouard   467:   Revision 1.131  2009/06/20 16:22:47  brouard
                    468:   Some dimensions resccaled
                    469: 
1.131     brouard   470:   Revision 1.130  2009/05/26 06:44:34  brouard
                    471:   (Module): Max Covariate is now set to 20 instead of 8. A
                    472:   lot of cleaning with variables initialized to 0. Trying to make
                    473:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    474: 
1.130     brouard   475:   Revision 1.129  2007/08/31 13:49:27  lievre
                    476:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    477: 
1.129     lievre    478:   Revision 1.128  2006/06/30 13:02:05  brouard
                    479:   (Module): Clarifications on computing e.j
                    480: 
1.128     brouard   481:   Revision 1.127  2006/04/28 18:11:50  brouard
                    482:   (Module): Yes the sum of survivors was wrong since
                    483:   imach-114 because nhstepm was no more computed in the age
                    484:   loop. Now we define nhstepma in the age loop.
                    485:   (Module): In order to speed up (in case of numerous covariates) we
                    486:   compute health expectancies (without variances) in a first step
                    487:   and then all the health expectancies with variances or standard
                    488:   deviation (needs data from the Hessian matrices) which slows the
                    489:   computation.
                    490:   In the future we should be able to stop the program is only health
                    491:   expectancies and graph are needed without standard deviations.
                    492: 
1.127     brouard   493:   Revision 1.126  2006/04/28 17:23:28  brouard
                    494:   (Module): Yes the sum of survivors was wrong since
                    495:   imach-114 because nhstepm was no more computed in the age
                    496:   loop. Now we define nhstepma in the age loop.
                    497:   Version 0.98h
                    498: 
1.126     brouard   499:   Revision 1.125  2006/04/04 15:20:31  lievre
                    500:   Errors in calculation of health expectancies. Age was not initialized.
                    501:   Forecasting file added.
                    502: 
                    503:   Revision 1.124  2006/03/22 17:13:53  lievre
                    504:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    505:   The log-likelihood is printed in the log file
                    506: 
                    507:   Revision 1.123  2006/03/20 10:52:43  brouard
                    508:   * imach.c (Module): <title> changed, corresponds to .htm file
                    509:   name. <head> headers where missing.
                    510: 
                    511:   * imach.c (Module): Weights can have a decimal point as for
                    512:   English (a comma might work with a correct LC_NUMERIC environment,
                    513:   otherwise the weight is truncated).
                    514:   Modification of warning when the covariates values are not 0 or
                    515:   1.
                    516:   Version 0.98g
                    517: 
                    518:   Revision 1.122  2006/03/20 09:45:41  brouard
                    519:   (Module): Weights can have a decimal point as for
                    520:   English (a comma might work with a correct LC_NUMERIC environment,
                    521:   otherwise the weight is truncated).
                    522:   Modification of warning when the covariates values are not 0 or
                    523:   1.
                    524:   Version 0.98g
                    525: 
                    526:   Revision 1.121  2006/03/16 17:45:01  lievre
                    527:   * imach.c (Module): Comments concerning covariates added
                    528: 
                    529:   * imach.c (Module): refinements in the computation of lli if
                    530:   status=-2 in order to have more reliable computation if stepm is
                    531:   not 1 month. Version 0.98f
                    532: 
                    533:   Revision 1.120  2006/03/16 15:10:38  lievre
                    534:   (Module): refinements in the computation of lli if
                    535:   status=-2 in order to have more reliable computation if stepm is
                    536:   not 1 month. Version 0.98f
                    537: 
                    538:   Revision 1.119  2006/03/15 17:42:26  brouard
                    539:   (Module): Bug if status = -2, the loglikelihood was
                    540:   computed as likelihood omitting the logarithm. Version O.98e
                    541: 
                    542:   Revision 1.118  2006/03/14 18:20:07  brouard
                    543:   (Module): varevsij Comments added explaining the second
                    544:   table of variances if popbased=1 .
                    545:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    546:   (Module): Function pstamp added
                    547:   (Module): Version 0.98d
                    548: 
                    549:   Revision 1.117  2006/03/14 17:16:22  brouard
                    550:   (Module): varevsij Comments added explaining the second
                    551:   table of variances if popbased=1 .
                    552:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    553:   (Module): Function pstamp added
                    554:   (Module): Version 0.98d
                    555: 
                    556:   Revision 1.116  2006/03/06 10:29:27  brouard
                    557:   (Module): Variance-covariance wrong links and
                    558:   varian-covariance of ej. is needed (Saito).
                    559: 
                    560:   Revision 1.115  2006/02/27 12:17:45  brouard
                    561:   (Module): One freematrix added in mlikeli! 0.98c
                    562: 
                    563:   Revision 1.114  2006/02/26 12:57:58  brouard
                    564:   (Module): Some improvements in processing parameter
                    565:   filename with strsep.
                    566: 
                    567:   Revision 1.113  2006/02/24 14:20:24  brouard
                    568:   (Module): Memory leaks checks with valgrind and:
                    569:   datafile was not closed, some imatrix were not freed and on matrix
                    570:   allocation too.
                    571: 
                    572:   Revision 1.112  2006/01/30 09:55:26  brouard
                    573:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    574: 
                    575:   Revision 1.111  2006/01/25 20:38:18  brouard
                    576:   (Module): Lots of cleaning and bugs added (Gompertz)
                    577:   (Module): Comments can be added in data file. Missing date values
                    578:   can be a simple dot '.'.
                    579: 
                    580:   Revision 1.110  2006/01/25 00:51:50  brouard
                    581:   (Module): Lots of cleaning and bugs added (Gompertz)
                    582: 
                    583:   Revision 1.109  2006/01/24 19:37:15  brouard
                    584:   (Module): Comments (lines starting with a #) are allowed in data.
                    585: 
                    586:   Revision 1.108  2006/01/19 18:05:42  lievre
                    587:   Gnuplot problem appeared...
                    588:   To be fixed
                    589: 
                    590:   Revision 1.107  2006/01/19 16:20:37  brouard
                    591:   Test existence of gnuplot in imach path
                    592: 
                    593:   Revision 1.106  2006/01/19 13:24:36  brouard
                    594:   Some cleaning and links added in html output
                    595: 
                    596:   Revision 1.105  2006/01/05 20:23:19  lievre
                    597:   *** empty log message ***
                    598: 
                    599:   Revision 1.104  2005/09/30 16:11:43  lievre
                    600:   (Module): sump fixed, loop imx fixed, and simplifications.
                    601:   (Module): If the status is missing at the last wave but we know
                    602:   that the person is alive, then we can code his/her status as -2
                    603:   (instead of missing=-1 in earlier versions) and his/her
                    604:   contributions to the likelihood is 1 - Prob of dying from last
                    605:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    606:   the healthy state at last known wave). Version is 0.98
                    607: 
                    608:   Revision 1.103  2005/09/30 15:54:49  lievre
                    609:   (Module): sump fixed, loop imx fixed, and simplifications.
                    610: 
                    611:   Revision 1.102  2004/09/15 17:31:30  brouard
                    612:   Add the possibility to read data file including tab characters.
                    613: 
                    614:   Revision 1.101  2004/09/15 10:38:38  brouard
                    615:   Fix on curr_time
                    616: 
                    617:   Revision 1.100  2004/07/12 18:29:06  brouard
                    618:   Add version for Mac OS X. Just define UNIX in Makefile
                    619: 
                    620:   Revision 1.99  2004/06/05 08:57:40  brouard
                    621:   *** empty log message ***
                    622: 
                    623:   Revision 1.98  2004/05/16 15:05:56  brouard
                    624:   New version 0.97 . First attempt to estimate force of mortality
                    625:   directly from the data i.e. without the need of knowing the health
                    626:   state at each age, but using a Gompertz model: log u =a + b*age .
                    627:   This is the basic analysis of mortality and should be done before any
                    628:   other analysis, in order to test if the mortality estimated from the
                    629:   cross-longitudinal survey is different from the mortality estimated
                    630:   from other sources like vital statistic data.
                    631: 
                    632:   The same imach parameter file can be used but the option for mle should be -3.
                    633: 
1.133     brouard   634:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   635:   former routines in order to include the new code within the former code.
                    636: 
                    637:   The output is very simple: only an estimate of the intercept and of
                    638:   the slope with 95% confident intervals.
                    639: 
                    640:   Current limitations:
                    641:   A) Even if you enter covariates, i.e. with the
                    642:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    643:   B) There is no computation of Life Expectancy nor Life Table.
                    644: 
                    645:   Revision 1.97  2004/02/20 13:25:42  lievre
                    646:   Version 0.96d. Population forecasting command line is (temporarily)
                    647:   suppressed.
                    648: 
                    649:   Revision 1.96  2003/07/15 15:38:55  brouard
                    650:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    651:   rewritten within the same printf. Workaround: many printfs.
                    652: 
                    653:   Revision 1.95  2003/07/08 07:54:34  brouard
                    654:   * imach.c (Repository):
                    655:   (Repository): Using imachwizard code to output a more meaningful covariance
                    656:   matrix (cov(a12,c31) instead of numbers.
                    657: 
                    658:   Revision 1.94  2003/06/27 13:00:02  brouard
                    659:   Just cleaning
                    660: 
                    661:   Revision 1.93  2003/06/25 16:33:55  brouard
                    662:   (Module): On windows (cygwin) function asctime_r doesn't
                    663:   exist so I changed back to asctime which exists.
                    664:   (Module): Version 0.96b
                    665: 
                    666:   Revision 1.92  2003/06/25 16:30:45  brouard
                    667:   (Module): On windows (cygwin) function asctime_r doesn't
                    668:   exist so I changed back to asctime which exists.
                    669: 
                    670:   Revision 1.91  2003/06/25 15:30:29  brouard
                    671:   * imach.c (Repository): Duplicated warning errors corrected.
                    672:   (Repository): Elapsed time after each iteration is now output. It
                    673:   helps to forecast when convergence will be reached. Elapsed time
                    674:   is stamped in powell.  We created a new html file for the graphs
                    675:   concerning matrix of covariance. It has extension -cov.htm.
                    676: 
                    677:   Revision 1.90  2003/06/24 12:34:15  brouard
                    678:   (Module): Some bugs corrected for windows. Also, when
                    679:   mle=-1 a template is output in file "or"mypar.txt with the design
                    680:   of the covariance matrix to be input.
                    681: 
                    682:   Revision 1.89  2003/06/24 12:30:52  brouard
                    683:   (Module): Some bugs corrected for windows. Also, when
                    684:   mle=-1 a template is output in file "or"mypar.txt with the design
                    685:   of the covariance matrix to be input.
                    686: 
                    687:   Revision 1.88  2003/06/23 17:54:56  brouard
                    688:   * 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.
                    689: 
                    690:   Revision 1.87  2003/06/18 12:26:01  brouard
                    691:   Version 0.96
                    692: 
                    693:   Revision 1.86  2003/06/17 20:04:08  brouard
                    694:   (Module): Change position of html and gnuplot routines and added
                    695:   routine fileappend.
                    696: 
                    697:   Revision 1.85  2003/06/17 13:12:43  brouard
                    698:   * imach.c (Repository): Check when date of death was earlier that
                    699:   current date of interview. It may happen when the death was just
                    700:   prior to the death. In this case, dh was negative and likelihood
                    701:   was wrong (infinity). We still send an "Error" but patch by
                    702:   assuming that the date of death was just one stepm after the
                    703:   interview.
                    704:   (Repository): Because some people have very long ID (first column)
                    705:   we changed int to long in num[] and we added a new lvector for
                    706:   memory allocation. But we also truncated to 8 characters (left
                    707:   truncation)
                    708:   (Repository): No more line truncation errors.
                    709: 
                    710:   Revision 1.84  2003/06/13 21:44:43  brouard
                    711:   * imach.c (Repository): Replace "freqsummary" at a correct
                    712:   place. It differs from routine "prevalence" which may be called
                    713:   many times. Probs is memory consuming and must be used with
                    714:   parcimony.
                    715:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    716: 
                    717:   Revision 1.83  2003/06/10 13:39:11  lievre
                    718:   *** empty log message ***
                    719: 
                    720:   Revision 1.82  2003/06/05 15:57:20  brouard
                    721:   Add log in  imach.c and  fullversion number is now printed.
                    722: 
                    723: */
                    724: /*
                    725:    Interpolated Markov Chain
                    726: 
                    727:   Short summary of the programme:
                    728:   
1.227     brouard   729:   This program computes Healthy Life Expectancies or State-specific
                    730:   (if states aren't health statuses) Expectancies from
                    731:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    732: 
                    733:   -1- a first survey ("cross") where individuals from different ages
                    734:   are interviewed on their health status or degree of disability (in
                    735:   the case of a health survey which is our main interest)
                    736: 
                    737:   -2- at least a second wave of interviews ("longitudinal") which
                    738:   measure each change (if any) in individual health status.  Health
                    739:   expectancies are computed from the time spent in each health state
                    740:   according to a model. More health states you consider, more time is
                    741:   necessary to reach the Maximum Likelihood of the parameters involved
                    742:   in the model.  The simplest model is the multinomial logistic model
                    743:   where pij is the probability to be observed in state j at the second
                    744:   wave conditional to be observed in state i at the first
                    745:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    746:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    747:   have a more complex model than "constant and age", you should modify
                    748:   the program where the markup *Covariates have to be included here
                    749:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   750:   convergence.
                    751: 
                    752:   The advantage of this computer programme, compared to a simple
                    753:   multinomial logistic model, is clear when the delay between waves is not
                    754:   identical for each individual. Also, if a individual missed an
                    755:   intermediate interview, the information is lost, but taken into
                    756:   account using an interpolation or extrapolation.  
                    757: 
                    758:   hPijx is the probability to be observed in state i at age x+h
                    759:   conditional to the observed state i at age x. The delay 'h' can be
                    760:   split into an exact number (nh*stepm) of unobserved intermediate
                    761:   states. This elementary transition (by month, quarter,
                    762:   semester or year) is modelled as a multinomial logistic.  The hPx
                    763:   matrix is simply the matrix product of nh*stepm elementary matrices
                    764:   and the contribution of each individual to the likelihood is simply
                    765:   hPijx.
                    766: 
                    767:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   768:   of the life expectancies. It also computes the period (stable) prevalence.
                    769: 
                    770: Back prevalence and projections:
1.227     brouard   771: 
                    772:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    773:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    774:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    775:    mobilavproj)
                    776: 
                    777:     Computes the back prevalence limit for any combination of
                    778:     covariate values k at any age between ageminpar and agemaxpar and
                    779:     returns it in **bprlim. In the loops,
                    780: 
                    781:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    782:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    783: 
                    784:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   785:    Computes for any combination of covariates k and any age between bage and fage 
                    786:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    787:                        oldm=oldms;savm=savms;
1.227     brouard   788: 
                    789:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   790:      Computes the transition matrix starting at age 'age' over
                    791:      'nhstepm*hstepm*stepm' months (i.e. until
                    792:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   793:      nhstepm*hstepm matrices. 
                    794: 
                    795:      Returns p3mat[i][j][h] after calling
                    796:      p3mat[i][j][h]=matprod2(newm,
                    797:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    798:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    799:      oldm);
1.226     brouard   800: 
                    801: Important routines
                    802: 
                    803: - func (or funcone), computes logit (pij) distinguishing
                    804:   o fixed variables (single or product dummies or quantitative);
                    805:   o varying variables by:
                    806:    (1) wave (single, product dummies, quantitative), 
                    807:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    808:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    809:        % varying dummy (not done) or quantitative (not done);
                    810: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    811:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    812: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    813:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    814:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   815: 
1.226     brouard   816: 
                    817:   
1.133     brouard   818:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    819:            Institut national d'études démographiques, Paris.
1.126     brouard   820:   This software have been partly granted by Euro-REVES, a concerted action
                    821:   from the European Union.
                    822:   It is copyrighted identically to a GNU software product, ie programme and
                    823:   software can be distributed freely for non commercial use. Latest version
                    824:   can be accessed at http://euroreves.ined.fr/imach .
                    825: 
                    826:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    827:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    828:   
                    829:   **********************************************************************/
                    830: /*
                    831:   main
                    832:   read parameterfile
                    833:   read datafile
                    834:   concatwav
                    835:   freqsummary
                    836:   if (mle >= 1)
                    837:     mlikeli
                    838:   print results files
                    839:   if mle==1 
                    840:      computes hessian
                    841:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    842:       begin-prev-date,...
                    843:   open gnuplot file
                    844:   open html file
1.145     brouard   845:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    846:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    847:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    848:     freexexit2 possible for memory heap.
                    849: 
                    850:   h Pij x                         | pij_nom  ficrestpij
                    851:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    852:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    853:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    854: 
                    855:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    856:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    857:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    858:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    859:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    860: 
1.126     brouard   861:   forecasting if prevfcast==1 prevforecast call prevalence()
                    862:   health expectancies
                    863:   Variance-covariance of DFLE
                    864:   prevalence()
                    865:    movingaverage()
                    866:   varevsij() 
                    867:   if popbased==1 varevsij(,popbased)
                    868:   total life expectancies
                    869:   Variance of period (stable) prevalence
                    870:  end
                    871: */
                    872: 
1.187     brouard   873: /* #define DEBUG */
                    874: /* #define DEBUGBRENT */
1.203     brouard   875: /* #define DEBUGLINMIN */
                    876: /* #define DEBUGHESS */
                    877: #define DEBUGHESSIJ
1.224     brouard   878: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   879: #define POWELL /* Instead of NLOPT */
1.224     brouard   880: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   881: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    882: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   883: 
                    884: #include <math.h>
                    885: #include <stdio.h>
                    886: #include <stdlib.h>
                    887: #include <string.h>
1.226     brouard   888: #include <ctype.h>
1.159     brouard   889: 
                    890: #ifdef _WIN32
                    891: #include <io.h>
1.172     brouard   892: #include <windows.h>
                    893: #include <tchar.h>
1.159     brouard   894: #else
1.126     brouard   895: #include <unistd.h>
1.159     brouard   896: #endif
1.126     brouard   897: 
                    898: #include <limits.h>
                    899: #include <sys/types.h>
1.171     brouard   900: 
                    901: #if defined(__GNUC__)
                    902: #include <sys/utsname.h> /* Doesn't work on Windows */
                    903: #endif
                    904: 
1.126     brouard   905: #include <sys/stat.h>
                    906: #include <errno.h>
1.159     brouard   907: /* extern int errno; */
1.126     brouard   908: 
1.157     brouard   909: /* #ifdef LINUX */
                    910: /* #include <time.h> */
                    911: /* #include "timeval.h" */
                    912: /* #else */
                    913: /* #include <sys/time.h> */
                    914: /* #endif */
                    915: 
1.126     brouard   916: #include <time.h>
                    917: 
1.136     brouard   918: #ifdef GSL
                    919: #include <gsl/gsl_errno.h>
                    920: #include <gsl/gsl_multimin.h>
                    921: #endif
                    922: 
1.167     brouard   923: 
1.162     brouard   924: #ifdef NLOPT
                    925: #include <nlopt.h>
                    926: typedef struct {
                    927:   double (* function)(double [] );
                    928: } myfunc_data ;
                    929: #endif
                    930: 
1.126     brouard   931: /* #include <libintl.h> */
                    932: /* #define _(String) gettext (String) */
                    933: 
1.251     brouard   934: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   935: 
                    936: #define GNUPLOTPROGRAM "gnuplot"
                    937: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    938: #define FILENAMELENGTH 132
                    939: 
                    940: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    941: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    942: 
1.144     brouard   943: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    944: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   945: 
                    946: #define NINTERVMAX 8
1.144     brouard   947: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    948: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    949: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   950: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   951: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    952: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   953: #define MAXN 20000
1.144     brouard   954: #define YEARM 12. /**< Number of months per year */
1.218     brouard   955: /* #define AGESUP 130 */
                    956: #define AGESUP 150
                    957: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   958: #define AGEBASE 40
1.194     brouard   959: #define AGEOVERFLOW 1.e20
1.164     brouard   960: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   961: #ifdef _WIN32
                    962: #define DIRSEPARATOR '\\'
                    963: #define CHARSEPARATOR "\\"
                    964: #define ODIRSEPARATOR '/'
                    965: #else
1.126     brouard   966: #define DIRSEPARATOR '/'
                    967: #define CHARSEPARATOR "/"
                    968: #define ODIRSEPARATOR '\\'
                    969: #endif
                    970: 
1.257   ! brouard   971: /* $Id: imach.c,v 1.256 2017/03/27 05:50:23 brouard Exp $ */
1.126     brouard   972: /* $State: Exp $ */
1.196     brouard   973: #include "version.h"
                    974: char version[]=__IMACH_VERSION__;
1.224     brouard   975: 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.257   ! brouard   976: char fullversion[]="$Revision: 1.256 $ $Date: 2017/03/27 05:50:23 $"; 
1.126     brouard   977: char strstart[80];
                    978: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   979: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   980: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   981: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    982: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    983: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   984: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    985: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   986: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    987: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    988: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   989: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    990: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   991: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   992: int nsd=0; /**< Total number of single dummy variables (output) */
                    993: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   994: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   995: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   996: int ntveff=0; /**< ntveff number of effective time varying variables */
                    997: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   998: int cptcov=0; /* Working variable */
1.218     brouard   999: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard  1000: int npar=NPARMAX;
                   1001: int nlstate=2; /* Number of live states */
                   1002: int ndeath=1; /* Number of dead states */
1.130     brouard  1003: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1004: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1005: int popbased=0;
                   1006: 
                   1007: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1008: int maxwav=0; /* Maxim number of waves */
                   1009: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1010: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1011: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1012:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1013: int mle=1, weightopt=0;
1.126     brouard  1014: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1015: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1016: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1017:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1018: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1019: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1020: 
1.130     brouard  1021: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1022: double **matprod2(); /* test */
1.126     brouard  1023: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1024: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1025: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1026: 
1.136     brouard  1027: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1028: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1029: FILE *ficlog, *ficrespow;
1.130     brouard  1030: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1031: double fretone; /* Only one call to likelihood */
1.130     brouard  1032: long ipmx=0; /* Number of contributions */
1.126     brouard  1033: double sw; /* Sum of weights */
                   1034: char filerespow[FILENAMELENGTH];
                   1035: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1036: FILE *ficresilk;
                   1037: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1038: FILE *ficresprobmorprev;
                   1039: FILE *fichtm, *fichtmcov; /* Html File */
                   1040: FILE *ficreseij;
                   1041: char filerese[FILENAMELENGTH];
                   1042: FILE *ficresstdeij;
                   1043: char fileresstde[FILENAMELENGTH];
                   1044: FILE *ficrescveij;
                   1045: char filerescve[FILENAMELENGTH];
                   1046: FILE  *ficresvij;
                   1047: char fileresv[FILENAMELENGTH];
                   1048: FILE  *ficresvpl;
                   1049: char fileresvpl[FILENAMELENGTH];
                   1050: char title[MAXLINE];
1.234     brouard  1051: char model[MAXLINE]; /**< The model line */
1.217     brouard  1052: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1053: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1054: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1055: char command[FILENAMELENGTH];
                   1056: int  outcmd=0;
                   1057: 
1.217     brouard  1058: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1059: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1060: char filelog[FILENAMELENGTH]; /* Log file */
                   1061: char filerest[FILENAMELENGTH];
                   1062: char fileregp[FILENAMELENGTH];
                   1063: char popfile[FILENAMELENGTH];
                   1064: 
                   1065: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1066: 
1.157     brouard  1067: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1068: /* struct timezone tzp; */
                   1069: /* extern int gettimeofday(); */
                   1070: struct tm tml, *gmtime(), *localtime();
                   1071: 
                   1072: extern time_t time();
                   1073: 
                   1074: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1075: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1076: struct tm tm;
                   1077: 
1.126     brouard  1078: char strcurr[80], strfor[80];
                   1079: 
                   1080: char *endptr;
                   1081: long lval;
                   1082: double dval;
                   1083: 
                   1084: #define NR_END 1
                   1085: #define FREE_ARG char*
                   1086: #define FTOL 1.0e-10
                   1087: 
                   1088: #define NRANSI 
1.240     brouard  1089: #define ITMAX 200
                   1090: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1091: 
                   1092: #define TOL 2.0e-4 
                   1093: 
                   1094: #define CGOLD 0.3819660 
                   1095: #define ZEPS 1.0e-10 
                   1096: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1097: 
                   1098: #define GOLD 1.618034 
                   1099: #define GLIMIT 100.0 
                   1100: #define TINY 1.0e-20 
                   1101: 
                   1102: static double maxarg1,maxarg2;
                   1103: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1104: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1105:   
                   1106: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1107: #define rint(a) floor(a+0.5)
1.166     brouard  1108: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1109: #define mytinydouble 1.0e-16
1.166     brouard  1110: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1111: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1112: /* static double dsqrarg; */
                   1113: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1114: static double sqrarg;
                   1115: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1116: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1117: int agegomp= AGEGOMP;
                   1118: 
                   1119: int imx; 
                   1120: int stepm=1;
                   1121: /* Stepm, step in month: minimum step interpolation*/
                   1122: 
                   1123: int estepm;
                   1124: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1125: 
                   1126: int m,nb;
                   1127: long *num;
1.197     brouard  1128: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1129: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1130:                   covariate for which somebody answered excluding 
                   1131:                   undefined. Usually 2: 0 and 1. */
                   1132: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1133:                             covariate for which somebody answered including 
                   1134:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1135: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1136: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1137: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1138: double *ageexmed,*agecens;
                   1139: double dateintmean=0;
                   1140: 
                   1141: double *weight;
                   1142: int **s; /* Status */
1.141     brouard  1143: double *agedc;
1.145     brouard  1144: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1145:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1146:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1147: double **coqvar; /* Fixed quantitative covariate iqv */
                   1148: double ***cotvar; /* Time varying covariate itv */
                   1149: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1150: double  idx; 
                   1151: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1152: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1153: /*k          1  2   3   4     5    6    7     8    9 */
                   1154: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1155: /* Tndvar[k]    1   2   3               4          5 */
                   1156: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1157: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1158: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1159: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1160: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1161: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1162: /* Tprod[i]=k           4               7            */
                   1163: /* Tage[i]=k                  5               8      */
                   1164: /* */
                   1165: /* Type                    */
                   1166: /* V         1  2  3  4  5 */
                   1167: /*           F  F  V  V  V */
                   1168: /*           D  Q  D  D  Q */
                   1169: /*                         */
                   1170: int *TvarsD;
                   1171: int *TvarsDind;
                   1172: int *TvarsQ;
                   1173: int *TvarsQind;
                   1174: 
1.235     brouard  1175: #define MAXRESULTLINES 10
                   1176: int nresult=0;
                   1177: int TKresult[MAXRESULTLINES];
1.237     brouard  1178: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1179: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1180: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1181: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1182: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1183: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1184: 
1.234     brouard  1185: /* 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  1186: 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 */
                   1187: 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 */
                   1188: 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 */
                   1189: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1190: 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 */
                   1191: 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  1192: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1193: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1194: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1195: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1196: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1197: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1198: 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 */
                   1199: 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 */
                   1200: 
1.230     brouard  1201: int *Tvarsel; /**< Selected covariates for output */
                   1202: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1203: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1204: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1205: 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  1206: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1207: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1208: int *Tage;
1.227     brouard  1209: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1210: 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  1211: 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*/ 
                   1212: 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  1213: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1214: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1215: int **Tvard;
                   1216: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1217: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1218: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1219:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1220:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1221: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1222: double *lsurv, *lpop, *tpop;
                   1223: 
1.231     brouard  1224: #define FD 1; /* Fixed dummy covariate */
                   1225: #define FQ 2; /* Fixed quantitative covariate */
                   1226: #define FP 3; /* Fixed product covariate */
                   1227: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1228: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1229: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1230: #define VD 10; /* Varying dummy covariate */
                   1231: #define VQ 11; /* Varying quantitative covariate */
                   1232: #define VP 12; /* Varying product covariate */
                   1233: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1234: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1235: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1236: #define APFD 16; /* Age product * fixed dummy covariate */
                   1237: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1238: #define APVD 18; /* Age product * varying dummy covariate */
                   1239: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1240: 
                   1241: #define FTYPE 1; /* Fixed covariate */
                   1242: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1243: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1244: 
                   1245: struct kmodel{
                   1246:        int maintype; /* main type */
                   1247:        int subtype; /* subtype */
                   1248: };
                   1249: struct kmodel modell[NCOVMAX];
                   1250: 
1.143     brouard  1251: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1252: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1253: 
                   1254: /**************** split *************************/
                   1255: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1256: {
                   1257:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1258:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1259:   */ 
                   1260:   char *ss;                            /* pointer */
1.186     brouard  1261:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1262: 
                   1263:   l1 = strlen(path );                  /* length of path */
                   1264:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1265:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1266:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1267:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1268:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1269:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1270:     /* get current working directory */
                   1271:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1272: #ifdef WIN32
                   1273:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1274: #else
                   1275:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1276: #endif
1.126     brouard  1277:       return( GLOCK_ERROR_GETCWD );
                   1278:     }
                   1279:     /* got dirc from getcwd*/
                   1280:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1281:   } else {                             /* strip directory from path */
1.126     brouard  1282:     ss++;                              /* after this, the filename */
                   1283:     l2 = strlen( ss );                 /* length of filename */
                   1284:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1285:     strcpy( name, ss );                /* save file name */
                   1286:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1287:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1288:     printf(" DIRC2 = %s \n",dirc);
                   1289:   }
                   1290:   /* We add a separator at the end of dirc if not exists */
                   1291:   l1 = strlen( dirc );                 /* length of directory */
                   1292:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1293:     dirc[l1] =  DIRSEPARATOR;
                   1294:     dirc[l1+1] = 0; 
                   1295:     printf(" DIRC3 = %s \n",dirc);
                   1296:   }
                   1297:   ss = strrchr( name, '.' );           /* find last / */
                   1298:   if (ss >0){
                   1299:     ss++;
                   1300:     strcpy(ext,ss);                    /* save extension */
                   1301:     l1= strlen( name);
                   1302:     l2= strlen(ss)+1;
                   1303:     strncpy( finame, name, l1-l2);
                   1304:     finame[l1-l2]= 0;
                   1305:   }
                   1306: 
                   1307:   return( 0 );                         /* we're done */
                   1308: }
                   1309: 
                   1310: 
                   1311: /******************************************/
                   1312: 
                   1313: void replace_back_to_slash(char *s, char*t)
                   1314: {
                   1315:   int i;
                   1316:   int lg=0;
                   1317:   i=0;
                   1318:   lg=strlen(t);
                   1319:   for(i=0; i<= lg; i++) {
                   1320:     (s[i] = t[i]);
                   1321:     if (t[i]== '\\') s[i]='/';
                   1322:   }
                   1323: }
                   1324: 
1.132     brouard  1325: char *trimbb(char *out, char *in)
1.137     brouard  1326: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1327:   char *s;
                   1328:   s=out;
                   1329:   while (*in != '\0'){
1.137     brouard  1330:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1331:       in++;
                   1332:     }
                   1333:     *out++ = *in++;
                   1334:   }
                   1335:   *out='\0';
                   1336:   return s;
                   1337: }
                   1338: 
1.187     brouard  1339: /* char *substrchaine(char *out, char *in, char *chain) */
                   1340: /* { */
                   1341: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1342: /*   char *s, *t; */
                   1343: /*   t=in;s=out; */
                   1344: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1345: /*     *out++ = *in++; */
                   1346: /*   } */
                   1347: 
                   1348: /*   /\* *in matches *chain *\/ */
                   1349: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1350: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1351: /*   } */
                   1352: /*   in--; chain--; */
                   1353: /*   while ( (*in != '\0')){ */
                   1354: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1355: /*     *out++ = *in++; */
                   1356: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1357: /*   } */
                   1358: /*   *out='\0'; */
                   1359: /*   out=s; */
                   1360: /*   return out; */
                   1361: /* } */
                   1362: char *substrchaine(char *out, char *in, char *chain)
                   1363: {
                   1364:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1365:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1366: 
                   1367:   char *strloc;
                   1368: 
                   1369:   strcpy (out, in); 
                   1370:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1371:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1372:   if(strloc != NULL){ 
                   1373:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1374:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1375:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1376:   }
                   1377:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1378:   return out;
                   1379: }
                   1380: 
                   1381: 
1.145     brouard  1382: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1383: {
1.187     brouard  1384:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1385:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1386:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1387:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1388:   */
1.160     brouard  1389:   char *s, *t;
1.145     brouard  1390:   t=in;s=in;
                   1391:   while ((*in != occ) && (*in != '\0')){
                   1392:     *alocc++ = *in++;
                   1393:   }
                   1394:   if( *in == occ){
                   1395:     *(alocc)='\0';
                   1396:     s=++in;
                   1397:   }
                   1398:  
                   1399:   if (s == t) {/* occ not found */
                   1400:     *(alocc-(in-s))='\0';
                   1401:     in=s;
                   1402:   }
                   1403:   while ( *in != '\0'){
                   1404:     *blocc++ = *in++;
                   1405:   }
                   1406: 
                   1407:   *blocc='\0';
                   1408:   return t;
                   1409: }
1.137     brouard  1410: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1411: {
1.187     brouard  1412:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1413:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1414:      gives blocc="abcdef2ghi" and alocc="j".
                   1415:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1416:   */
                   1417:   char *s, *t;
                   1418:   t=in;s=in;
                   1419:   while (*in != '\0'){
                   1420:     while( *in == occ){
                   1421:       *blocc++ = *in++;
                   1422:       s=in;
                   1423:     }
                   1424:     *blocc++ = *in++;
                   1425:   }
                   1426:   if (s == t) /* occ not found */
                   1427:     *(blocc-(in-s))='\0';
                   1428:   else
                   1429:     *(blocc-(in-s)-1)='\0';
                   1430:   in=s;
                   1431:   while ( *in != '\0'){
                   1432:     *alocc++ = *in++;
                   1433:   }
                   1434: 
                   1435:   *alocc='\0';
                   1436:   return s;
                   1437: }
                   1438: 
1.126     brouard  1439: int nbocc(char *s, char occ)
                   1440: {
                   1441:   int i,j=0;
                   1442:   int lg=20;
                   1443:   i=0;
                   1444:   lg=strlen(s);
                   1445:   for(i=0; i<= lg; i++) {
1.234     brouard  1446:     if  (s[i] == occ ) j++;
1.126     brouard  1447:   }
                   1448:   return j;
                   1449: }
                   1450: 
1.137     brouard  1451: /* void cutv(char *u,char *v, char*t, char occ) */
                   1452: /* { */
                   1453: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1454: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1455: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1456: /*   int i,lg,j,p=0; */
                   1457: /*   i=0; */
                   1458: /*   lg=strlen(t); */
                   1459: /*   for(j=0; j<=lg-1; j++) { */
                   1460: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1461: /*   } */
1.126     brouard  1462: 
1.137     brouard  1463: /*   for(j=0; j<p; j++) { */
                   1464: /*     (u[j] = t[j]); */
                   1465: /*   } */
                   1466: /*      u[p]='\0'; */
1.126     brouard  1467: 
1.137     brouard  1468: /*    for(j=0; j<= lg; j++) { */
                   1469: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1470: /*   } */
                   1471: /* } */
1.126     brouard  1472: 
1.160     brouard  1473: #ifdef _WIN32
                   1474: char * strsep(char **pp, const char *delim)
                   1475: {
                   1476:   char *p, *q;
                   1477:          
                   1478:   if ((p = *pp) == NULL)
                   1479:     return 0;
                   1480:   if ((q = strpbrk (p, delim)) != NULL)
                   1481:   {
                   1482:     *pp = q + 1;
                   1483:     *q = '\0';
                   1484:   }
                   1485:   else
                   1486:     *pp = 0;
                   1487:   return p;
                   1488: }
                   1489: #endif
                   1490: 
1.126     brouard  1491: /********************** nrerror ********************/
                   1492: 
                   1493: void nrerror(char error_text[])
                   1494: {
                   1495:   fprintf(stderr,"ERREUR ...\n");
                   1496:   fprintf(stderr,"%s\n",error_text);
                   1497:   exit(EXIT_FAILURE);
                   1498: }
                   1499: /*********************** vector *******************/
                   1500: double *vector(int nl, int nh)
                   1501: {
                   1502:   double *v;
                   1503:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1504:   if (!v) nrerror("allocation failure in vector");
                   1505:   return v-nl+NR_END;
                   1506: }
                   1507: 
                   1508: /************************ free vector ******************/
                   1509: void free_vector(double*v, int nl, int nh)
                   1510: {
                   1511:   free((FREE_ARG)(v+nl-NR_END));
                   1512: }
                   1513: 
                   1514: /************************ivector *******************************/
                   1515: int *ivector(long nl,long nh)
                   1516: {
                   1517:   int *v;
                   1518:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1519:   if (!v) nrerror("allocation failure in ivector");
                   1520:   return v-nl+NR_END;
                   1521: }
                   1522: 
                   1523: /******************free ivector **************************/
                   1524: void free_ivector(int *v, long nl, long nh)
                   1525: {
                   1526:   free((FREE_ARG)(v+nl-NR_END));
                   1527: }
                   1528: 
                   1529: /************************lvector *******************************/
                   1530: long *lvector(long nl,long nh)
                   1531: {
                   1532:   long *v;
                   1533:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1534:   if (!v) nrerror("allocation failure in ivector");
                   1535:   return v-nl+NR_END;
                   1536: }
                   1537: 
                   1538: /******************free lvector **************************/
                   1539: void free_lvector(long *v, long nl, long nh)
                   1540: {
                   1541:   free((FREE_ARG)(v+nl-NR_END));
                   1542: }
                   1543: 
                   1544: /******************* imatrix *******************************/
                   1545: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1546:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1547: { 
                   1548:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1549:   int **m; 
                   1550:   
                   1551:   /* allocate pointers to rows */ 
                   1552:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1553:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1554:   m += NR_END; 
                   1555:   m -= nrl; 
                   1556:   
                   1557:   
                   1558:   /* allocate rows and set pointers to them */ 
                   1559:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1560:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1561:   m[nrl] += NR_END; 
                   1562:   m[nrl] -= ncl; 
                   1563:   
                   1564:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1565:   
                   1566:   /* return pointer to array of pointers to rows */ 
                   1567:   return m; 
                   1568: } 
                   1569: 
                   1570: /****************** free_imatrix *************************/
                   1571: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1572:       int **m;
                   1573:       long nch,ncl,nrh,nrl; 
                   1574:      /* free an int matrix allocated by imatrix() */ 
                   1575: { 
                   1576:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1577:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1578: } 
                   1579: 
                   1580: /******************* matrix *******************************/
                   1581: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1582: {
                   1583:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1584:   double **m;
                   1585: 
                   1586:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1587:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1588:   m += NR_END;
                   1589:   m -= nrl;
                   1590: 
                   1591:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1592:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1593:   m[nrl] += NR_END;
                   1594:   m[nrl] -= ncl;
                   1595: 
                   1596:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1597:   return m;
1.145     brouard  1598:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1599: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1600: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1601:    */
                   1602: }
                   1603: 
                   1604: /*************************free matrix ************************/
                   1605: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1606: {
                   1607:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1608:   free((FREE_ARG)(m+nrl-NR_END));
                   1609: }
                   1610: 
                   1611: /******************* ma3x *******************************/
                   1612: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1613: {
                   1614:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1615:   double ***m;
                   1616: 
                   1617:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1618:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1619:   m += NR_END;
                   1620:   m -= nrl;
                   1621: 
                   1622:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1623:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1624:   m[nrl] += NR_END;
                   1625:   m[nrl] -= ncl;
                   1626: 
                   1627:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1628: 
                   1629:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1630:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1631:   m[nrl][ncl] += NR_END;
                   1632:   m[nrl][ncl] -= nll;
                   1633:   for (j=ncl+1; j<=nch; j++) 
                   1634:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1635:   
                   1636:   for (i=nrl+1; i<=nrh; i++) {
                   1637:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1638:     for (j=ncl+1; j<=nch; j++) 
                   1639:       m[i][j]=m[i][j-1]+nlay;
                   1640:   }
                   1641:   return m; 
                   1642:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1643:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1644:   */
                   1645: }
                   1646: 
                   1647: /*************************free ma3x ************************/
                   1648: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1649: {
                   1650:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1651:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1652:   free((FREE_ARG)(m+nrl-NR_END));
                   1653: }
                   1654: 
                   1655: /*************** function subdirf ***********/
                   1656: char *subdirf(char fileres[])
                   1657: {
                   1658:   /* Caution optionfilefiname is hidden */
                   1659:   strcpy(tmpout,optionfilefiname);
                   1660:   strcat(tmpout,"/"); /* Add to the right */
                   1661:   strcat(tmpout,fileres);
                   1662:   return tmpout;
                   1663: }
                   1664: 
                   1665: /*************** function subdirf2 ***********/
                   1666: char *subdirf2(char fileres[], char *preop)
                   1667: {
                   1668:   
                   1669:   /* Caution optionfilefiname is hidden */
                   1670:   strcpy(tmpout,optionfilefiname);
                   1671:   strcat(tmpout,"/");
                   1672:   strcat(tmpout,preop);
                   1673:   strcat(tmpout,fileres);
                   1674:   return tmpout;
                   1675: }
                   1676: 
                   1677: /*************** function subdirf3 ***********/
                   1678: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1679: {
                   1680:   
                   1681:   /* Caution optionfilefiname is hidden */
                   1682:   strcpy(tmpout,optionfilefiname);
                   1683:   strcat(tmpout,"/");
                   1684:   strcat(tmpout,preop);
                   1685:   strcat(tmpout,preop2);
                   1686:   strcat(tmpout,fileres);
                   1687:   return tmpout;
                   1688: }
1.213     brouard  1689:  
                   1690: /*************** function subdirfext ***********/
                   1691: char *subdirfext(char fileres[], char *preop, char *postop)
                   1692: {
                   1693:   
                   1694:   strcpy(tmpout,preop);
                   1695:   strcat(tmpout,fileres);
                   1696:   strcat(tmpout,postop);
                   1697:   return tmpout;
                   1698: }
1.126     brouard  1699: 
1.213     brouard  1700: /*************** function subdirfext3 ***********/
                   1701: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1702: {
                   1703:   
                   1704:   /* Caution optionfilefiname is hidden */
                   1705:   strcpy(tmpout,optionfilefiname);
                   1706:   strcat(tmpout,"/");
                   1707:   strcat(tmpout,preop);
                   1708:   strcat(tmpout,fileres);
                   1709:   strcat(tmpout,postop);
                   1710:   return tmpout;
                   1711: }
                   1712:  
1.162     brouard  1713: char *asc_diff_time(long time_sec, char ascdiff[])
                   1714: {
                   1715:   long sec_left, days, hours, minutes;
                   1716:   days = (time_sec) / (60*60*24);
                   1717:   sec_left = (time_sec) % (60*60*24);
                   1718:   hours = (sec_left) / (60*60) ;
                   1719:   sec_left = (sec_left) %(60*60);
                   1720:   minutes = (sec_left) /60;
                   1721:   sec_left = (sec_left) % (60);
                   1722:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1723:   return ascdiff;
                   1724: }
                   1725: 
1.126     brouard  1726: /***************** f1dim *************************/
                   1727: extern int ncom; 
                   1728: extern double *pcom,*xicom;
                   1729: extern double (*nrfunc)(double []); 
                   1730:  
                   1731: double f1dim(double x) 
                   1732: { 
                   1733:   int j; 
                   1734:   double f;
                   1735:   double *xt; 
                   1736:  
                   1737:   xt=vector(1,ncom); 
                   1738:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1739:   f=(*nrfunc)(xt); 
                   1740:   free_vector(xt,1,ncom); 
                   1741:   return f; 
                   1742: } 
                   1743: 
                   1744: /*****************brent *************************/
                   1745: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1746: {
                   1747:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1748:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1749:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1750:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1751:    * returned function value. 
                   1752:   */
1.126     brouard  1753:   int iter; 
                   1754:   double a,b,d,etemp;
1.159     brouard  1755:   double fu=0,fv,fw,fx;
1.164     brouard  1756:   double ftemp=0.;
1.126     brouard  1757:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1758:   double e=0.0; 
                   1759:  
                   1760:   a=(ax < cx ? ax : cx); 
                   1761:   b=(ax > cx ? ax : cx); 
                   1762:   x=w=v=bx; 
                   1763:   fw=fv=fx=(*f)(x); 
                   1764:   for (iter=1;iter<=ITMAX;iter++) { 
                   1765:     xm=0.5*(a+b); 
                   1766:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1767:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1768:     printf(".");fflush(stdout);
                   1769:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1770: #ifdef DEBUGBRENT
1.126     brouard  1771:     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);
                   1772:     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);
                   1773:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1774: #endif
                   1775:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1776:       *xmin=x; 
                   1777:       return fx; 
                   1778:     } 
                   1779:     ftemp=fu;
                   1780:     if (fabs(e) > tol1) { 
                   1781:       r=(x-w)*(fx-fv); 
                   1782:       q=(x-v)*(fx-fw); 
                   1783:       p=(x-v)*q-(x-w)*r; 
                   1784:       q=2.0*(q-r); 
                   1785:       if (q > 0.0) p = -p; 
                   1786:       q=fabs(q); 
                   1787:       etemp=e; 
                   1788:       e=d; 
                   1789:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1790:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1791:       else { 
1.224     brouard  1792:                                d=p/q; 
                   1793:                                u=x+d; 
                   1794:                                if (u-a < tol2 || b-u < tol2) 
                   1795:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1796:       } 
                   1797:     } else { 
                   1798:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1799:     } 
                   1800:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1801:     fu=(*f)(u); 
                   1802:     if (fu <= fx) { 
                   1803:       if (u >= x) a=x; else b=x; 
                   1804:       SHFT(v,w,x,u) 
1.183     brouard  1805:       SHFT(fv,fw,fx,fu) 
                   1806:     } else { 
                   1807:       if (u < x) a=u; else b=u; 
                   1808:       if (fu <= fw || w == x) { 
1.224     brouard  1809:                                v=w; 
                   1810:                                w=u; 
                   1811:                                fv=fw; 
                   1812:                                fw=fu; 
1.183     brouard  1813:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1814:                                v=u; 
                   1815:                                fv=fu; 
1.183     brouard  1816:       } 
                   1817:     } 
1.126     brouard  1818:   } 
                   1819:   nrerror("Too many iterations in brent"); 
                   1820:   *xmin=x; 
                   1821:   return fx; 
                   1822: } 
                   1823: 
                   1824: /****************** mnbrak ***********************/
                   1825: 
                   1826: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1827:            double (*func)(double)) 
1.183     brouard  1828: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1829: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1830: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1831: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1832:    */
1.126     brouard  1833:   double ulim,u,r,q, dum;
                   1834:   double fu; 
1.187     brouard  1835: 
                   1836:   double scale=10.;
                   1837:   int iterscale=0;
                   1838: 
                   1839:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1840:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1841: 
                   1842: 
                   1843:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1844:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1845:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1846:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1847:   /* } */
                   1848: 
1.126     brouard  1849:   if (*fb > *fa) { 
                   1850:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1851:     SHFT(dum,*fb,*fa,dum) 
                   1852:   } 
1.126     brouard  1853:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1854:   *fc=(*func)(*cx); 
1.183     brouard  1855: #ifdef DEBUG
1.224     brouard  1856:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1857:   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  1858: #endif
1.224     brouard  1859:   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  1860:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1861:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1862:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1863:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1864:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1865:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1866:       fu=(*func)(u); 
1.163     brouard  1867: #ifdef DEBUG
                   1868:       /* f(x)=A(x-u)**2+f(u) */
                   1869:       double A, fparabu; 
                   1870:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1871:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1872:       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);
                   1873:       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  1874:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1875:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1876:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1877:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1878: #endif 
1.184     brouard  1879: #ifdef MNBRAKORIGINAL
1.183     brouard  1880: #else
1.191     brouard  1881: /*       if (fu > *fc) { */
                   1882: /* #ifdef DEBUG */
                   1883: /*       printf("mnbrak4  fu > fc \n"); */
                   1884: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1885: /* #endif */
                   1886: /*     /\* 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 *\\/  *\/ */
                   1887: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1888: /*     dum=u; /\* Shifting c and u *\/ */
                   1889: /*     u = *cx; */
                   1890: /*     *cx = dum; */
                   1891: /*     dum = fu; */
                   1892: /*     fu = *fc; */
                   1893: /*     *fc =dum; */
                   1894: /*       } else { /\* end *\/ */
                   1895: /* #ifdef DEBUG */
                   1896: /*       printf("mnbrak3  fu < fc \n"); */
                   1897: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1898: /* #endif */
                   1899: /*     dum=u; /\* Shifting c and u *\/ */
                   1900: /*     u = *cx; */
                   1901: /*     *cx = dum; */
                   1902: /*     dum = fu; */
                   1903: /*     fu = *fc; */
                   1904: /*     *fc =dum; */
                   1905: /*       } */
1.224     brouard  1906: #ifdef DEBUGMNBRAK
                   1907:                 double A, fparabu; 
                   1908:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1909:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1910:      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);
                   1911:      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  1912: #endif
1.191     brouard  1913:       dum=u; /* Shifting c and u */
                   1914:       u = *cx;
                   1915:       *cx = dum;
                   1916:       dum = fu;
                   1917:       fu = *fc;
                   1918:       *fc =dum;
1.183     brouard  1919: #endif
1.162     brouard  1920:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1921: #ifdef DEBUG
1.224     brouard  1922:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1923:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1924: #endif
1.126     brouard  1925:       fu=(*func)(u); 
                   1926:       if (fu < *fc) { 
1.183     brouard  1927: #ifdef DEBUG
1.224     brouard  1928:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1929:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1930: #endif
                   1931:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1932:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1933: #ifdef DEBUG
                   1934:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1935: #endif
                   1936:       } 
1.162     brouard  1937:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1938: #ifdef DEBUG
1.224     brouard  1939:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1940:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1941: #endif
1.126     brouard  1942:       u=ulim; 
                   1943:       fu=(*func)(u); 
1.183     brouard  1944:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1945: #ifdef DEBUG
1.224     brouard  1946:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1947:       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  1948: #endif
1.126     brouard  1949:       u=(*cx)+GOLD*(*cx-*bx); 
                   1950:       fu=(*func)(u); 
1.224     brouard  1951: #ifdef DEBUG
                   1952:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1953:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1954: #endif
1.183     brouard  1955:     } /* end tests */
1.126     brouard  1956:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1957:     SHFT(*fa,*fb,*fc,fu) 
                   1958: #ifdef DEBUG
1.224     brouard  1959:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1960:       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  1961: #endif
                   1962:   } /* 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  1963: } 
                   1964: 
                   1965: /*************** linmin ************************/
1.162     brouard  1966: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1967: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1968: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1969: the value of func at the returned location p . This is actually all accomplished by calling the
                   1970: routines mnbrak and brent .*/
1.126     brouard  1971: int ncom; 
                   1972: double *pcom,*xicom;
                   1973: double (*nrfunc)(double []); 
                   1974:  
1.224     brouard  1975: #ifdef LINMINORIGINAL
1.126     brouard  1976: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1977: #else
                   1978: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1979: #endif
1.126     brouard  1980: { 
                   1981:   double brent(double ax, double bx, double cx, 
                   1982:               double (*f)(double), double tol, double *xmin); 
                   1983:   double f1dim(double x); 
                   1984:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1985:              double *fc, double (*func)(double)); 
                   1986:   int j; 
                   1987:   double xx,xmin,bx,ax; 
                   1988:   double fx,fb,fa;
1.187     brouard  1989: 
1.203     brouard  1990: #ifdef LINMINORIGINAL
                   1991: #else
                   1992:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1993: #endif
                   1994:   
1.126     brouard  1995:   ncom=n; 
                   1996:   pcom=vector(1,n); 
                   1997:   xicom=vector(1,n); 
                   1998:   nrfunc=func; 
                   1999:   for (j=1;j<=n;j++) { 
                   2000:     pcom[j]=p[j]; 
1.202     brouard  2001:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2002:   } 
1.187     brouard  2003: 
1.203     brouard  2004: #ifdef LINMINORIGINAL
                   2005:   xx=1.;
                   2006: #else
                   2007:   axs=0.0;
                   2008:   xxs=1.;
                   2009:   do{
                   2010:     xx= xxs;
                   2011: #endif
1.187     brouard  2012:     ax=0.;
                   2013:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2014:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2015:     /* 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))   */
                   2016:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2017:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2018:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2019:     /* 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  2020: #ifdef LINMINORIGINAL
                   2021: #else
                   2022:     if (fx != fx){
1.224     brouard  2023:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2024:                        printf("|");
                   2025:                        fprintf(ficlog,"|");
1.203     brouard  2026: #ifdef DEBUGLINMIN
1.224     brouard  2027:                        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  2028: #endif
                   2029:     }
1.224     brouard  2030:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2031: #endif
                   2032:   
1.191     brouard  2033: #ifdef DEBUGLINMIN
                   2034:   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  2035:   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  2036: #endif
1.224     brouard  2037: #ifdef LINMINORIGINAL
                   2038: #else
                   2039:        if(fb == fx){ /* Flat function in the direction */
                   2040:                xmin=xx;
                   2041:     *flat=1;
                   2042:        }else{
                   2043:     *flat=0;
                   2044: #endif
                   2045:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2046:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2047:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2048:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2049:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2050:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2051: #ifdef DEBUG
1.224     brouard  2052:   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);
                   2053:   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);
                   2054: #endif
                   2055: #ifdef LINMINORIGINAL
                   2056: #else
                   2057:                        }
1.126     brouard  2058: #endif
1.191     brouard  2059: #ifdef DEBUGLINMIN
                   2060:   printf("linmin end ");
1.202     brouard  2061:   fprintf(ficlog,"linmin end ");
1.191     brouard  2062: #endif
1.126     brouard  2063:   for (j=1;j<=n;j++) { 
1.203     brouard  2064: #ifdef LINMINORIGINAL
                   2065:     xi[j] *= xmin; 
                   2066: #else
                   2067: #ifdef DEBUGLINMIN
                   2068:     if(xxs <1.0)
                   2069:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2070: #endif
                   2071:     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) */
                   2072: #ifdef DEBUGLINMIN
                   2073:     if(xxs <1.0)
                   2074:       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 );
                   2075: #endif
                   2076: #endif
1.187     brouard  2077:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2078:   } 
1.191     brouard  2079: #ifdef DEBUGLINMIN
1.203     brouard  2080:   printf("\n");
1.191     brouard  2081:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2082:   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  2083:   for (j=1;j<=n;j++) { 
1.202     brouard  2084:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2085:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2086:     if(j % ncovmodel == 0){
1.191     brouard  2087:       printf("\n");
1.202     brouard  2088:       fprintf(ficlog,"\n");
                   2089:     }
1.191     brouard  2090:   }
1.203     brouard  2091: #else
1.191     brouard  2092: #endif
1.126     brouard  2093:   free_vector(xicom,1,n); 
                   2094:   free_vector(pcom,1,n); 
                   2095: } 
                   2096: 
                   2097: 
                   2098: /*************** powell ************************/
1.162     brouard  2099: /*
                   2100: Minimization of a function func of n variables. Input consists of an initial starting point
                   2101: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2102: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2103: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2104: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2105: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2106:  */
1.224     brouard  2107: #ifdef LINMINORIGINAL
                   2108: #else
                   2109:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2110:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2111: #endif
1.126     brouard  2112: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2113:            double (*func)(double [])) 
                   2114: { 
1.224     brouard  2115: #ifdef LINMINORIGINAL
                   2116:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2117:              double (*func)(double [])); 
1.224     brouard  2118: #else 
1.241     brouard  2119:  void linmin(double p[], double xi[], int n, double *fret,
                   2120:             double (*func)(double []),int *flat); 
1.224     brouard  2121: #endif
1.239     brouard  2122:  int i,ibig,j,jk,k; 
1.126     brouard  2123:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2124:   double directest;
1.126     brouard  2125:   double fp,fptt;
                   2126:   double *xits;
                   2127:   int niterf, itmp;
1.224     brouard  2128: #ifdef LINMINORIGINAL
                   2129: #else
                   2130: 
                   2131:   flatdir=ivector(1,n); 
                   2132:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2133: #endif
1.126     brouard  2134: 
                   2135:   pt=vector(1,n); 
                   2136:   ptt=vector(1,n); 
                   2137:   xit=vector(1,n); 
                   2138:   xits=vector(1,n); 
                   2139:   *fret=(*func)(p); 
                   2140:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2141:   rcurr_time = time(NULL);  
1.126     brouard  2142:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2143:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2144:     ibig=0; 
                   2145:     del=0.0; 
1.157     brouard  2146:     rlast_time=rcurr_time;
                   2147:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2148:     rcurr_time = time(NULL);  
                   2149:     curr_time = *localtime(&rcurr_time);
                   2150:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2151:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2152: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2153:     for (i=1;i<=n;i++) {
1.126     brouard  2154:       fprintf(ficrespow," %.12lf", p[i]);
                   2155:     }
1.239     brouard  2156:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2157:     printf("\n#model=  1      +     age ");
                   2158:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2159:     if(nagesqr==1){
1.241     brouard  2160:        printf("  + age*age  ");
                   2161:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2162:     }
                   2163:     for(j=1;j <=ncovmodel-2;j++){
                   2164:       if(Typevar[j]==0) {
                   2165:        printf("  +      V%d  ",Tvar[j]);
                   2166:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2167:       }else if(Typevar[j]==1) {
                   2168:        printf("  +    V%d*age ",Tvar[j]);
                   2169:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2170:       }else if(Typevar[j]==2) {
                   2171:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2172:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2173:       }
                   2174:     }
1.126     brouard  2175:     printf("\n");
1.239     brouard  2176: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2177: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2178:     fprintf(ficlog,"\n");
1.239     brouard  2179:     for(i=1,jk=1; i <=nlstate; i++){
                   2180:       for(k=1; k <=(nlstate+ndeath); k++){
                   2181:        if (k != i) {
                   2182:          printf("%d%d ",i,k);
                   2183:          fprintf(ficlog,"%d%d ",i,k);
                   2184:          for(j=1; j <=ncovmodel; j++){
                   2185:            printf("%12.7f ",p[jk]);
                   2186:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2187:            jk++; 
                   2188:          }
                   2189:          printf("\n");
                   2190:          fprintf(ficlog,"\n");
                   2191:        }
                   2192:       }
                   2193:     }
1.241     brouard  2194:     if(*iter <=3 && *iter >1){
1.157     brouard  2195:       tml = *localtime(&rcurr_time);
                   2196:       strcpy(strcurr,asctime(&tml));
                   2197:       rforecast_time=rcurr_time; 
1.126     brouard  2198:       itmp = strlen(strcurr);
                   2199:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2200:        strcurr[itmp-1]='\0';
1.162     brouard  2201:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2202:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2203:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2204:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2205:        forecast_time = *localtime(&rforecast_time);
                   2206:        strcpy(strfor,asctime(&forecast_time));
                   2207:        itmp = strlen(strfor);
                   2208:        if(strfor[itmp-1]=='\n')
                   2209:          strfor[itmp-1]='\0';
                   2210:        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);
                   2211:        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  2212:       }
                   2213:     }
1.187     brouard  2214:     for (i=1;i<=n;i++) { /* For each direction i */
                   2215:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2216:       fptt=(*fret); 
                   2217: #ifdef DEBUG
1.203     brouard  2218:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2219:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2220: #endif
1.203     brouard  2221:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2222:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2223: #ifdef LINMINORIGINAL
1.188     brouard  2224:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2225: #else
                   2226:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2227:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2228: #endif
                   2229:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2230:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2231:                                /* because that direction will be replaced unless the gain del is small */
                   2232:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2233:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2234:                                /* with the new direction. */
                   2235:                                del=fabs(fptt-(*fret)); 
                   2236:                                ibig=i; 
1.126     brouard  2237:       } 
                   2238: #ifdef DEBUG
                   2239:       printf("%d %.12e",i,(*fret));
                   2240:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2241:       for (j=1;j<=n;j++) {
1.224     brouard  2242:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2243:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2244:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2245:       }
                   2246:       for(j=1;j<=n;j++) {
1.225     brouard  2247:                                printf(" p(%d)=%.12e",j,p[j]);
                   2248:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2249:       }
                   2250:       printf("\n");
                   2251:       fprintf(ficlog,"\n");
                   2252: #endif
1.187     brouard  2253:     } /* end loop on each direction i */
                   2254:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2255:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2256:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2257:       for(j=1;j<=n;j++) {
1.225     brouard  2258:                                if(flatdir[j] >0){
                   2259:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2260:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2261:                                }
                   2262:                                /* printf("\n"); */
                   2263:                                /* fprintf(ficlog,"\n"); */
                   2264:                        }
1.243     brouard  2265:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2266:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2267:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2268:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2269:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2270:       /* decreased of more than 3.84  */
                   2271:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2272:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2273:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2274:                        
1.188     brouard  2275:       /* Starting the program with initial values given by a former maximization will simply change */
                   2276:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2277:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2278:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2279: #ifdef DEBUG
                   2280:       int k[2],l;
                   2281:       k[0]=1;
                   2282:       k[1]=-1;
                   2283:       printf("Max: %.12e",(*func)(p));
                   2284:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2285:       for (j=1;j<=n;j++) {
                   2286:        printf(" %.12e",p[j]);
                   2287:        fprintf(ficlog," %.12e",p[j]);
                   2288:       }
                   2289:       printf("\n");
                   2290:       fprintf(ficlog,"\n");
                   2291:       for(l=0;l<=1;l++) {
                   2292:        for (j=1;j<=n;j++) {
                   2293:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2294:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2295:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2296:        }
                   2297:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2298:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2299:       }
                   2300: #endif
                   2301: 
1.224     brouard  2302: #ifdef LINMINORIGINAL
                   2303: #else
                   2304:       free_ivector(flatdir,1,n); 
                   2305: #endif
1.126     brouard  2306:       free_vector(xit,1,n); 
                   2307:       free_vector(xits,1,n); 
                   2308:       free_vector(ptt,1,n); 
                   2309:       free_vector(pt,1,n); 
                   2310:       return; 
1.192     brouard  2311:     } /* enough precision */ 
1.240     brouard  2312:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2313:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2314:       ptt[j]=2.0*p[j]-pt[j]; 
                   2315:       xit[j]=p[j]-pt[j]; 
                   2316:       pt[j]=p[j]; 
                   2317:     } 
1.181     brouard  2318:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2319: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2320:                if (*iter <=4) {
1.225     brouard  2321: #else
                   2322: #endif
1.224     brouard  2323: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2324: #else
1.161     brouard  2325:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2326: #endif
1.162     brouard  2327:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2328:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2329:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2330:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2331:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2332:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2333:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2334:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2335:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2336:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2337:       /* mu² and del² are equal when f3=f1 */
                   2338:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2339:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2340:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2341:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2342: #ifdef NRCORIGINAL
                   2343:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2344: #else
                   2345:       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  2346:       t= t- del*SQR(fp-fptt);
1.183     brouard  2347: #endif
1.202     brouard  2348:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2349: #ifdef DEBUG
1.181     brouard  2350:       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);
                   2351:       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  2352:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2353:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2354:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2355:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2356:       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);
                   2357:       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);
                   2358: #endif
1.183     brouard  2359: #ifdef POWELLORIGINAL
                   2360:       if (t < 0.0) { /* Then we use it for new direction */
                   2361: #else
1.182     brouard  2362:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2363:                                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  2364:         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  2365:         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  2366:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2367:       } 
1.181     brouard  2368:       if (directest < 0.0) { /* Then we use it for new direction */
                   2369: #endif
1.191     brouard  2370: #ifdef DEBUGLINMIN
1.234     brouard  2371:        printf("Before linmin in direction P%d-P0\n",n);
                   2372:        for (j=1;j<=n;j++) {
                   2373:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2374:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2375:          if(j % ncovmodel == 0){
                   2376:            printf("\n");
                   2377:            fprintf(ficlog,"\n");
                   2378:          }
                   2379:        }
1.224     brouard  2380: #endif
                   2381: #ifdef LINMINORIGINAL
1.234     brouard  2382:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2383: #else
1.234     brouard  2384:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2385:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2386: #endif
1.234     brouard  2387:        
1.191     brouard  2388: #ifdef DEBUGLINMIN
1.234     brouard  2389:        for (j=1;j<=n;j++) { 
                   2390:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2391:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2392:          if(j % ncovmodel == 0){
                   2393:            printf("\n");
                   2394:            fprintf(ficlog,"\n");
                   2395:          }
                   2396:        }
1.224     brouard  2397: #endif
1.234     brouard  2398:        for (j=1;j<=n;j++) { 
                   2399:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2400:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2401:        }
1.224     brouard  2402: #ifdef LINMINORIGINAL
                   2403: #else
1.234     brouard  2404:        for (j=1, flatd=0;j<=n;j++) {
                   2405:          if(flatdir[j]>0)
                   2406:            flatd++;
                   2407:        }
                   2408:        if(flatd >0){
1.255     brouard  2409:          printf("%d flat directions: ",flatd);
                   2410:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2411:          for (j=1;j<=n;j++) { 
                   2412:            if(flatdir[j]>0){
                   2413:              printf("%d ",j);
                   2414:              fprintf(ficlog,"%d ",j);
                   2415:            }
                   2416:          }
                   2417:          printf("\n");
                   2418:          fprintf(ficlog,"\n");
                   2419:        }
1.191     brouard  2420: #endif
1.234     brouard  2421:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2422:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2423:        
1.126     brouard  2424: #ifdef DEBUG
1.234     brouard  2425:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2426:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2427:        for(j=1;j<=n;j++){
                   2428:          printf(" %lf",xit[j]);
                   2429:          fprintf(ficlog," %lf",xit[j]);
                   2430:        }
                   2431:        printf("\n");
                   2432:        fprintf(ficlog,"\n");
1.126     brouard  2433: #endif
1.192     brouard  2434:       } /* end of t or directest negative */
1.224     brouard  2435: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2436: #else
1.234     brouard  2437:       } /* end if (fptt < fp)  */
1.192     brouard  2438: #endif
1.225     brouard  2439: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2440:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2441: #else
1.224     brouard  2442: #endif
1.234     brouard  2443:                } /* loop iteration */ 
1.126     brouard  2444: } 
1.234     brouard  2445:   
1.126     brouard  2446: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2447:   
1.235     brouard  2448:   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  2449:   {
1.235     brouard  2450:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2451:        (and selected quantitative values in nres)
                   2452:        by left multiplying the unit
1.234     brouard  2453:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2454:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2455:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2456:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2457:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2458:   /* Initial matrix pimij */
                   2459:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2460:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2461:   /*  0,                   0                  , 1} */
                   2462:   /*
                   2463:    * and after some iteration: */
                   2464:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2465:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2466:   /*  0,                   0                  , 1} */
                   2467:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2468:   /* {0.51571254859325999, 0.4842874514067399, */
                   2469:   /*  0.51326036147820708, 0.48673963852179264} */
                   2470:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2471:     
1.126     brouard  2472:   int i, ii,j,k;
1.209     brouard  2473:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2474:   /* double **matprod2(); */ /* test */
1.218     brouard  2475:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2476:   double **newm;
1.209     brouard  2477:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2478:   int ncvloop=0;
1.169     brouard  2479:   
1.209     brouard  2480:   min=vector(1,nlstate);
                   2481:   max=vector(1,nlstate);
                   2482:   meandiff=vector(1,nlstate);
                   2483: 
1.218     brouard  2484:        /* Starting with matrix unity */
1.126     brouard  2485:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2486:     for (j=1;j<=nlstate+ndeath;j++){
                   2487:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2488:     }
1.169     brouard  2489:   
                   2490:   cov[1]=1.;
                   2491:   
                   2492:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2493:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2494:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2495:     ncvloop++;
1.126     brouard  2496:     newm=savm;
                   2497:     /* Covariates have to be included here again */
1.138     brouard  2498:     cov[2]=agefin;
1.187     brouard  2499:     if(nagesqr==1)
                   2500:       cov[3]= agefin*agefin;;
1.234     brouard  2501:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2502:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2503:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2504:       /* 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  2505:     }
                   2506:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2507:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2508:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2509:       /* 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  2510:     }
1.237     brouard  2511:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2512:       if(Dummy[Tvar[Tage[k]]]){
                   2513:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2514:       } else{
1.235     brouard  2515:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2516:       }
1.235     brouard  2517:       /* 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  2518:     }
1.237     brouard  2519:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2520:       /* 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  2521:       if(Dummy[Tvard[k][1]==0]){
                   2522:        if(Dummy[Tvard[k][2]==0]){
                   2523:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2524:        }else{
                   2525:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2526:        }
                   2527:       }else{
                   2528:        if(Dummy[Tvard[k][2]==0]){
                   2529:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2530:        }else{
                   2531:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2532:        }
                   2533:       }
1.234     brouard  2534:     }
1.138     brouard  2535:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2536:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2537:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2538:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2539:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2540:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2541:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2542:     
1.126     brouard  2543:     savm=oldm;
                   2544:     oldm=newm;
1.209     brouard  2545: 
                   2546:     for(j=1; j<=nlstate; j++){
                   2547:       max[j]=0.;
                   2548:       min[j]=1.;
                   2549:     }
                   2550:     for(i=1;i<=nlstate;i++){
                   2551:       sumnew=0;
                   2552:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2553:       for(j=1; j<=nlstate; j++){ 
                   2554:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2555:        max[j]=FMAX(max[j],prlim[i][j]);
                   2556:        min[j]=FMIN(min[j],prlim[i][j]);
                   2557:       }
                   2558:     }
                   2559: 
1.126     brouard  2560:     maxmax=0.;
1.209     brouard  2561:     for(j=1; j<=nlstate; j++){
                   2562:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2563:       maxmax=FMAX(maxmax,meandiff[j]);
                   2564:       /* 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  2565:     } /* j loop */
1.203     brouard  2566:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2567:     /* 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  2568:     if(maxmax < ftolpl){
1.209     brouard  2569:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2570:       free_vector(min,1,nlstate);
                   2571:       free_vector(max,1,nlstate);
                   2572:       free_vector(meandiff,1,nlstate);
1.126     brouard  2573:       return prlim;
                   2574:     }
1.169     brouard  2575:   } /* age loop */
1.208     brouard  2576:     /* After some age loop it doesn't converge */
1.209     brouard  2577:   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  2578: 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  2579:   /* 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); */
                   2580:   free_vector(min,1,nlstate);
                   2581:   free_vector(max,1,nlstate);
                   2582:   free_vector(meandiff,1,nlstate);
1.208     brouard  2583:   
1.169     brouard  2584:   return prlim; /* should not reach here */
1.126     brouard  2585: }
                   2586: 
1.217     brouard  2587: 
                   2588:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2589: 
1.218     brouard  2590:  /* 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) */
                   2591:  /* 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  2592:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2593: {
1.218     brouard  2594:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2595:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2596:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2597:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2598:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2599:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2600:   /* Initial matrix pimij */
                   2601:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2602:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2603:   /*  0,                   0                  , 1} */
                   2604:   /*
                   2605:    * and after some iteration: */
                   2606:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2607:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2608:   /*  0,                   0                  , 1} */
                   2609:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2610:   /* {0.51571254859325999, 0.4842874514067399, */
                   2611:   /*  0.51326036147820708, 0.48673963852179264} */
                   2612:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2613: 
                   2614:   int i, ii,j,k;
1.247     brouard  2615:   int first=0;
1.217     brouard  2616:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2617:   /* double **matprod2(); */ /* test */
                   2618:   double **out, cov[NCOVMAX+1], **bmij();
                   2619:   double **newm;
1.218     brouard  2620:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2621:   double        **oldm, **savm;  /* for use */
                   2622: 
1.217     brouard  2623:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2624:   int ncvloop=0;
                   2625:   
                   2626:   min=vector(1,nlstate);
                   2627:   max=vector(1,nlstate);
                   2628:   meandiff=vector(1,nlstate);
                   2629: 
1.218     brouard  2630:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2631:        oldm=oldms; savm=savms;
                   2632: 
                   2633:        /* Starting with matrix unity */
                   2634:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2635:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2636:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2637:     }
                   2638:   
                   2639:   cov[1]=1.;
                   2640:   
                   2641:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2642:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2643:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2644:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2645:     ncvloop++;
1.218     brouard  2646:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2647:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2648:     /* Covariates have to be included here again */
                   2649:     cov[2]=agefin;
                   2650:     if(nagesqr==1)
                   2651:       cov[3]= agefin*agefin;;
1.242     brouard  2652:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2653:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2654:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2655:       /* 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)); */
                   2656:     }
                   2657:     /* for (k=1; k<=cptcovn;k++) { */
                   2658:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2659:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2660:     /*   /\* 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])]); *\/ */
                   2661:     /* } */
                   2662:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2663:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2664:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2665:       /* 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]); */
                   2666:     }
                   2667:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2668:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2669:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2670:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2671:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2672:       if(Dummy[Tvar[Tage[k]]]){
                   2673:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2674:       } else{
                   2675:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2676:       }
                   2677:       /* 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]); */
                   2678:     }
                   2679:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2680:       /* 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]); */
                   2681:       if(Dummy[Tvard[k][1]==0]){
                   2682:        if(Dummy[Tvard[k][2]==0]){
                   2683:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2684:        }else{
                   2685:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2686:        }
                   2687:       }else{
                   2688:        if(Dummy[Tvard[k][2]==0]){
                   2689:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2690:        }else{
                   2691:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2692:        }
                   2693:       }
1.217     brouard  2694:     }
                   2695:     
                   2696:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2697:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2698:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2699:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2700:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2701:                /* ij should be linked to the correct index of cov */
                   2702:                /* age and covariate values ij are in 'cov', but we need to pass
                   2703:                 * ij for the observed prevalence at age and status and covariate
                   2704:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2705:                 */
                   2706:     /* 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 *\/ */
                   2707:     /* 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 *\/ */
                   2708:     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  2709:     savm=oldm;
                   2710:     oldm=newm;
                   2711:     for(j=1; j<=nlstate; j++){
                   2712:       max[j]=0.;
                   2713:       min[j]=1.;
                   2714:     }
                   2715:     for(j=1; j<=nlstate; j++){ 
                   2716:       for(i=1;i<=nlstate;i++){
1.234     brouard  2717:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2718:        bprlim[i][j]= newm[i][j];
                   2719:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2720:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2721:       }
                   2722:     }
1.218     brouard  2723:                
1.217     brouard  2724:     maxmax=0.;
                   2725:     for(i=1; i<=nlstate; i++){
                   2726:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2727:       maxmax=FMAX(maxmax,meandiff[i]);
                   2728:       /* 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); */
                   2729:     } /* j loop */
                   2730:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2731:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2732:     if(maxmax < ftolpl){
1.220     brouard  2733:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2734:       free_vector(min,1,nlstate);
                   2735:       free_vector(max,1,nlstate);
                   2736:       free_vector(meandiff,1,nlstate);
                   2737:       return bprlim;
                   2738:     }
                   2739:   } /* age loop */
                   2740:     /* After some age loop it doesn't converge */
1.247     brouard  2741:   if(first){
                   2742:     first=1;
                   2743:     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\
                   2744: 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);
                   2745:   }
                   2746:   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  2747: 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);
                   2748:   /* 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); */
                   2749:   free_vector(min,1,nlstate);
                   2750:   free_vector(max,1,nlstate);
                   2751:   free_vector(meandiff,1,nlstate);
                   2752:   
                   2753:   return bprlim; /* should not reach here */
                   2754: }
                   2755: 
1.126     brouard  2756: /*************** transition probabilities ***************/ 
                   2757: 
                   2758: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2759: {
1.138     brouard  2760:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2761:      computes the probability to be observed in state j being in state i by appying the
                   2762:      model to the ncovmodel covariates (including constant and age).
                   2763:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2764:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2765:      ncth covariate in the global vector x is given by the formula:
                   2766:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2767:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2768:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2769:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2770:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2771:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2772:   */
                   2773:   double s1, lnpijopii;
1.126     brouard  2774:   /*double t34;*/
1.164     brouard  2775:   int i,j, nc, ii, jj;
1.126     brouard  2776: 
1.223     brouard  2777:   for(i=1; i<= nlstate; i++){
                   2778:     for(j=1; j<i;j++){
                   2779:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2780:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2781:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2782:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2783:       }
                   2784:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2785:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2786:     }
                   2787:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2788:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2789:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2790:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2791:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2792:       }
                   2793:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2794:     }
                   2795:   }
1.218     brouard  2796:   
1.223     brouard  2797:   for(i=1; i<= nlstate; i++){
                   2798:     s1=0;
                   2799:     for(j=1; j<i; j++){
                   2800:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2801:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2802:     }
                   2803:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2804:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2805:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2806:     }
                   2807:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2808:     ps[i][i]=1./(s1+1.);
                   2809:     /* Computing other pijs */
                   2810:     for(j=1; j<i; j++)
                   2811:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2812:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2813:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2814:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2815:   } /* end i */
1.218     brouard  2816:   
1.223     brouard  2817:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2818:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2819:       ps[ii][jj]=0;
                   2820:       ps[ii][ii]=1;
                   2821:     }
                   2822:   }
1.218     brouard  2823:   
                   2824:   
1.223     brouard  2825:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2826:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2827:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2828:   /*   } */
                   2829:   /*   printf("\n "); */
                   2830:   /* } */
                   2831:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2832:   /*
                   2833:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2834:                goto end;*/
1.223     brouard  2835:   return ps;
1.126     brouard  2836: }
                   2837: 
1.218     brouard  2838: /*************** backward transition probabilities ***************/ 
                   2839: 
                   2840:  /* 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 ) */
                   2841: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2842:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2843: {
1.222     brouard  2844:   /* Computes the backward probability at age agefin and covariate ij
                   2845:    * and returns in **ps as well as **bmij.
                   2846:    */
1.218     brouard  2847:   int i, ii, j,k;
1.222     brouard  2848:   
                   2849:   double **out, **pmij();
                   2850:   double sumnew=0.;
1.218     brouard  2851:   double agefin;
1.222     brouard  2852:   
                   2853:   double **dnewm, **dsavm, **doldm;
                   2854:   double **bbmij;
                   2855:   
1.218     brouard  2856:   doldm=ddoldms; /* global pointers */
1.222     brouard  2857:   dnewm=ddnewms;
                   2858:   dsavm=ddsavms;
                   2859:   
                   2860:   agefin=cov[2];
                   2861:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2862:      the observed prevalence (with this covariate ij) */
                   2863:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2864:   /* We do have the matrix Px in savm  and we need pij */
                   2865:   for (j=1;j<=nlstate+ndeath;j++){
                   2866:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2867:     for (ii=1;ii<=nlstate;ii++){
                   2868:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2869:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2870:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2871:       if(sumnew >= 1.e-10){
                   2872:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2873:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2874:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2875:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2876:        /* }else */
                   2877:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2878:       }else{
1.242     brouard  2879:        ;
                   2880:        /* 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  2881:       }
                   2882:     } /*End ii */
                   2883:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2884:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2885:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2886:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2887:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2888:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2889:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2890:   for (j=1;j<=nlstate+ndeath;j++){
                   2891:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2892:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2893:     }
                   2894:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2895:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2896:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2897:   /* end bmij */
                   2898:   return ps; 
1.218     brouard  2899: }
1.217     brouard  2900: /*************** transition probabilities ***************/ 
                   2901: 
1.218     brouard  2902: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2903: {
                   2904:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2905:      computes the probability to be observed in state j being in state i by appying the
                   2906:      model to the ncovmodel covariates (including constant and age).
                   2907:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2908:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2909:      ncth covariate in the global vector x is given by the formula:
                   2910:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2911:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2912:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2913:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2914:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2915:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2916:   */
                   2917:   double s1, lnpijopii;
                   2918:   /*double t34;*/
                   2919:   int i,j, nc, ii, jj;
                   2920: 
1.234     brouard  2921:   for(i=1; i<= nlstate; i++){
                   2922:     for(j=1; j<i;j++){
                   2923:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2924:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2925:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2926:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2927:       }
                   2928:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2929:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2930:     }
                   2931:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2932:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2933:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2934:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2935:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2936:       }
                   2937:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2938:     }
                   2939:   }
                   2940:   
                   2941:   for(i=1; i<= nlstate; i++){
                   2942:     s1=0;
                   2943:     for(j=1; j<i; j++){
                   2944:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2945:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2946:     }
                   2947:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2948:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2949:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2950:     }
                   2951:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2952:     ps[i][i]=1./(s1+1.);
                   2953:     /* Computing other pijs */
                   2954:     for(j=1; j<i; j++)
                   2955:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2956:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2957:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2958:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2959:   } /* end i */
                   2960:   
                   2961:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2962:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2963:       ps[ii][jj]=0;
                   2964:       ps[ii][ii]=1;
                   2965:     }
                   2966:   }
                   2967:   /* Added for backcast */ /* Transposed matrix too */
                   2968:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2969:     s1=0.;
                   2970:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2971:       s1+=ps[ii][jj];
                   2972:     }
                   2973:     for(ii=1; ii<= nlstate; ii++){
                   2974:       ps[ii][jj]=ps[ii][jj]/s1;
                   2975:     }
                   2976:   }
                   2977:   /* Transposition */
                   2978:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2979:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2980:       s1=ps[ii][jj];
                   2981:       ps[ii][jj]=ps[jj][ii];
                   2982:       ps[jj][ii]=s1;
                   2983:     }
                   2984:   }
                   2985:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2986:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2987:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2988:   /*   } */
                   2989:   /*   printf("\n "); */
                   2990:   /* } */
                   2991:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2992:   /*
                   2993:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2994:     goto end;*/
                   2995:   return ps;
1.217     brouard  2996: }
                   2997: 
                   2998: 
1.126     brouard  2999: /**************** Product of 2 matrices ******************/
                   3000: 
1.145     brouard  3001: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3002: {
                   3003:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3004:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3005:   /* in, b, out are matrice of pointers which should have been initialized 
                   3006:      before: only the contents of out is modified. The function returns
                   3007:      a pointer to pointers identical to out */
1.145     brouard  3008:   int i, j, k;
1.126     brouard  3009:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3010:     for(k=ncolol; k<=ncoloh; k++){
                   3011:       out[i][k]=0.;
                   3012:       for(j=ncl; j<=nch; j++)
                   3013:        out[i][k] +=in[i][j]*b[j][k];
                   3014:     }
1.126     brouard  3015:   return out;
                   3016: }
                   3017: 
                   3018: 
                   3019: /************* Higher Matrix Product ***************/
                   3020: 
1.235     brouard  3021: 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  3022: {
1.218     brouard  3023:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3024:      'nhstepm*hstepm*stepm' months (i.e. until
                   3025:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3026:      nhstepm*hstepm matrices. 
                   3027:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3028:      (typically every 2 years instead of every month which is too big 
                   3029:      for the memory).
                   3030:      Model is determined by parameters x and covariates have to be 
                   3031:      included manually here. 
                   3032: 
                   3033:      */
                   3034: 
                   3035:   int i, j, d, h, k;
1.131     brouard  3036:   double **out, cov[NCOVMAX+1];
1.126     brouard  3037:   double **newm;
1.187     brouard  3038:   double agexact;
1.214     brouard  3039:   double agebegin, ageend;
1.126     brouard  3040: 
                   3041:   /* Hstepm could be zero and should return the unit matrix */
                   3042:   for (i=1;i<=nlstate+ndeath;i++)
                   3043:     for (j=1;j<=nlstate+ndeath;j++){
                   3044:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3045:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3046:     }
                   3047:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3048:   for(h=1; h <=nhstepm; h++){
                   3049:     for(d=1; d <=hstepm; d++){
                   3050:       newm=savm;
                   3051:       /* Covariates have to be included here again */
                   3052:       cov[1]=1.;
1.214     brouard  3053:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3054:       cov[2]=agexact;
                   3055:       if(nagesqr==1)
1.227     brouard  3056:        cov[3]= agexact*agexact;
1.235     brouard  3057:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3058:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3059:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3060:        /* 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)); */
                   3061:       }
                   3062:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3063:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3064:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3065:        /* 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]); */
                   3066:       }
                   3067:       for (k=1; k<=cptcovage;k++){
                   3068:        if(Dummy[Tvar[Tage[k]]]){
                   3069:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3070:        } else{
                   3071:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3072:        }
                   3073:        /* 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]); */
                   3074:       }
                   3075:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3076:        /* 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]); */
                   3077:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3078:       }
                   3079:       /* for (k=1; k<=cptcovn;k++)  */
                   3080:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3081:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3082:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3083:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3084:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3085:       
                   3086:       
1.126     brouard  3087:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3088:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3089:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3090:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3091:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3092:       /* if((int)age == 70){ */
                   3093:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3094:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3095:       /*         printf("%d pmmij ",i); */
                   3096:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3097:       /*           printf("%f ",pmmij[i][j]); */
                   3098:       /*         } */
                   3099:       /*         printf(" oldm "); */
                   3100:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3101:       /*           printf("%f ",oldm[i][j]); */
                   3102:       /*         } */
                   3103:       /*         printf("\n"); */
                   3104:       /*       } */
                   3105:       /* } */
1.126     brouard  3106:       savm=oldm;
                   3107:       oldm=newm;
                   3108:     }
                   3109:     for(i=1; i<=nlstate+ndeath; i++)
                   3110:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3111:                                po[i][j][h]=newm[i][j];
                   3112:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3113:       }
1.128     brouard  3114:     /*printf("h=%d ",h);*/
1.126     brouard  3115:   } /* end h */
1.218     brouard  3116:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3117:   return po;
                   3118: }
                   3119: 
1.217     brouard  3120: /************* Higher Back Matrix Product ***************/
1.218     brouard  3121: /* 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  3122: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3123: {
1.218     brouard  3124:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3125:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3126:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3127:      nhstepm*hstepm matrices.
                   3128:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3129:      (typically every 2 years instead of every month which is too big
1.217     brouard  3130:      for the memory).
1.218     brouard  3131:      Model is determined by parameters x and covariates have to be
                   3132:      included manually here.
1.217     brouard  3133: 
1.222     brouard  3134:   */
1.217     brouard  3135: 
                   3136:   int i, j, d, h, k;
                   3137:   double **out, cov[NCOVMAX+1];
                   3138:   double **newm;
                   3139:   double agexact;
                   3140:   double agebegin, ageend;
1.222     brouard  3141:   double **oldm, **savm;
1.217     brouard  3142: 
1.222     brouard  3143:   oldm=oldms;savm=savms;
1.217     brouard  3144:   /* Hstepm could be zero and should return the unit matrix */
                   3145:   for (i=1;i<=nlstate+ndeath;i++)
                   3146:     for (j=1;j<=nlstate+ndeath;j++){
                   3147:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3148:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3149:     }
                   3150:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3151:   for(h=1; h <=nhstepm; h++){
                   3152:     for(d=1; d <=hstepm; d++){
                   3153:       newm=savm;
                   3154:       /* Covariates have to be included here again */
                   3155:       cov[1]=1.;
                   3156:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3157:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3158:       cov[2]=agexact;
                   3159:       if(nagesqr==1)
1.222     brouard  3160:        cov[3]= agexact*agexact;
1.218     brouard  3161:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3162:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3163:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3164:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3165:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3166:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3167:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3168:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3169:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3170:       /* 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  3171:                        
                   3172:                        
1.217     brouard  3173:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3174:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3175:       /* Careful transposed matrix */
1.222     brouard  3176:       /* age is in cov[2] */
1.218     brouard  3177:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3178:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3179:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3180:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3181:       /* if((int)age == 70){ */
                   3182:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3183:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3184:       /*         printf("%d pmmij ",i); */
                   3185:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3186:       /*           printf("%f ",pmmij[i][j]); */
                   3187:       /*         } */
                   3188:       /*         printf(" oldm "); */
                   3189:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3190:       /*           printf("%f ",oldm[i][j]); */
                   3191:       /*         } */
                   3192:       /*         printf("\n"); */
                   3193:       /*       } */
                   3194:       /* } */
                   3195:       savm=oldm;
                   3196:       oldm=newm;
                   3197:     }
                   3198:     for(i=1; i<=nlstate+ndeath; i++)
                   3199:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3200:        po[i][j][h]=newm[i][j];
                   3201:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3202:       }
                   3203:     /*printf("h=%d ",h);*/
                   3204:   } /* end h */
1.222     brouard  3205:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3206:   return po;
                   3207: }
                   3208: 
                   3209: 
1.162     brouard  3210: #ifdef NLOPT
                   3211:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3212:   double fret;
                   3213:   double *xt;
                   3214:   int j;
                   3215:   myfunc_data *d2 = (myfunc_data *) pd;
                   3216: /* xt = (p1-1); */
                   3217:   xt=vector(1,n); 
                   3218:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3219: 
                   3220:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3221:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3222:   printf("Function = %.12lf ",fret);
                   3223:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3224:   printf("\n");
                   3225:  free_vector(xt,1,n);
                   3226:   return fret;
                   3227: }
                   3228: #endif
1.126     brouard  3229: 
                   3230: /*************** log-likelihood *************/
                   3231: double func( double *x)
                   3232: {
1.226     brouard  3233:   int i, ii, j, k, mi, d, kk;
                   3234:   int ioffset=0;
                   3235:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3236:   double **out;
                   3237:   double lli; /* Individual log likelihood */
                   3238:   int s1, s2;
1.228     brouard  3239:   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  3240:   double bbh, survp;
                   3241:   long ipmx;
                   3242:   double agexact;
                   3243:   /*extern weight */
                   3244:   /* We are differentiating ll according to initial status */
                   3245:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3246:   /*for(i=1;i<imx;i++) 
                   3247:     printf(" %d\n",s[4][i]);
                   3248:   */
1.162     brouard  3249: 
1.226     brouard  3250:   ++countcallfunc;
1.162     brouard  3251: 
1.226     brouard  3252:   cov[1]=1.;
1.126     brouard  3253: 
1.226     brouard  3254:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3255:   ioffset=0;
1.226     brouard  3256:   if(mle==1){
                   3257:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3258:       /* Computes the values of the ncovmodel covariates of the model
                   3259:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3260:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3261:         to be observed in j being in i according to the model.
                   3262:       */
1.243     brouard  3263:       ioffset=2+nagesqr ;
1.233     brouard  3264:    /* Fixed */
1.234     brouard  3265:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3266:        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)*/
                   3267:       }
1.226     brouard  3268:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3269:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3270:         has been calculated etc */
                   3271:       /* For an individual i, wav[i] gives the number of effective waves */
                   3272:       /* We compute the contribution to Likelihood of each effective transition
                   3273:         mw[mi][i] is real wave of the mi th effectve wave */
                   3274:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3275:         s2=s[mw[mi+1][i]][i];
                   3276:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3277:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3278:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3279:       */
                   3280:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3281:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3282:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3283:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3284:        }
                   3285:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3286:          for (j=1;j<=nlstate+ndeath;j++){
                   3287:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3288:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3289:          }
                   3290:        for(d=0; d<dh[mi][i]; d++){
                   3291:          newm=savm;
                   3292:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3293:          cov[2]=agexact;
                   3294:          if(nagesqr==1)
                   3295:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3296:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3297:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3298:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3299:          else
                   3300:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3301:          }
                   3302:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3303:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3304:          savm=oldm;
                   3305:          oldm=newm;
                   3306:        } /* end mult */
                   3307:        
                   3308:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3309:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3310:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3311:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3312:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3313:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3314:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3315:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3316:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3317:                                 * -stepm/2 to stepm/2 .
                   3318:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3319:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3320:                                 */
1.234     brouard  3321:        s1=s[mw[mi][i]][i];
                   3322:        s2=s[mw[mi+1][i]][i];
                   3323:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3324:        /* bias bh is positive if real duration
                   3325:         * is higher than the multiple of stepm and negative otherwise.
                   3326:         */
                   3327:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3328:        if( s2 > nlstate){ 
                   3329:          /* i.e. if s2 is a death state and if the date of death is known 
                   3330:             then the contribution to the likelihood is the probability to 
                   3331:             die between last step unit time and current  step unit time, 
                   3332:             which is also equal to probability to die before dh 
                   3333:             minus probability to die before dh-stepm . 
                   3334:             In version up to 0.92 likelihood was computed
                   3335:             as if date of death was unknown. Death was treated as any other
                   3336:             health state: the date of the interview describes the actual state
                   3337:             and not the date of a change in health state. The former idea was
                   3338:             to consider that at each interview the state was recorded
                   3339:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3340:             introduced the exact date of death then we should have modified
                   3341:             the contribution of an exact death to the likelihood. This new
                   3342:             contribution is smaller and very dependent of the step unit
                   3343:             stepm. It is no more the probability to die between last interview
                   3344:             and month of death but the probability to survive from last
                   3345:             interview up to one month before death multiplied by the
                   3346:             probability to die within a month. Thanks to Chris
                   3347:             Jackson for correcting this bug.  Former versions increased
                   3348:             mortality artificially. The bad side is that we add another loop
                   3349:             which slows down the processing. The difference can be up to 10%
                   3350:             lower mortality.
                   3351:          */
                   3352:          /* If, at the beginning of the maximization mostly, the
                   3353:             cumulative probability or probability to be dead is
                   3354:             constant (ie = 1) over time d, the difference is equal to
                   3355:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3356:             s1 at precedent wave, to be dead a month before current
                   3357:             wave is equal to probability, being at state s1 at
                   3358:             precedent wave, to be dead at mont of the current
                   3359:             wave. Then the observed probability (that this person died)
                   3360:             is null according to current estimated parameter. In fact,
                   3361:             it should be very low but not zero otherwise the log go to
                   3362:             infinity.
                   3363:          */
1.183     brouard  3364: /* #ifdef INFINITYORIGINAL */
                   3365: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3366: /* #else */
                   3367: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3368: /*         lli=log(mytinydouble); */
                   3369: /*       else */
                   3370: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3371: /* #endif */
1.226     brouard  3372:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3373:          
1.226     brouard  3374:        } else if  ( s2==-1 ) { /* alive */
                   3375:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3376:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3377:          /*survp += out[s1][j]; */
                   3378:          lli= log(survp);
                   3379:        }
                   3380:        else if  (s2==-4) { 
                   3381:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3382:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3383:          lli= log(survp); 
                   3384:        } 
                   3385:        else if  (s2==-5) { 
                   3386:          for (j=1,survp=0. ; j<=2; j++)  
                   3387:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3388:          lli= log(survp); 
                   3389:        } 
                   3390:        else{
                   3391:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3392:          /*  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 */
                   3393:        } 
                   3394:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3395:        /*if(lli ==000.0)*/
                   3396:        /*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); */
                   3397:        ipmx +=1;
                   3398:        sw += weight[i];
                   3399:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3400:        /* if (lli < log(mytinydouble)){ */
                   3401:        /*   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); */
                   3402:        /*   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]); */
                   3403:        /* } */
                   3404:       } /* end of wave */
                   3405:     } /* end of individual */
                   3406:   }  else if(mle==2){
                   3407:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3408:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3409:       for(mi=1; mi<= wav[i]-1; mi++){
                   3410:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3411:          for (j=1;j<=nlstate+ndeath;j++){
                   3412:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3413:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3414:          }
                   3415:        for(d=0; d<=dh[mi][i]; d++){
                   3416:          newm=savm;
                   3417:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3418:          cov[2]=agexact;
                   3419:          if(nagesqr==1)
                   3420:            cov[3]= agexact*agexact;
                   3421:          for (kk=1; kk<=cptcovage;kk++) {
                   3422:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3423:          }
                   3424:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3425:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3426:          savm=oldm;
                   3427:          oldm=newm;
                   3428:        } /* end mult */
                   3429:       
                   3430:        s1=s[mw[mi][i]][i];
                   3431:        s2=s[mw[mi+1][i]][i];
                   3432:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3433:        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 */
                   3434:        ipmx +=1;
                   3435:        sw += weight[i];
                   3436:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3437:       } /* end of wave */
                   3438:     } /* end of individual */
                   3439:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3440:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3441:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3442:       for(mi=1; mi<= wav[i]-1; mi++){
                   3443:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3444:          for (j=1;j<=nlstate+ndeath;j++){
                   3445:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3446:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3447:          }
                   3448:        for(d=0; d<dh[mi][i]; d++){
                   3449:          newm=savm;
                   3450:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3451:          cov[2]=agexact;
                   3452:          if(nagesqr==1)
                   3453:            cov[3]= agexact*agexact;
                   3454:          for (kk=1; kk<=cptcovage;kk++) {
                   3455:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3456:          }
                   3457:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3458:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3459:          savm=oldm;
                   3460:          oldm=newm;
                   3461:        } /* end mult */
                   3462:       
                   3463:        s1=s[mw[mi][i]][i];
                   3464:        s2=s[mw[mi+1][i]][i];
                   3465:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3466:        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 */
                   3467:        ipmx +=1;
                   3468:        sw += weight[i];
                   3469:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3470:       } /* end of wave */
                   3471:     } /* end of individual */
                   3472:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3473:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3474:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3475:       for(mi=1; mi<= wav[i]-1; mi++){
                   3476:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3477:          for (j=1;j<=nlstate+ndeath;j++){
                   3478:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3479:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3480:          }
                   3481:        for(d=0; d<dh[mi][i]; d++){
                   3482:          newm=savm;
                   3483:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3484:          cov[2]=agexact;
                   3485:          if(nagesqr==1)
                   3486:            cov[3]= agexact*agexact;
                   3487:          for (kk=1; kk<=cptcovage;kk++) {
                   3488:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3489:          }
1.126     brouard  3490:        
1.226     brouard  3491:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3492:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3493:          savm=oldm;
                   3494:          oldm=newm;
                   3495:        } /* end mult */
                   3496:       
                   3497:        s1=s[mw[mi][i]][i];
                   3498:        s2=s[mw[mi+1][i]][i];
                   3499:        if( s2 > nlstate){ 
                   3500:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3501:        } else if  ( s2==-1 ) { /* alive */
                   3502:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3503:            survp += out[s1][j];
                   3504:          lli= log(survp);
                   3505:        }else{
                   3506:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3507:        }
                   3508:        ipmx +=1;
                   3509:        sw += weight[i];
                   3510:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3511: /*     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  3512:       } /* end of wave */
                   3513:     } /* end of individual */
                   3514:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3515:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3516:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3517:       for(mi=1; mi<= wav[i]-1; mi++){
                   3518:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3519:          for (j=1;j<=nlstate+ndeath;j++){
                   3520:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3521:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3522:          }
                   3523:        for(d=0; d<dh[mi][i]; d++){
                   3524:          newm=savm;
                   3525:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3526:          cov[2]=agexact;
                   3527:          if(nagesqr==1)
                   3528:            cov[3]= agexact*agexact;
                   3529:          for (kk=1; kk<=cptcovage;kk++) {
                   3530:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3531:          }
1.126     brouard  3532:        
1.226     brouard  3533:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3534:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3535:          savm=oldm;
                   3536:          oldm=newm;
                   3537:        } /* end mult */
                   3538:       
                   3539:        s1=s[mw[mi][i]][i];
                   3540:        s2=s[mw[mi+1][i]][i];
                   3541:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3542:        ipmx +=1;
                   3543:        sw += weight[i];
                   3544:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3545:        /*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]);*/
                   3546:       } /* end of wave */
                   3547:     } /* end of individual */
                   3548:   } /* End of if */
                   3549:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3550:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3551:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3552:   return -l;
1.126     brouard  3553: }
                   3554: 
                   3555: /*************** log-likelihood *************/
                   3556: double funcone( double *x)
                   3557: {
1.228     brouard  3558:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3559:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3560:   int ioffset=0;
1.131     brouard  3561:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3562:   double **out;
                   3563:   double lli; /* Individual log likelihood */
                   3564:   double llt;
                   3565:   int s1, s2;
1.228     brouard  3566:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3567: 
1.126     brouard  3568:   double bbh, survp;
1.187     brouard  3569:   double agexact;
1.214     brouard  3570:   double agebegin, ageend;
1.126     brouard  3571:   /*extern weight */
                   3572:   /* We are differentiating ll according to initial status */
                   3573:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3574:   /*for(i=1;i<imx;i++) 
                   3575:     printf(" %d\n",s[4][i]);
                   3576:   */
                   3577:   cov[1]=1.;
                   3578: 
                   3579:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3580:   ioffset=0;
                   3581:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3582:     /* ioffset=2+nagesqr+cptcovage; */
                   3583:     ioffset=2+nagesqr;
1.232     brouard  3584:     /* Fixed */
1.224     brouard  3585:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3586:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3587:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3588:       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)*/
                   3589: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3590: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3591: /*    cov[2+6]=covar[2][i]; V2  */
                   3592: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3593: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3594: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3595: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3596: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3597: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3598:     }
1.232     brouard  3599:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3600:     /*   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?)*\/ */
                   3601:     /* } */
1.231     brouard  3602:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3603:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3604:     /* } */
1.225     brouard  3605:     
1.233     brouard  3606: 
                   3607:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3608:     /* Wave varying (but not age varying) */
                   3609:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3610:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3611:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3612:       }
1.232     brouard  3613:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3614:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3615:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3616:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3617:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3618:       /* 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  3619:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3620:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3621:       /*       /\* 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]); *\/ */
                   3622:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3623:       /* } */
1.126     brouard  3624:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3625:        for (j=1;j<=nlstate+ndeath;j++){
                   3626:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3627:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3628:        }
1.214     brouard  3629:       
                   3630:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3631:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3632:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3633:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3634:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3635:          and mw[mi+1][i]. dh depends on stepm.*/
                   3636:        newm=savm;
1.247     brouard  3637:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3638:        cov[2]=agexact;
                   3639:        if(nagesqr==1)
                   3640:          cov[3]= agexact*agexact;
                   3641:        for (kk=1; kk<=cptcovage;kk++) {
                   3642:          if(!FixedV[Tvar[Tage[kk]]])
                   3643:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3644:          else
                   3645:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3646:        }
                   3647:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3648:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3649:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3650:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3651:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3652:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3653:        savm=oldm;
                   3654:        oldm=newm;
1.126     brouard  3655:       } /* end mult */
                   3656:       
                   3657:       s1=s[mw[mi][i]][i];
                   3658:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3659:       /* if(s2==-1){ */
                   3660:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3661:       /*       /\* exit(1); *\/ */
                   3662:       /* } */
1.126     brouard  3663:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3664:       /* bias is positive if real duration
                   3665:        * is higher than the multiple of stepm and negative otherwise.
                   3666:        */
                   3667:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3668:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3669:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3670:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3671:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3672:        lli= log(survp);
1.126     brouard  3673:       }else if (mle==1){
1.242     brouard  3674:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3675:       } else if(mle==2){
1.242     brouard  3676:        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  3677:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3678:        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  3679:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3680:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3681:       } else{  /* mle=0 back to 1 */
1.242     brouard  3682:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3683:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3684:       } /* End of if */
                   3685:       ipmx +=1;
                   3686:       sw += weight[i];
                   3687:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3688:       /*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  3689:       if(globpr){
1.246     brouard  3690:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3691:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3692:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3693:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3694:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3695:          llt +=ll[k]*gipmx/gsw;
                   3696:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3697:        }
                   3698:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3699:       }
1.232     brouard  3700:        } /* end of wave */
                   3701: } /* end of individual */
                   3702: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3703: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3704: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3705: if(globpr==0){ /* First time we count the contributions and weights */
                   3706:        gipmx=ipmx;
                   3707:        gsw=sw;
                   3708: }
                   3709: return -l;
1.126     brouard  3710: }
                   3711: 
                   3712: 
                   3713: /*************** function likelione ***********/
                   3714: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3715: {
                   3716:   /* This routine should help understanding what is done with 
                   3717:      the selection of individuals/waves and
                   3718:      to check the exact contribution to the likelihood.
                   3719:      Plotting could be done.
                   3720:    */
                   3721:   int k;
                   3722: 
                   3723:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3724:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3725:     strcat(fileresilk,fileresu);
1.126     brouard  3726:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3727:       printf("Problem with resultfile: %s\n", fileresilk);
                   3728:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3729:     }
1.214     brouard  3730:     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");
                   3731:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3732:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3733:     for(k=1; k<=nlstate; k++) 
                   3734:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3735:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3736:   }
                   3737: 
                   3738:   *fretone=(*funcone)(p);
                   3739:   if(*globpri !=0){
                   3740:     fclose(ficresilk);
1.205     brouard  3741:     if (mle ==0)
                   3742:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3743:     else if(mle >=1)
                   3744:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3745:     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  3746:     
1.208     brouard  3747:       
                   3748:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3749:       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  3750: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3751:     }
1.207     brouard  3752:     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  3753: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3754:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3755: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3756:     fflush(fichtm);
1.205     brouard  3757:   }
1.126     brouard  3758:   return;
                   3759: }
                   3760: 
                   3761: 
                   3762: /*********** Maximum Likelihood Estimation ***************/
                   3763: 
                   3764: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3765: {
1.165     brouard  3766:   int i,j, iter=0;
1.126     brouard  3767:   double **xi;
                   3768:   double fret;
                   3769:   double fretone; /* Only one call to likelihood */
                   3770:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3771: 
                   3772: #ifdef NLOPT
                   3773:   int creturn;
                   3774:   nlopt_opt opt;
                   3775:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3776:   double *lb;
                   3777:   double minf; /* the minimum objective value, upon return */
                   3778:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3779:   myfunc_data dinst, *d = &dinst;
                   3780: #endif
                   3781: 
                   3782: 
1.126     brouard  3783:   xi=matrix(1,npar,1,npar);
                   3784:   for (i=1;i<=npar;i++)
                   3785:     for (j=1;j<=npar;j++)
                   3786:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3787:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3788:   strcpy(filerespow,"POW_"); 
1.126     brouard  3789:   strcat(filerespow,fileres);
                   3790:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3791:     printf("Problem with resultfile: %s\n", filerespow);
                   3792:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3793:   }
                   3794:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3795:   for (i=1;i<=nlstate;i++)
                   3796:     for(j=1;j<=nlstate+ndeath;j++)
                   3797:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3798:   fprintf(ficrespow,"\n");
1.162     brouard  3799: #ifdef POWELL
1.126     brouard  3800:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3801: #endif
1.126     brouard  3802: 
1.162     brouard  3803: #ifdef NLOPT
                   3804: #ifdef NEWUOA
                   3805:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3806: #else
                   3807:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3808: #endif
                   3809:   lb=vector(0,npar-1);
                   3810:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3811:   nlopt_set_lower_bounds(opt, lb);
                   3812:   nlopt_set_initial_step1(opt, 0.1);
                   3813:   
                   3814:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3815:   d->function = func;
                   3816:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3817:   nlopt_set_min_objective(opt, myfunc, d);
                   3818:   nlopt_set_xtol_rel(opt, ftol);
                   3819:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3820:     printf("nlopt failed! %d\n",creturn); 
                   3821:   }
                   3822:   else {
                   3823:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3824:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3825:     iter=1; /* not equal */
                   3826:   }
                   3827:   nlopt_destroy(opt);
                   3828: #endif
1.126     brouard  3829:   free_matrix(xi,1,npar,1,npar);
                   3830:   fclose(ficrespow);
1.203     brouard  3831:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3832:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3833:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3834: 
                   3835: }
                   3836: 
                   3837: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3838: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3839: {
                   3840:   double  **a,**y,*x,pd;
1.203     brouard  3841:   /* double **hess; */
1.164     brouard  3842:   int i, j;
1.126     brouard  3843:   int *indx;
                   3844: 
                   3845:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3846:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3847:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3848:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3849:   double gompertz(double p[]);
1.203     brouard  3850:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3851: 
                   3852:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3853:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3854:   for (i=1;i<=npar;i++){
1.203     brouard  3855:     printf("%d-",i);fflush(stdout);
                   3856:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3857:    
                   3858:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3859:     
                   3860:     /*  printf(" %f ",p[i]);
                   3861:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3862:   }
                   3863:   
                   3864:   for (i=1;i<=npar;i++) {
                   3865:     for (j=1;j<=npar;j++)  {
                   3866:       if (j>i) { 
1.203     brouard  3867:        printf(".%d-%d",i,j);fflush(stdout);
                   3868:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3869:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3870:        
                   3871:        hess[j][i]=hess[i][j];    
                   3872:        /*printf(" %lf ",hess[i][j]);*/
                   3873:       }
                   3874:     }
                   3875:   }
                   3876:   printf("\n");
                   3877:   fprintf(ficlog,"\n");
                   3878: 
                   3879:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3880:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3881:   
                   3882:   a=matrix(1,npar,1,npar);
                   3883:   y=matrix(1,npar,1,npar);
                   3884:   x=vector(1,npar);
                   3885:   indx=ivector(1,npar);
                   3886:   for (i=1;i<=npar;i++)
                   3887:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3888:   ludcmp(a,npar,indx,&pd);
                   3889: 
                   3890:   for (j=1;j<=npar;j++) {
                   3891:     for (i=1;i<=npar;i++) x[i]=0;
                   3892:     x[j]=1;
                   3893:     lubksb(a,npar,indx,x);
                   3894:     for (i=1;i<=npar;i++){ 
                   3895:       matcov[i][j]=x[i];
                   3896:     }
                   3897:   }
                   3898: 
                   3899:   printf("\n#Hessian matrix#\n");
                   3900:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3901:   for (i=1;i<=npar;i++) { 
                   3902:     for (j=1;j<=npar;j++) { 
1.203     brouard  3903:       printf("%.6e ",hess[i][j]);
                   3904:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3905:     }
                   3906:     printf("\n");
                   3907:     fprintf(ficlog,"\n");
                   3908:   }
                   3909: 
1.203     brouard  3910:   /* printf("\n#Covariance matrix#\n"); */
                   3911:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3912:   /* for (i=1;i<=npar;i++) {  */
                   3913:   /*   for (j=1;j<=npar;j++) {  */
                   3914:   /*     printf("%.6e ",matcov[i][j]); */
                   3915:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3916:   /*   } */
                   3917:   /*   printf("\n"); */
                   3918:   /*   fprintf(ficlog,"\n"); */
                   3919:   /* } */
                   3920: 
1.126     brouard  3921:   /* Recompute Inverse */
1.203     brouard  3922:   /* for (i=1;i<=npar;i++) */
                   3923:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3924:   /* ludcmp(a,npar,indx,&pd); */
                   3925: 
                   3926:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3927: 
                   3928:   /* for (j=1;j<=npar;j++) { */
                   3929:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3930:   /*   x[j]=1; */
                   3931:   /*   lubksb(a,npar,indx,x); */
                   3932:   /*   for (i=1;i<=npar;i++){  */
                   3933:   /*     y[i][j]=x[i]; */
                   3934:   /*     printf("%.3e ",y[i][j]); */
                   3935:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3936:   /*   } */
                   3937:   /*   printf("\n"); */
                   3938:   /*   fprintf(ficlog,"\n"); */
                   3939:   /* } */
                   3940: 
                   3941:   /* Verifying the inverse matrix */
                   3942: #ifdef DEBUGHESS
                   3943:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3944: 
1.203     brouard  3945:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3946:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3947: 
                   3948:   for (j=1;j<=npar;j++) {
                   3949:     for (i=1;i<=npar;i++){ 
1.203     brouard  3950:       printf("%.2f ",y[i][j]);
                   3951:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3952:     }
                   3953:     printf("\n");
                   3954:     fprintf(ficlog,"\n");
                   3955:   }
1.203     brouard  3956: #endif
1.126     brouard  3957: 
                   3958:   free_matrix(a,1,npar,1,npar);
                   3959:   free_matrix(y,1,npar,1,npar);
                   3960:   free_vector(x,1,npar);
                   3961:   free_ivector(indx,1,npar);
1.203     brouard  3962:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3963: 
                   3964: 
                   3965: }
                   3966: 
                   3967: /*************** hessian matrix ****************/
                   3968: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3969: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3970:   int i;
                   3971:   int l=1, lmax=20;
1.203     brouard  3972:   double k1,k2, res, fx;
1.132     brouard  3973:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3974:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3975:   int k=0,kmax=10;
                   3976:   double l1;
                   3977: 
                   3978:   fx=func(x);
                   3979:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3980:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3981:     l1=pow(10,l);
                   3982:     delts=delt;
                   3983:     for(k=1 ; k <kmax; k=k+1){
                   3984:       delt = delta*(l1*k);
                   3985:       p2[theta]=x[theta] +delt;
1.145     brouard  3986:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3987:       p2[theta]=x[theta]-delt;
                   3988:       k2=func(p2)-fx;
                   3989:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3990:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3991:       
1.203     brouard  3992: #ifdef DEBUGHESSII
1.126     brouard  3993:       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);
                   3994:       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);
                   3995: #endif
                   3996:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3997:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3998:        k=kmax;
                   3999:       }
                   4000:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4001:        k=kmax; l=lmax*10;
1.126     brouard  4002:       }
                   4003:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4004:        delts=delt;
                   4005:       }
1.203     brouard  4006:     } /* End loop k */
1.126     brouard  4007:   }
                   4008:   delti[theta]=delts;
                   4009:   return res; 
                   4010:   
                   4011: }
                   4012: 
1.203     brouard  4013: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4014: {
                   4015:   int i;
1.164     brouard  4016:   int l=1, lmax=20;
1.126     brouard  4017:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4018:   double p2[MAXPARM+1];
1.203     brouard  4019:   int k, kmax=1;
                   4020:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4021: 
                   4022:   int firstime=0;
1.203     brouard  4023:   
1.126     brouard  4024:   fx=func(x);
1.203     brouard  4025:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4026:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4027:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4028:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4029:     k1=func(p2)-fx;
                   4030:   
1.203     brouard  4031:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4032:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4033:     k2=func(p2)-fx;
                   4034:   
1.203     brouard  4035:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4036:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4037:     k3=func(p2)-fx;
                   4038:   
1.203     brouard  4039:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4040:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4041:     k4=func(p2)-fx;
1.203     brouard  4042:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4043:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4044:       firstime=1;
1.203     brouard  4045:       kmax=kmax+10;
1.208     brouard  4046:     }
                   4047:     if(kmax >=10 || firstime ==1){
1.246     brouard  4048:       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);
                   4049:       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  4050:       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);
                   4051:       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);
                   4052:     }
                   4053: #ifdef DEBUGHESSIJ
                   4054:     v1=hess[thetai][thetai];
                   4055:     v2=hess[thetaj][thetaj];
                   4056:     cv12=res;
                   4057:     /* Computing eigen value of Hessian matrix */
                   4058:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4059:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4060:     if ((lc2 <0) || (lc1 <0) ){
                   4061:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4062:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4063:       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);
                   4064:       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);
                   4065:     }
1.126     brouard  4066: #endif
                   4067:   }
                   4068:   return res;
                   4069: }
                   4070: 
1.203     brouard  4071:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4072: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4073: /* { */
                   4074: /*   int i; */
                   4075: /*   int l=1, lmax=20; */
                   4076: /*   double k1,k2,k3,k4,res,fx; */
                   4077: /*   double p2[MAXPARM+1]; */
                   4078: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4079: /*   int k=0,kmax=10; */
                   4080: /*   double l1; */
                   4081:   
                   4082: /*   fx=func(x); */
                   4083: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4084: /*     l1=pow(10,l); */
                   4085: /*     delts=delt; */
                   4086: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4087: /*       delt = delti*(l1*k); */
                   4088: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4089: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4090: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4091: /*       k1=func(p2)-fx; */
                   4092:       
                   4093: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4094: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4095: /*       k2=func(p2)-fx; */
                   4096:       
                   4097: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4098: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4099: /*       k3=func(p2)-fx; */
                   4100:       
                   4101: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4102: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4103: /*       k4=func(p2)-fx; */
                   4104: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4105: /* #ifdef DEBUGHESSIJ */
                   4106: /*       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); */
                   4107: /*       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); */
                   4108: /* #endif */
                   4109: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4110: /*     k=kmax; */
                   4111: /*       } */
                   4112: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4113: /*     k=kmax; l=lmax*10; */
                   4114: /*       } */
                   4115: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4116: /*     delts=delt; */
                   4117: /*       } */
                   4118: /*     } /\* End loop k *\/ */
                   4119: /*   } */
                   4120: /*   delti[theta]=delts; */
                   4121: /*   return res;  */
                   4122: /* } */
                   4123: 
                   4124: 
1.126     brouard  4125: /************** Inverse of matrix **************/
                   4126: void ludcmp(double **a, int n, int *indx, double *d) 
                   4127: { 
                   4128:   int i,imax,j,k; 
                   4129:   double big,dum,sum,temp; 
                   4130:   double *vv; 
                   4131:  
                   4132:   vv=vector(1,n); 
                   4133:   *d=1.0; 
                   4134:   for (i=1;i<=n;i++) { 
                   4135:     big=0.0; 
                   4136:     for (j=1;j<=n;j++) 
                   4137:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4138:     if (big == 0.0){
                   4139:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4140:       for (j=1;j<=n;j++) {
                   4141:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4142:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4143:       }
                   4144:       fflush(ficlog);
                   4145:       fclose(ficlog);
                   4146:       nrerror("Singular matrix in routine ludcmp"); 
                   4147:     }
1.126     brouard  4148:     vv[i]=1.0/big; 
                   4149:   } 
                   4150:   for (j=1;j<=n;j++) { 
                   4151:     for (i=1;i<j;i++) { 
                   4152:       sum=a[i][j]; 
                   4153:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4154:       a[i][j]=sum; 
                   4155:     } 
                   4156:     big=0.0; 
                   4157:     for (i=j;i<=n;i++) { 
                   4158:       sum=a[i][j]; 
                   4159:       for (k=1;k<j;k++) 
                   4160:        sum -= a[i][k]*a[k][j]; 
                   4161:       a[i][j]=sum; 
                   4162:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4163:        big=dum; 
                   4164:        imax=i; 
                   4165:       } 
                   4166:     } 
                   4167:     if (j != imax) { 
                   4168:       for (k=1;k<=n;k++) { 
                   4169:        dum=a[imax][k]; 
                   4170:        a[imax][k]=a[j][k]; 
                   4171:        a[j][k]=dum; 
                   4172:       } 
                   4173:       *d = -(*d); 
                   4174:       vv[imax]=vv[j]; 
                   4175:     } 
                   4176:     indx[j]=imax; 
                   4177:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4178:     if (j != n) { 
                   4179:       dum=1.0/(a[j][j]); 
                   4180:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4181:     } 
                   4182:   } 
                   4183:   free_vector(vv,1,n);  /* Doesn't work */
                   4184: ;
                   4185: } 
                   4186: 
                   4187: void lubksb(double **a, int n, int *indx, double b[]) 
                   4188: { 
                   4189:   int i,ii=0,ip,j; 
                   4190:   double sum; 
                   4191:  
                   4192:   for (i=1;i<=n;i++) { 
                   4193:     ip=indx[i]; 
                   4194:     sum=b[ip]; 
                   4195:     b[ip]=b[i]; 
                   4196:     if (ii) 
                   4197:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4198:     else if (sum) ii=i; 
                   4199:     b[i]=sum; 
                   4200:   } 
                   4201:   for (i=n;i>=1;i--) { 
                   4202:     sum=b[i]; 
                   4203:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4204:     b[i]=sum/a[i][i]; 
                   4205:   } 
                   4206: } 
                   4207: 
                   4208: void pstamp(FILE *fichier)
                   4209: {
1.196     brouard  4210:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4211: }
                   4212: 
1.253     brouard  4213: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   4214: 
                   4215:   /* y=a+bx regression */
                   4216:   double   sumx = 0.0;                        /* sum of x                      */
                   4217:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   4218:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   4219:   double   sumy = 0.0;                        /* sum of y                      */
                   4220:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   4221:   double   sume2; /* sum of square or residuals */
                   4222:   double yhat;
                   4223:   
                   4224:   double denom=0;
                   4225:   int i;
                   4226:   int ne=*no;
                   4227:   
                   4228:   for ( i=ifi, ne=0;i<=ila;i++) {
                   4229:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   4230:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   4231:       continue;
                   4232:     }
                   4233:     ne=ne+1;
                   4234:     sumx  += x[i];       
                   4235:     sumx2 += x[i]*x[i];  
                   4236:     sumxy += x[i] * y[i];
                   4237:     sumy  += y[i];      
                   4238:     sumy2 += y[i]*y[i]; 
                   4239:     denom = (ne * sumx2 - sumx*sumx);
                   4240:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
                   4241:   } 
                   4242:   
                   4243:   denom = (ne * sumx2 - sumx*sumx);
                   4244:   if (denom == 0) {
                   4245:     // vertical, slope m is infinity
                   4246:     *b = INFINITY;
                   4247:     *a = 0;
                   4248:     if (r) *r = 0;
                   4249:     return 1;
                   4250:   }
                   4251:   
                   4252:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   4253:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   4254:   if (r!=NULL) {
                   4255:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   4256:       sqrt((sumx2 - sumx*sumx/ne) *
                   4257:           (sumy2 - sumy*sumy/ne));
                   4258:   }
                   4259:   *no=ne;
                   4260:   for ( i=ifi, ne=0;i<=ila;i++) {
                   4261:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   4262:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   4263:       continue;
                   4264:     }
                   4265:     ne=ne+1;
                   4266:     yhat = y[i] - *a -*b* x[i];
                   4267:     sume2  += yhat * yhat ;       
                   4268:     
                   4269:     denom = (ne * sumx2 - sumx*sumx);
                   4270:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
                   4271:   } 
                   4272:   *sb = sqrt(sume2/(ne-2)/(sumx2 - sumx * sumx /ne));
                   4273:   *sa= *sb * sqrt(sumx2/ne);
                   4274:   
                   4275:   return 0; 
                   4276: }
                   4277: 
1.126     brouard  4278: /************ Frequencies ********************/
1.251     brouard  4279: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4280:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4281:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4282: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4283:   
1.253     brouard  4284:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0;
1.226     brouard  4285:   int iind=0, iage=0;
                   4286:   int mi; /* Effective wave */
                   4287:   int first;
                   4288:   double ***freq; /* Frequencies */
1.253     brouard  4289:   double *x, *y, a,b,r, sa, sb; /* for regression, y=b+m*x and r is the correlation coefficient */
                   4290:   int no;
1.226     brouard  4291:   double *meanq;
                   4292:   double **meanqt;
                   4293:   double *pp, **prop, *posprop, *pospropt;
                   4294:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4295:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4296:   double agebegin, ageend;
                   4297:     
                   4298:   pp=vector(1,nlstate);
1.251     brouard  4299:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4300:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4301:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4302:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4303:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4304:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4305:   strcpy(fileresp,"P_");
                   4306:   strcat(fileresp,fileresu);
                   4307:   /*strcat(fileresphtm,fileresu);*/
                   4308:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4309:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4310:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4311:     exit(0);
                   4312:   }
1.240     brouard  4313:   
1.226     brouard  4314:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4315:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4316:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4317:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4318:     fflush(ficlog);
                   4319:     exit(70); 
                   4320:   }
                   4321:   else{
                   4322:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4323: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4324: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4325:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4326:   }
1.237     brouard  4327:   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  4328:   
1.226     brouard  4329:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4330:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4331:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4332:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4333:     fflush(ficlog);
                   4334:     exit(70); 
1.240     brouard  4335:   } else{
1.226     brouard  4336:     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  4337: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4338: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4339:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4340:   }
1.240     brouard  4341:   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);
                   4342:   
1.253     brouard  4343:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4344:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4345:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4346:   j1=0;
1.126     brouard  4347:   
1.227     brouard  4348:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4349:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4350:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4351:   
                   4352:   
1.226     brouard  4353:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4354:      reference=low_education V1=0,V2=0
                   4355:      med_educ                V1=1 V2=0, 
                   4356:      high_educ               V1=0 V2=1
                   4357:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4358:   */
1.249     brouard  4359:   dateintsum=0;
                   4360:   k2cpt=0;
                   4361: 
1.253     brouard  4362:   if(cptcoveff == 0 )
                   4363:     nl=1;  /* Constant model only */
                   4364:   else
                   4365:     nl=2;
                   4366:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4367:     if(nj==1)
                   4368:       j=0;  /* First pass for the constant */
                   4369:     else
                   4370:       j=cptcoveff; /* Other passes for the covariate values */
1.251     brouard  4371:     first=1;
                   4372:     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 */
                   4373:       posproptt=0.;
                   4374:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4375:        scanf("%d", i);*/
                   4376:       for (i=-5; i<=nlstate+ndeath; i++)  
                   4377:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   4378:          for(m=iagemin; m <= iagemax+3; m++)
                   4379:            freq[i][jk][m]=0;
                   4380:       
                   4381:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4382:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4383:          prop[i][m]=0;
                   4384:        posprop[i]=0;
                   4385:        pospropt[i]=0;
                   4386:       }
                   4387:       /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4388:       /*   meanq[z1]+=0.; */
                   4389:       /*   for(m=1;m<=lastpass;m++){ */
                   4390:       /*       meanqt[m][z1]=0.; */
                   4391:       /*   } */
                   4392:       /* } */
                   4393:       
                   4394:       /* dateintsum=0; */
                   4395:       /* k2cpt=0; */
                   4396:       
                   4397:       /* For that combination of covariate j1, we count and print the frequencies in one pass */
                   4398:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4399:        bool=1;
                   4400:        if(j !=0){
                   4401:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4402:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4403:              /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4404:              /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4405:              /* } */
                   4406:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4407:                /* if(Tvaraff[z1] ==-20){ */
                   4408:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4409:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4410:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4411:                /* }else  */
                   4412:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
                   4413:                  /* Tests if this individual iind responded to combination j1 (V4=1 V3=0) */
                   4414:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4415:                  /* 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", 
                   4416:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4417:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4418:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4419:                } /* Onlyf fixed */
                   4420:              } /* end z1 */
                   4421:            } /* cptcovn > 0 */
                   4422:          } /* end any */
                   4423:        }/* end j==0 */
                   4424:        if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
                   4425:          /* for(m=firstpass; m<=lastpass; m++){ */
                   4426:          for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4427:            m=mw[mi][iind];
                   4428:            if(j!=0){
                   4429:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4430:                for (z1=1; z1<=cptcoveff; z1++) {
                   4431:                  if( Fixed[Tmodelind[z1]]==1){
                   4432:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4433:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4434:                                                                                      value is -1, we don't select. It differs from the 
                   4435:                                                                                      constant and age model which counts them. */
                   4436:                      bool=0; /* not selected */
                   4437:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4438:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4439:                      bool=0;
                   4440:                    }
                   4441:                  }
                   4442:                }
                   4443:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4444:            } /* end j==0 */
                   4445:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4446:            if(bool==1){
                   4447:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4448:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4449:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4450:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4451:              if(m >=firstpass && m <=lastpass){
                   4452:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4453:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4454:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4455:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4456:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4457:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4458:                if (m<lastpass) {
                   4459:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4460:                  /*   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]); */
                   4461:                  if(s[m][iind]==-1)
                   4462:                    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.));
                   4463:                  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4464:                  /* if((int)agev[m][iind] == 55) */
                   4465:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4466:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4467:                  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 */
1.234     brouard  4468:                }
1.251     brouard  4469:              } /* end if between passes */  
                   4470:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4471:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4472:                k2cpt++;
                   4473:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4474:              }
1.251     brouard  4475:            }else{
                   4476:              bool=1;
                   4477:            }/* end bool 2 */
                   4478:          } /* end m */
                   4479:        } /* end bool */
                   4480:       } /* end iind = 1 to imx */
                   4481:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4482:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4483:       
                   4484:       
                   4485:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4486:       pstamp(ficresp);
                   4487:       if  (cptcoveff>0 && j!=0){
                   4488:        printf( "\n#********** Variable "); 
                   4489:        fprintf(ficresp, "\n#********** Variable "); 
                   4490:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4491:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4492:        fprintf(ficlog, "\n#********** Variable "); 
                   4493:        for (z1=1; z1<=cptcoveff; z1++){
                   4494:          if(!FixedV[Tvaraff[z1]]){
                   4495:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4496:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4497:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4498:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4499:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4500:          }else{
1.251     brouard  4501:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4502:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4503:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4504:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4505:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4506:          }
                   4507:        }
                   4508:        printf( "**********\n#");
                   4509:        fprintf(ficresp, "**********\n#");
                   4510:        fprintf(ficresphtm, "**********</h3>\n");
                   4511:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4512:        fprintf(ficlog, "**********\n");
                   4513:       }
                   4514:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4515:       for(i=1; i<=nlstate;i++) {
                   4516:        fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
                   4517:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4518:       }
                   4519:       fprintf(ficresp, "\n");
                   4520:       fprintf(ficresphtm, "\n");
                   4521:       
                   4522:       /* Header of frequency table by age */
                   4523:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4524:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   4525:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4526:        for(m=-1; m <=nlstate+ndeath; m++){
                   4527:          if(jk!=0 && m!=0)
                   4528:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.240     brouard  4529:        }
1.226     brouard  4530:       }
1.251     brouard  4531:       fprintf(ficresphtmfr, "\n");
                   4532:     
                   4533:       /* For each age */
                   4534:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4535:        fprintf(ficresphtm,"<tr>");
                   4536:        if(iage==iagemax+1){
                   4537:          fprintf(ficlog,"1");
                   4538:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4539:        }else if(iage==iagemax+2){
                   4540:          fprintf(ficlog,"0");
                   4541:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4542:        }else if(iage==iagemax+3){
                   4543:          fprintf(ficlog,"Total");
                   4544:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4545:        }else{
1.240     brouard  4546:          if(first==1){
1.251     brouard  4547:            first=0;
                   4548:            printf("See log file for details...\n");
                   4549:          }
                   4550:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4551:          fprintf(ficlog,"Age %d", iage);
                   4552:        }
                   4553:        for(jk=1; jk <=nlstate ; jk++){
                   4554:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4555:            pp[jk] += freq[jk][m][iage]; 
                   4556:        }
                   4557:        for(jk=1; jk <=nlstate ; jk++){
                   4558:          for(m=-1, pos=0; m <=0 ; m++)
                   4559:            pos += freq[jk][m][iage];
                   4560:          if(pp[jk]>=1.e-10){
                   4561:            if(first==1){
                   4562:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4563:            }
                   4564:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4565:          }else{
                   4566:            if(first==1)
                   4567:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4568:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
1.240     brouard  4569:          }
                   4570:        }
                   4571:       
1.251     brouard  4572:        for(jk=1; jk <=nlstate ; jk++){ 
                   4573:          /* posprop[jk]=0; */
                   4574:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4575:            pp[jk] += freq[jk][m][iage];
                   4576:        }       /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
                   4577:       
                   4578:        for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
                   4579:          pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4580:          posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4581:                                            from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4582:          pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
1.240     brouard  4583:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4584:        }
1.251     brouard  4585:        for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4586:          if(pos>=1.e-5){
1.251     brouard  4587:            if(first==1)
                   4588:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4589:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4590:          }else{
                   4591:            if(first==1)
                   4592:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4593:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4594:          }
                   4595:          if( iage <= iagemax){
                   4596:            if(pos>=1.e-5){
                   4597:              fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4598:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4599:              /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4600:              /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4601:            }
                   4602:            else{
                   4603:              fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4604:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4605:            }
1.240     brouard  4606:          }
1.251     brouard  4607:          pospropt[jk] +=posprop[jk];
                   4608:        } /* end loop jk */
                   4609:        /* pospropt=0.; */
                   4610:        for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4611:          for(m=-1; m <=nlstate+ndeath; m++){
                   4612:            if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4613:              if(first==1){
                   4614:                printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4615:              }
1.253     brouard  4616:              /* printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]); */
1.251     brouard  4617:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4618:            }
                   4619:            if(jk!=0 && m!=0)
                   4620:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
1.240     brouard  4621:          }
1.251     brouard  4622:        } /* end loop jk */
                   4623:        posproptt=0.; 
                   4624:        for(jk=1; jk <=nlstate; jk++){
                   4625:          posproptt += pospropt[jk];
                   4626:        }
                   4627:        fprintf(ficresphtmfr,"</tr>\n ");
                   4628:        if(iage <= iagemax){
                   4629:          fprintf(ficresp,"\n");
                   4630:          fprintf(ficresphtm,"</tr>\n");
1.240     brouard  4631:        }
1.251     brouard  4632:        if(first==1)
                   4633:          printf("Others in log...\n");
                   4634:        fprintf(ficlog,"\n");
                   4635:       } /* end loop age iage */
                   4636:       fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4637:       for(jk=1; jk <=nlstate ; jk++){
                   4638:        if(posproptt < 1.e-5){
                   4639:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt); 
                   4640:        }else{
                   4641:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);  
1.240     brouard  4642:        }
1.226     brouard  4643:       }
1.251     brouard  4644:       fprintf(ficresphtm,"</tr>\n");
                   4645:       fprintf(ficresphtm,"</table>\n");
                   4646:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4647:       if(posproptt < 1.e-5){
1.251     brouard  4648:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4649:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4650:        fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4651:        invalidvarcomb[j1]=1;
1.226     brouard  4652:       }else{
1.251     brouard  4653:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4654:        invalidvarcomb[j1]=0;
1.226     brouard  4655:       }
1.251     brouard  4656:       fprintf(ficresphtmfr,"</table>\n");
                   4657:       fprintf(ficlog,"\n");
                   4658:       if(j!=0){
                   4659:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
                   4660:        for(i=1,jk=1; i <=nlstate; i++){
                   4661:          for(k=1; k <=(nlstate+ndeath); k++){
                   4662:            if (k != i) {
                   4663:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting jk */
1.253     brouard  4664:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4665:                  if(j1==1){ /* All dummy covariates to zero */
                   4666:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4667:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4668:                    printf("%d%d ",i,k);
                   4669:                    fprintf(ficlog,"%d%d ",i,k);
                   4670:                    printf("%12.7f ln(%.0f/%.0f)= %f, OR=%f sd=%f \n",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]),freq[i][k][iagemax+3]/freq[i][i][iagemax+3], sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]));
                   4671:                    fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f \n",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   4672:                    pstart[jk]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4673:                  }
1.253     brouard  4674:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4675:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4676:                    x[iage]= (double)iage;
                   4677:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
                   4678:                    /* printf("i=%d, k=%d, jk=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,jk,j1,jj, iage, y[iage]); */
                   4679:                  }
                   4680:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
                   4681:                  pstart[jk]=b;
                   4682:                  pstart[jk-1]=a;
1.252     brouard  4683:                }else if( j1!=1 && (j1==2 || (log(j1-1.)/log(2.)-(int)(log(j1-1.)/log(2.))) <0.010) && ( TvarsDind[(int)(log(j1-1.)/log(2.))+1]+2+nagesqr == jj)  && Dummy[jj-2-nagesqr]==0){ /* We want only if the position, jj, in model corresponds to unique covariate equal to 1 in j1 combination */ 
                   4684:                  printf("j1=%d, jj=%d, (int)(log(j1-1.)/log(2.))+1=%d, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(int)(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
                   4685:                  printf("j1=%d, jj=%d, (log(j1-1.)/log(2.))+1=%f, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
1.251     brouard  4686:                  pstart[jk]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
1.252     brouard  4687:                  printf("%d%d ",i,k);
                   4688:                  fprintf(ficlog,"%d%d ",i,k);
1.251     brouard  4689:                  printf("jk=%d,i=%d,k=%d,p[%d]=%12.7f ln((%.0f/%.0f)/(%.0f/%.0f))= %f, OR=%f sd=%f \n",jk,i,k,jk,p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3],freq[i][k][iagemax+4],freq[i][i][iagemax+4], log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4])),(freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]), sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]+1/freq[i][k][iagemax+4]+1/freq[i][i][iagemax+4]));
                   4690:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4691:                  ;
                   4692:                }
                   4693:                /* printf("%12.7f )", param[i][jj][k]); */
                   4694:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   4695:                jk++; 
                   4696:              } /* end jj */
                   4697:            } /* end k!= i */
                   4698:          } /* end k */
                   4699:        } /* end i, jk */
                   4700:       } /* end j !=0 */
                   4701:     } /* end selected combination of covariate j1 */
                   4702:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4703:       printf("#Freqsummary: Starting values for the constants:\n");
                   4704:       fprintf(ficlog,"\n");
                   4705:       for(i=1,jk=1; i <=nlstate; i++){
                   4706:        for(k=1; k <=(nlstate+ndeath); k++){
                   4707:          if (k != i) {
                   4708:            printf("%d%d ",i,k);
                   4709:            fprintf(ficlog,"%d%d ",i,k);
                   4710:            for(jj=1; jj <=ncovmodel; jj++){
1.253     brouard  4711:              pstart[jk]=p[jk]; /* Setting pstart to p values by default */
                   4712:              if(jj==1){ /* Age has to be done */
                   4713:                pstart[jk]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4714:                printf("%12.7f ln(%.0f/%.0f)= %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]));
                   4715:                fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %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]));
                   4716:              }
                   4717:              /* printf("%12.7f )", param[i][jj][k]); */
                   4718:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   4719:              jk++; 
1.250     brouard  4720:            }
1.251     brouard  4721:            printf("\n");
                   4722:            fprintf(ficlog,"\n");
1.250     brouard  4723:          }
                   4724:        }
                   4725:       }
1.251     brouard  4726:       printf("#Freqsummary\n");
                   4727:       fprintf(ficlog,"\n");
                   4728:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4729:        for(m=-1; m <=nlstate+ndeath; m++){
                   4730:          /* param[i]|j][k]= freq[jk][m][iagemax+3] */
1.250     brouard  4731:          printf(" %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]);
                   4732:          fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]);
1.251     brouard  4733:          /* if(freq[jk][m][iage] !=0 ) { /\* minimizing output *\/ */
                   4734:          /*   printf(" %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]); */
                   4735:          /*   fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]); */
                   4736:          /* } */
                   4737:        }
                   4738:       } /* end loop jk */
                   4739:       
                   4740:       printf("\n");
                   4741:       fprintf(ficlog,"\n");
                   4742:     } /* end j=0 */
1.249     brouard  4743:   } /* end j */
1.252     brouard  4744: 
1.253     brouard  4745:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  4746:     for(i=1, jk=1; i <=nlstate; i++){
                   4747:       for(j=1; j <=nlstate+ndeath; j++){
                   4748:        if(j!=i){
                   4749:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4750:          printf("%1d%1d",i,j);
                   4751:          fprintf(ficparo,"%1d%1d",i,j);
                   4752:          for(k=1; k<=ncovmodel;k++){
                   4753:            /*    printf(" %lf",param[i][j][k]); */
                   4754:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   4755:            p[jk]=pstart[jk];
                   4756:            printf(" %f ",pstart[jk]);
                   4757:            fprintf(ficparo," %f ",pstart[jk]);
                   4758:            jk++;
                   4759:          }
                   4760:          printf("\n");
                   4761:          fprintf(ficparo,"\n");
                   4762:        }
                   4763:       }
                   4764:     }
                   4765:   } /* end mle=-2 */
1.226     brouard  4766:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4767:   
1.226     brouard  4768:   fclose(ficresp);
                   4769:   fclose(ficresphtm);
                   4770:   fclose(ficresphtmfr);
                   4771:   free_vector(meanq,1,nqfveff);
                   4772:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  4773:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   4774:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  4775:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4776:   free_vector(pospropt,1,nlstate);
                   4777:   free_vector(posprop,1,nlstate);
1.251     brouard  4778:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4779:   free_vector(pp,1,nlstate);
                   4780:   /* End of freqsummary */
                   4781: }
1.126     brouard  4782: 
                   4783: /************ Prevalence ********************/
1.227     brouard  4784: 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)
                   4785: {  
                   4786:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4787:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4788:      We still use firstpass and lastpass as another selection.
                   4789:   */
1.126     brouard  4790:  
1.227     brouard  4791:   int i, m, jk, j1, bool, z1,j, iv;
                   4792:   int mi; /* Effective wave */
                   4793:   int iage;
                   4794:   double agebegin, ageend;
                   4795: 
                   4796:   double **prop;
                   4797:   double posprop; 
                   4798:   double  y2; /* in fractional years */
                   4799:   int iagemin, iagemax;
                   4800:   int first; /** to stop verbosity which is redirected to log file */
                   4801: 
                   4802:   iagemin= (int) agemin;
                   4803:   iagemax= (int) agemax;
                   4804:   /*pp=vector(1,nlstate);*/
1.251     brouard  4805:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  4806:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4807:   j1=0;
1.222     brouard  4808:   
1.227     brouard  4809:   /*j=cptcoveff;*/
                   4810:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4811:   
1.227     brouard  4812:   first=1;
                   4813:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4814:     for (i=1; i<=nlstate; i++)  
1.251     brouard  4815:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  4816:        prop[i][iage]=0.0;
                   4817:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4818:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4819:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4820:     
                   4821:     for (i=1; i<=imx; i++) { /* Each individual */
                   4822:       bool=1;
                   4823:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4824:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4825:        m=mw[mi][i];
                   4826:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4827:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4828:        for (z1=1; z1<=cptcoveff; z1++){
                   4829:          if( Fixed[Tmodelind[z1]]==1){
                   4830:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4831:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4832:              bool=0;
                   4833:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4834:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4835:              bool=0;
                   4836:            }
                   4837:        }
                   4838:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4839:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4840:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4841:          if(m >=firstpass && m <=lastpass){
                   4842:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4843:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4844:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4845:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  4846:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  4847:                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); 
                   4848:                exit(1);
                   4849:              }
                   4850:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4851:                /*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]]);*/
                   4852:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4853:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4854:              } /* end valid statuses */ 
                   4855:            } /* end selection of dates */
                   4856:          } /* end selection of waves */
                   4857:        } /* end bool */
                   4858:       } /* end wave */
                   4859:     } /* end individual */
                   4860:     for(i=iagemin; i <= iagemax+3; i++){  
                   4861:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4862:        posprop += prop[jk][i]; 
                   4863:       } 
                   4864:       
                   4865:       for(jk=1; jk <=nlstate ; jk++){      
                   4866:        if( i <=  iagemax){ 
                   4867:          if(posprop>=1.e-5){ 
                   4868:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4869:          } else{
                   4870:            if(first==1){
                   4871:              first=0;
                   4872:              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]);
                   4873:            }
                   4874:          }
                   4875:        } 
                   4876:       }/* end jk */ 
                   4877:     }/* end i */ 
1.222     brouard  4878:      /*} *//* end i1 */
1.227     brouard  4879:   } /* end j1 */
1.222     brouard  4880:   
1.227     brouard  4881:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4882:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  4883:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  4884: }  /* End of prevalence */
1.126     brouard  4885: 
                   4886: /************* Waves Concatenation ***************/
                   4887: 
                   4888: 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)
                   4889: {
                   4890:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4891:      Death is a valid wave (if date is known).
                   4892:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4893:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4894:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4895:   */
1.126     brouard  4896: 
1.224     brouard  4897:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4898:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4899:      double sum=0., jmean=0.;*/
1.224     brouard  4900:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4901:   int j, k=0,jk, ju, jl;
                   4902:   double sum=0.;
                   4903:   first=0;
1.214     brouard  4904:   firstwo=0;
1.217     brouard  4905:   firsthree=0;
1.218     brouard  4906:   firstfour=0;
1.164     brouard  4907:   jmin=100000;
1.126     brouard  4908:   jmax=-1;
                   4909:   jmean=0.;
1.224     brouard  4910: 
                   4911: /* Treating live states */
1.214     brouard  4912:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4913:     mi=0;  /* First valid wave */
1.227     brouard  4914:     mli=0; /* Last valid wave */
1.126     brouard  4915:     m=firstpass;
1.214     brouard  4916:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4917:       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 */
                   4918:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4919:       }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 */
                   4920:        mw[++mi][i]=m;
                   4921:        mli=m;
1.224     brouard  4922:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4923:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4924:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4925:       }
1.227     brouard  4926:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4927: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4928:        break;
1.224     brouard  4929: #else
1.227     brouard  4930:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4931:          if(firsthree == 0){
                   4932:            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);
                   4933:            firsthree=1;
                   4934:          }
                   4935:          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);
                   4936:          mw[++mi][i]=m;
                   4937:          mli=m;
                   4938:        }
                   4939:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4940:          nbwarn++;
                   4941:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4942:            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);
                   4943:            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);
                   4944:          }
                   4945:          break;
                   4946:        }
                   4947:        break;
1.224     brouard  4948: #endif
1.227     brouard  4949:       }/* End m >= lastpass */
1.126     brouard  4950:     }/* end while */
1.224     brouard  4951: 
1.227     brouard  4952:     /* 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  4953:     /* After last pass */
1.224     brouard  4954: /* Treating death states */
1.214     brouard  4955:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4956:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4957:       /* } */
1.126     brouard  4958:       mi++;    /* Death is another wave */
                   4959:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4960:       /* Only death is a correct wave */
1.126     brouard  4961:       mw[mi][i]=m;
1.257   ! brouard  4962:     } /* else not in a death state */
1.224     brouard  4963: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257   ! brouard  4964:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  4965:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4966:        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 */
                   4967:          nbwarn++;
                   4968:          if(firstfiv==0){
                   4969:            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 );
                   4970:            firstfiv=1;
                   4971:          }else{
                   4972:            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 );
                   4973:          }
                   4974:        }else{ /* Death occured afer last wave potential bias */
                   4975:          nberr++;
                   4976:          if(firstwo==0){
1.257   ! brouard  4977:            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. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). See documentation\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.227     brouard  4978:            firstwo=1;
                   4979:          }
1.257   ! brouard  4980:          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. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.227     brouard  4981:        }
1.257   ! brouard  4982:       }else{ /* if date of interview is unknown */
1.227     brouard  4983:        /* death is known but not confirmed by death status at any wave */
                   4984:        if(firstfour==0){
                   4985:          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 );
                   4986:          firstfour=1;
                   4987:        }
                   4988:        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  4989:       }
1.224     brouard  4990:     } /* end if date of death is known */
                   4991: #endif
                   4992:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4993:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4994:     if(mi==0){
                   4995:       nbwarn++;
                   4996:       if(first==0){
1.227     brouard  4997:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4998:        first=1;
1.126     brouard  4999:       }
                   5000:       if(first==1){
1.227     brouard  5001:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5002:       }
                   5003:     } /* end mi==0 */
                   5004:   } /* End individuals */
1.214     brouard  5005:   /* wav and mw are no more changed */
1.223     brouard  5006:        
1.214     brouard  5007:   
1.126     brouard  5008:   for(i=1; i<=imx; i++){
                   5009:     for(mi=1; mi<wav[i];mi++){
                   5010:       if (stepm <=0)
1.227     brouard  5011:        dh[mi][i]=1;
1.126     brouard  5012:       else{
1.227     brouard  5013:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   5014:          if (agedc[i] < 2*AGESUP) {
                   5015:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5016:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5017:            else if(j<0){
                   5018:              nberr++;
                   5019:              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]);
                   5020:              j=1; /* Temporary Dangerous patch */
                   5021:              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);
                   5022:              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]);
                   5023:              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);
                   5024:            }
                   5025:            k=k+1;
                   5026:            if (j >= jmax){
                   5027:              jmax=j;
                   5028:              ijmax=i;
                   5029:            }
                   5030:            if (j <= jmin){
                   5031:              jmin=j;
                   5032:              ijmin=i;
                   5033:            }
                   5034:            sum=sum+j;
                   5035:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5036:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5037:          }
                   5038:        }
                   5039:        else{
                   5040:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5041: /*       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  5042:                                        
1.227     brouard  5043:          k=k+1;
                   5044:          if (j >= jmax) {
                   5045:            jmax=j;
                   5046:            ijmax=i;
                   5047:          }
                   5048:          else if (j <= jmin){
                   5049:            jmin=j;
                   5050:            ijmin=i;
                   5051:          }
                   5052:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5053:          /*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]);*/
                   5054:          if(j<0){
                   5055:            nberr++;
                   5056:            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]);
                   5057:            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]);
                   5058:          }
                   5059:          sum=sum+j;
                   5060:        }
                   5061:        jk= j/stepm;
                   5062:        jl= j -jk*stepm;
                   5063:        ju= j -(jk+1)*stepm;
                   5064:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5065:          if(jl==0){
                   5066:            dh[mi][i]=jk;
                   5067:            bh[mi][i]=0;
                   5068:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5069:                  * to avoid the price of an extra matrix product in likelihood */
                   5070:            dh[mi][i]=jk+1;
                   5071:            bh[mi][i]=ju;
                   5072:          }
                   5073:        }else{
                   5074:          if(jl <= -ju){
                   5075:            dh[mi][i]=jk;
                   5076:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5077:                                 * is higher than the multiple of stepm and negative otherwise.
                   5078:                                 */
                   5079:          }
                   5080:          else{
                   5081:            dh[mi][i]=jk+1;
                   5082:            bh[mi][i]=ju;
                   5083:          }
                   5084:          if(dh[mi][i]==0){
                   5085:            dh[mi][i]=1; /* At least one step */
                   5086:            bh[mi][i]=ju; /* At least one step */
                   5087:            /*  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);*/
                   5088:          }
                   5089:        } /* end if mle */
1.126     brouard  5090:       }
                   5091:     } /* end wave */
                   5092:   }
                   5093:   jmean=sum/k;
                   5094:   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  5095:   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  5096: }
1.126     brouard  5097: 
                   5098: /*********** Tricode ****************************/
1.220     brouard  5099:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5100:  {
                   5101:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5102:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5103:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5104:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5105:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5106:     */
1.130     brouard  5107: 
1.242     brouard  5108:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5109:    int modmaxcovj=0; /* Modality max of covariates j */
                   5110:    int cptcode=0; /* Modality max of covariates j */
                   5111:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5112: 
                   5113: 
1.242     brouard  5114:    /* cptcoveff=0;  */
                   5115:    /* *cptcov=0; */
1.126     brouard  5116:  
1.242     brouard  5117:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  5118: 
1.242     brouard  5119:    /* Loop on covariates without age and products and no quantitative variable */
                   5120:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
                   5121:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5122:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5123:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5124:        switch(Fixed[k]) {
                   5125:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5126:         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*/
                   5127:           ij=(int)(covar[Tvar[k]][i]);
                   5128:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5129:            * If product of Vn*Vm, still boolean *:
                   5130:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5131:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5132:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5133:              modality of the nth covariate of individual i. */
                   5134:           if (ij > modmaxcovj)
                   5135:             modmaxcovj=ij; 
                   5136:           else if (ij < modmincovj) 
                   5137:             modmincovj=ij; 
                   5138:           if ((ij < -1) && (ij > NCOVMAX)){
                   5139:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5140:             exit(1);
                   5141:           }else
                   5142:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5143:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5144:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5145:           /* getting the maximum value of the modality of the covariate
                   5146:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5147:              female ies 1, then modmaxcovj=1.
                   5148:           */
                   5149:         } /* end for loop on individuals i */
                   5150:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5151:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5152:         cptcode=modmaxcovj;
                   5153:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5154:         /*for (i=0; i<=cptcode; i++) {*/
                   5155:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5156:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5157:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5158:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5159:             if( j != -1){
                   5160:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5161:                                  covariate for which somebody answered excluding 
                   5162:                                  undefined. Usually 2: 0 and 1. */
                   5163:             }
                   5164:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5165:                                     covariate for which somebody answered including 
                   5166:                                     undefined. Usually 3: -1, 0 and 1. */
                   5167:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5168:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5169:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5170:                        
1.242     brouard  5171:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5172:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5173:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5174:         /* modmincovj=3; modmaxcovj = 7; */
                   5175:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5176:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5177:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5178:         /* nbcode[Tvar[j]][ij]=k; */
                   5179:         /* nbcode[Tvar[j]][1]=0; */
                   5180:         /* nbcode[Tvar[j]][2]=1; */
                   5181:         /* nbcode[Tvar[j]][3]=2; */
                   5182:         /* To be continued (not working yet). */
                   5183:         ij=0; /* ij is similar to i but can jump over null modalities */
                   5184:         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*/
                   5185:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5186:             break;
                   5187:           }
                   5188:           ij++;
                   5189:           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*/
                   5190:           cptcode = ij; /* New max modality for covar j */
                   5191:         } /* end of loop on modality i=-1 to 1 or more */
                   5192:         break;
                   5193:        case 1: /* Testing on varying covariate, could be simple and
                   5194:                * should look at waves or product of fixed *
                   5195:                * varying. No time to test -1, assuming 0 and 1 only */
                   5196:         ij=0;
                   5197:         for(i=0; i<=1;i++){
                   5198:           nbcode[Tvar[k]][++ij]=i;
                   5199:         }
                   5200:         break;
                   5201:        default:
                   5202:         break;
                   5203:        } /* end switch */
                   5204:      } /* end dummy test */
                   5205:     
                   5206:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   5207:      /*        /\*recode from 0 *\/ */
                   5208:      /*                                     k is a modality. If we have model=V1+V1*sex  */
                   5209:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   5210:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   5211:      /*        } */
                   5212:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   5213:      /*        if (ij > ncodemax[j]) { */
                   5214:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   5215:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   5216:      /*          break; */
                   5217:      /*        } */
                   5218:      /*   }  /\* end of loop on modality k *\/ */
                   5219:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   5220:   
                   5221:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5222:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5223:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5224:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5225:      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 */ 
                   5226:      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 */
                   5227:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5228:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5229:   
                   5230:    ij=0;
                   5231:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5232:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5233:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5234:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5235:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5236:        /* If product not in single variable we don't print results */
                   5237:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5238:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5239:        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*/
                   5240:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5241:        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 */
                   5242:        if(Fixed[k]!=0)
                   5243:         anyvaryingduminmodel=1;
                   5244:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5245:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5246:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5247:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5248:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5249:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5250:      } 
                   5251:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5252:    /* ij--; */
                   5253:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5254:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5255:                * because they can be excluded from the model and real
                   5256:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5257:    for(j=ij+1; j<= cptcovt; j++){
                   5258:      Tvaraff[j]=0;
                   5259:      Tmodelind[j]=0;
                   5260:    }
                   5261:    for(j=ntveff+1; j<= cptcovt; j++){
                   5262:      TmodelInvind[j]=0;
                   5263:    }
                   5264:    /* To be sorted */
                   5265:    ;
                   5266:  }
1.126     brouard  5267: 
1.145     brouard  5268: 
1.126     brouard  5269: /*********** Health Expectancies ****************/
                   5270: 
1.235     brouard  5271:  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  5272: 
                   5273: {
                   5274:   /* Health expectancies, no variances */
1.164     brouard  5275:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5276:   int nhstepma, nstepma; /* Decreasing with age */
                   5277:   double age, agelim, hf;
                   5278:   double ***p3mat;
                   5279:   double eip;
                   5280: 
1.238     brouard  5281:   /* pstamp(ficreseij); */
1.126     brouard  5282:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5283:   fprintf(ficreseij,"# Age");
                   5284:   for(i=1; i<=nlstate;i++){
                   5285:     for(j=1; j<=nlstate;j++){
                   5286:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5287:     }
                   5288:     fprintf(ficreseij," e%1d. ",i);
                   5289:   }
                   5290:   fprintf(ficreseij,"\n");
                   5291: 
                   5292:   
                   5293:   if(estepm < stepm){
                   5294:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5295:   }
                   5296:   else  hstepm=estepm;   
                   5297:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5298:    * This is mainly to measure the difference between two models: for example
                   5299:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5300:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5301:    * progression in between and thus overestimating or underestimating according
                   5302:    * to the curvature of the survival function. If, for the same date, we 
                   5303:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5304:    * to compare the new estimate of Life expectancy with the same linear 
                   5305:    * hypothesis. A more precise result, taking into account a more precise
                   5306:    * curvature will be obtained if estepm is as small as stepm. */
                   5307: 
                   5308:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5309:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5310:      nhstepm is the number of hstepm from age to agelim 
                   5311:      nstepm is the number of stepm from age to agelin. 
                   5312:      Look at hpijx to understand the reason of that which relies in memory size
                   5313:      and note for a fixed period like estepm months */
                   5314:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5315:      survival function given by stepm (the optimization length). Unfortunately it
                   5316:      means that if the survival funtion is printed only each two years of age and if
                   5317:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5318:      results. So we changed our mind and took the option of the best precision.
                   5319:   */
                   5320:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5321: 
                   5322:   agelim=AGESUP;
                   5323:   /* If stepm=6 months */
                   5324:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5325:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5326:     
                   5327: /* nhstepm age range expressed in number of stepm */
                   5328:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5329:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5330:   /* if (stepm >= YEARM) hstepm=1;*/
                   5331:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5332:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5333: 
                   5334:   for (age=bage; age<=fage; age ++){ 
                   5335:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5336:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5337:     /* if (stepm >= YEARM) hstepm=1;*/
                   5338:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5339: 
                   5340:     /* If stepm=6 months */
                   5341:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5342:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5343:     
1.235     brouard  5344:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5345:     
                   5346:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5347:     
                   5348:     printf("%d|",(int)age);fflush(stdout);
                   5349:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5350:     
                   5351:     /* Computing expectancies */
                   5352:     for(i=1; i<=nlstate;i++)
                   5353:       for(j=1; j<=nlstate;j++)
                   5354:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5355:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5356:          
                   5357:          /* 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]);*/
                   5358: 
                   5359:        }
                   5360: 
                   5361:     fprintf(ficreseij,"%3.0f",age );
                   5362:     for(i=1; i<=nlstate;i++){
                   5363:       eip=0;
                   5364:       for(j=1; j<=nlstate;j++){
                   5365:        eip +=eij[i][j][(int)age];
                   5366:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5367:       }
                   5368:       fprintf(ficreseij,"%9.4f", eip );
                   5369:     }
                   5370:     fprintf(ficreseij,"\n");
                   5371:     
                   5372:   }
                   5373:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5374:   printf("\n");
                   5375:   fprintf(ficlog,"\n");
                   5376:   
                   5377: }
                   5378: 
1.235     brouard  5379:  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  5380: 
                   5381: {
                   5382:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5383:      to initial status i, ei. .
1.126     brouard  5384:   */
                   5385:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5386:   int nhstepma, nstepma; /* Decreasing with age */
                   5387:   double age, agelim, hf;
                   5388:   double ***p3matp, ***p3matm, ***varhe;
                   5389:   double **dnewm,**doldm;
                   5390:   double *xp, *xm;
                   5391:   double **gp, **gm;
                   5392:   double ***gradg, ***trgradg;
                   5393:   int theta;
                   5394: 
                   5395:   double eip, vip;
                   5396: 
                   5397:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5398:   xp=vector(1,npar);
                   5399:   xm=vector(1,npar);
                   5400:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5401:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5402:   
                   5403:   pstamp(ficresstdeij);
                   5404:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5405:   fprintf(ficresstdeij,"# Age");
                   5406:   for(i=1; i<=nlstate;i++){
                   5407:     for(j=1; j<=nlstate;j++)
                   5408:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5409:     fprintf(ficresstdeij," e%1d. ",i);
                   5410:   }
                   5411:   fprintf(ficresstdeij,"\n");
                   5412: 
                   5413:   pstamp(ficrescveij);
                   5414:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5415:   fprintf(ficrescveij,"# Age");
                   5416:   for(i=1; i<=nlstate;i++)
                   5417:     for(j=1; j<=nlstate;j++){
                   5418:       cptj= (j-1)*nlstate+i;
                   5419:       for(i2=1; i2<=nlstate;i2++)
                   5420:        for(j2=1; j2<=nlstate;j2++){
                   5421:          cptj2= (j2-1)*nlstate+i2;
                   5422:          if(cptj2 <= cptj)
                   5423:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5424:        }
                   5425:     }
                   5426:   fprintf(ficrescveij,"\n");
                   5427:   
                   5428:   if(estepm < stepm){
                   5429:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5430:   }
                   5431:   else  hstepm=estepm;   
                   5432:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5433:    * This is mainly to measure the difference between two models: for example
                   5434:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5435:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5436:    * progression in between and thus overestimating or underestimating according
                   5437:    * to the curvature of the survival function. If, for the same date, we 
                   5438:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5439:    * to compare the new estimate of Life expectancy with the same linear 
                   5440:    * hypothesis. A more precise result, taking into account a more precise
                   5441:    * curvature will be obtained if estepm is as small as stepm. */
                   5442: 
                   5443:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5444:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5445:      nhstepm is the number of hstepm from age to agelim 
                   5446:      nstepm is the number of stepm from age to agelin. 
                   5447:      Look at hpijx to understand the reason of that which relies in memory size
                   5448:      and note for a fixed period like estepm months */
                   5449:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5450:      survival function given by stepm (the optimization length). Unfortunately it
                   5451:      means that if the survival funtion is printed only each two years of age and if
                   5452:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5453:      results. So we changed our mind and took the option of the best precision.
                   5454:   */
                   5455:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5456: 
                   5457:   /* If stepm=6 months */
                   5458:   /* nhstepm age range expressed in number of stepm */
                   5459:   agelim=AGESUP;
                   5460:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5461:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5462:   /* if (stepm >= YEARM) hstepm=1;*/
                   5463:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5464:   
                   5465:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5466:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5467:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5468:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5469:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5470:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5471: 
                   5472:   for (age=bage; age<=fage; age ++){ 
                   5473:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5474:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5475:     /* if (stepm >= YEARM) hstepm=1;*/
                   5476:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5477:                
1.126     brouard  5478:     /* If stepm=6 months */
                   5479:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5480:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5481:     
                   5482:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5483:                
1.126     brouard  5484:     /* Computing  Variances of health expectancies */
                   5485:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5486:        decrease memory allocation */
                   5487:     for(theta=1; theta <=npar; theta++){
                   5488:       for(i=1; i<=npar; i++){ 
1.222     brouard  5489:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5490:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5491:       }
1.235     brouard  5492:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5493:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5494:                        
1.126     brouard  5495:       for(j=1; j<= nlstate; j++){
1.222     brouard  5496:        for(i=1; i<=nlstate; i++){
                   5497:          for(h=0; h<=nhstepm-1; h++){
                   5498:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5499:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5500:          }
                   5501:        }
1.126     brouard  5502:       }
1.218     brouard  5503:                        
1.126     brouard  5504:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5505:        for(h=0; h<=nhstepm-1; h++){
                   5506:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5507:        }
1.126     brouard  5508:     }/* End theta */
                   5509:     
                   5510:     
                   5511:     for(h=0; h<=nhstepm-1; h++)
                   5512:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5513:        for(theta=1; theta <=npar; theta++)
                   5514:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5515:     
1.218     brouard  5516:                
1.222     brouard  5517:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5518:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5519:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5520:                
1.222     brouard  5521:     printf("%d|",(int)age);fflush(stdout);
                   5522:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5523:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5524:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5525:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5526:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5527:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5528:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5529:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5530:       }
                   5531:     }
1.218     brouard  5532:                
1.126     brouard  5533:     /* Computing expectancies */
1.235     brouard  5534:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5535:     for(i=1; i<=nlstate;i++)
                   5536:       for(j=1; j<=nlstate;j++)
1.222     brouard  5537:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5538:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5539:                                        
1.222     brouard  5540:          /* 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  5541:                                        
1.222     brouard  5542:        }
1.218     brouard  5543:                
1.126     brouard  5544:     fprintf(ficresstdeij,"%3.0f",age );
                   5545:     for(i=1; i<=nlstate;i++){
                   5546:       eip=0.;
                   5547:       vip=0.;
                   5548:       for(j=1; j<=nlstate;j++){
1.222     brouard  5549:        eip += eij[i][j][(int)age];
                   5550:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5551:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5552:        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  5553:       }
                   5554:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5555:     }
                   5556:     fprintf(ficresstdeij,"\n");
1.218     brouard  5557:                
1.126     brouard  5558:     fprintf(ficrescveij,"%3.0f",age );
                   5559:     for(i=1; i<=nlstate;i++)
                   5560:       for(j=1; j<=nlstate;j++){
1.222     brouard  5561:        cptj= (j-1)*nlstate+i;
                   5562:        for(i2=1; i2<=nlstate;i2++)
                   5563:          for(j2=1; j2<=nlstate;j2++){
                   5564:            cptj2= (j2-1)*nlstate+i2;
                   5565:            if(cptj2 <= cptj)
                   5566:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5567:          }
1.126     brouard  5568:       }
                   5569:     fprintf(ficrescveij,"\n");
1.218     brouard  5570:                
1.126     brouard  5571:   }
                   5572:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5573:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5574:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5575:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5576:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5577:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5578:   printf("\n");
                   5579:   fprintf(ficlog,"\n");
1.218     brouard  5580:        
1.126     brouard  5581:   free_vector(xm,1,npar);
                   5582:   free_vector(xp,1,npar);
                   5583:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5584:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5585:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5586: }
1.218     brouard  5587:  
1.126     brouard  5588: /************ Variance ******************/
1.235     brouard  5589:  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  5590:  {
                   5591:    /* Variance of health expectancies */
                   5592:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5593:    /* double **newm;*/
                   5594:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5595:   
                   5596:    /* int movingaverage(); */
                   5597:    double **dnewm,**doldm;
                   5598:    double **dnewmp,**doldmp;
                   5599:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5600:    int k;
                   5601:    double *xp;
                   5602:    double **gp, **gm;  /* for var eij */
                   5603:    double ***gradg, ***trgradg; /*for var eij */
                   5604:    double **gradgp, **trgradgp; /* for var p point j */
                   5605:    double *gpp, *gmp; /* for var p point j */
                   5606:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5607:    double ***p3mat;
                   5608:    double age,agelim, hf;
                   5609:    /* double ***mobaverage; */
                   5610:    int theta;
                   5611:    char digit[4];
                   5612:    char digitp[25];
                   5613: 
                   5614:    char fileresprobmorprev[FILENAMELENGTH];
                   5615: 
                   5616:    if(popbased==1){
                   5617:      if(mobilav!=0)
                   5618:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5619:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5620:    }
                   5621:    else 
                   5622:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5623: 
1.218     brouard  5624:    /* if (mobilav!=0) { */
                   5625:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5626:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5627:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5628:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5629:    /*   } */
                   5630:    /* } */
                   5631: 
                   5632:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5633:    sprintf(digit,"%-d",ij);
                   5634:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5635:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5636:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5637:    strcat(fileresprobmorprev,fileresu);
                   5638:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5639:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5640:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5641:    }
                   5642:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5643:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5644:    pstamp(ficresprobmorprev);
                   5645:    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  5646:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5647:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5648:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5649:    }
                   5650:    for(j=1;j<=cptcoveff;j++) 
                   5651:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5652:    fprintf(ficresprobmorprev,"\n");
                   5653: 
1.218     brouard  5654:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5655:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5656:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5657:      for(i=1; i<=nlstate;i++)
                   5658:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5659:    }  
                   5660:    fprintf(ficresprobmorprev,"\n");
                   5661:   
                   5662:    fprintf(ficgp,"\n# Routine varevsij");
                   5663:    fprintf(ficgp,"\nunset title \n");
                   5664:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5665:    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");
                   5666:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5667:    /*   } */
                   5668:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5669:    pstamp(ficresvij);
                   5670:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5671:    if(popbased==1)
                   5672:      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);
                   5673:    else
                   5674:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5675:    fprintf(ficresvij,"# Age");
                   5676:    for(i=1; i<=nlstate;i++)
                   5677:      for(j=1; j<=nlstate;j++)
                   5678:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5679:    fprintf(ficresvij,"\n");
                   5680: 
                   5681:    xp=vector(1,npar);
                   5682:    dnewm=matrix(1,nlstate,1,npar);
                   5683:    doldm=matrix(1,nlstate,1,nlstate);
                   5684:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5685:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5686: 
                   5687:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5688:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5689:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5690:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5691:   
1.218     brouard  5692:    if(estepm < stepm){
                   5693:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5694:    }
                   5695:    else  hstepm=estepm;   
                   5696:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5697:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5698:       nhstepm is the number of hstepm from age to agelim 
                   5699:       nstepm is the number of stepm from age to agelim. 
                   5700:       Look at function hpijx to understand why because of memory size limitations, 
                   5701:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5702:       survival function given by stepm (the optimization length). Unfortunately it
                   5703:       means that if the survival funtion is printed every two years of age and if
                   5704:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5705:       results. So we changed our mind and took the option of the best precision.
                   5706:    */
                   5707:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5708:    agelim = AGESUP;
                   5709:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5710:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5711:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5712:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5713:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5714:      gp=matrix(0,nhstepm,1,nlstate);
                   5715:      gm=matrix(0,nhstepm,1,nlstate);
                   5716:                
                   5717:                
                   5718:      for(theta=1; theta <=npar; theta++){
                   5719:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5720:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5721:        }
                   5722:                        
1.242     brouard  5723:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5724:                        
                   5725:        if (popbased==1) {
                   5726:         if(mobilav ==0){
                   5727:           for(i=1; i<=nlstate;i++)
                   5728:             prlim[i][i]=probs[(int)age][i][ij];
                   5729:         }else{ /* mobilav */ 
                   5730:           for(i=1; i<=nlstate;i++)
                   5731:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5732:         }
                   5733:        }
                   5734:                        
1.235     brouard  5735:        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  5736:        for(j=1; j<= nlstate; j++){
                   5737:         for(h=0; h<=nhstepm; h++){
                   5738:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5739:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5740:         }
                   5741:        }
                   5742:        /* Next for computing probability of death (h=1 means
                   5743:          computed over hstepm matrices product = hstepm*stepm months) 
                   5744:          as a weighted average of prlim.
                   5745:        */
                   5746:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5747:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5748:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5749:        }    
                   5750:        /* end probability of death */
                   5751:                        
                   5752:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5753:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5754:                        
1.242     brouard  5755:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5756:                        
                   5757:        if (popbased==1) {
                   5758:         if(mobilav ==0){
                   5759:           for(i=1; i<=nlstate;i++)
                   5760:             prlim[i][i]=probs[(int)age][i][ij];
                   5761:         }else{ /* mobilav */ 
                   5762:           for(i=1; i<=nlstate;i++)
                   5763:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5764:         }
                   5765:        }
                   5766:                        
1.235     brouard  5767:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5768:                        
                   5769:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5770:         for(h=0; h<=nhstepm; h++){
                   5771:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5772:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5773:         }
                   5774:        }
                   5775:        /* This for computing probability of death (h=1 means
                   5776:          computed over hstepm matrices product = hstepm*stepm months) 
                   5777:          as a weighted average of prlim.
                   5778:        */
                   5779:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5780:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5781:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5782:        }    
                   5783:        /* end probability of death */
                   5784:                        
                   5785:        for(j=1; j<= nlstate; j++) /* vareij */
                   5786:         for(h=0; h<=nhstepm; h++){
                   5787:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5788:         }
                   5789:                        
                   5790:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5791:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5792:        }
                   5793:                        
                   5794:      } /* End theta */
                   5795:                
                   5796:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5797:                
                   5798:      for(h=0; h<=nhstepm; h++) /* veij */
                   5799:        for(j=1; j<=nlstate;j++)
                   5800:         for(theta=1; theta <=npar; theta++)
                   5801:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5802:                
                   5803:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5804:        for(theta=1; theta <=npar; theta++)
                   5805:         trgradgp[j][theta]=gradgp[theta][j];
                   5806:                
                   5807:                
                   5808:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5809:      for(i=1;i<=nlstate;i++)
                   5810:        for(j=1;j<=nlstate;j++)
                   5811:         vareij[i][j][(int)age] =0.;
                   5812:                
                   5813:      for(h=0;h<=nhstepm;h++){
                   5814:        for(k=0;k<=nhstepm;k++){
                   5815:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5816:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5817:         for(i=1;i<=nlstate;i++)
                   5818:           for(j=1;j<=nlstate;j++)
                   5819:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5820:        }
                   5821:      }
                   5822:                
                   5823:      /* pptj */
                   5824:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5825:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5826:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5827:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5828:         varppt[j][i]=doldmp[j][i];
                   5829:      /* end ppptj */
                   5830:      /*  x centered again */
                   5831:                
1.242     brouard  5832:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5833:                
                   5834:      if (popbased==1) {
                   5835:        if(mobilav ==0){
                   5836:         for(i=1; i<=nlstate;i++)
                   5837:           prlim[i][i]=probs[(int)age][i][ij];
                   5838:        }else{ /* mobilav */ 
                   5839:         for(i=1; i<=nlstate;i++)
                   5840:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5841:        }
                   5842:      }
                   5843:                
                   5844:      /* This for computing probability of death (h=1 means
                   5845:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5846:        as a weighted average of prlim.
                   5847:      */
1.235     brouard  5848:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5849:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5850:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5851:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5852:      }    
                   5853:      /* end probability of death */
                   5854:                
                   5855:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5856:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5857:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5858:        for(i=1; i<=nlstate;i++){
                   5859:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5860:        }
                   5861:      } 
                   5862:      fprintf(ficresprobmorprev,"\n");
                   5863:                
                   5864:      fprintf(ficresvij,"%.0f ",age );
                   5865:      for(i=1; i<=nlstate;i++)
                   5866:        for(j=1; j<=nlstate;j++){
                   5867:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5868:        }
                   5869:      fprintf(ficresvij,"\n");
                   5870:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5871:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5872:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5873:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5874:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5875:    } /* End age */
                   5876:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5877:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5878:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5879:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5880:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5881:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5882:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5883:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5884:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5885:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5886:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5887:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5888:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5889:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5890:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5891:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5892:    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);
                   5893:    /*  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  5894:     */
1.218     brouard  5895:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5896:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5897: 
1.218     brouard  5898:    free_vector(xp,1,npar);
                   5899:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5900:    free_matrix(dnewm,1,nlstate,1,npar);
                   5901:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5902:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5903:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5904:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5905:    fclose(ficresprobmorprev);
                   5906:    fflush(ficgp);
                   5907:    fflush(fichtm); 
                   5908:  }  /* end varevsij */
1.126     brouard  5909: 
                   5910: /************ Variance of prevlim ******************/
1.235     brouard  5911:  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  5912: {
1.205     brouard  5913:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5914:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5915: 
1.126     brouard  5916:   double **dnewm,**doldm;
                   5917:   int i, j, nhstepm, hstepm;
                   5918:   double *xp;
                   5919:   double *gp, *gm;
                   5920:   double **gradg, **trgradg;
1.208     brouard  5921:   double **mgm, **mgp;
1.126     brouard  5922:   double age,agelim;
                   5923:   int theta;
                   5924:   
                   5925:   pstamp(ficresvpl);
                   5926:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5927:   fprintf(ficresvpl,"# Age ");
                   5928:   if(nresult >=1)
                   5929:     fprintf(ficresvpl," Result# ");
1.126     brouard  5930:   for(i=1; i<=nlstate;i++)
                   5931:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5932:   fprintf(ficresvpl,"\n");
                   5933: 
                   5934:   xp=vector(1,npar);
                   5935:   dnewm=matrix(1,nlstate,1,npar);
                   5936:   doldm=matrix(1,nlstate,1,nlstate);
                   5937:   
                   5938:   hstepm=1*YEARM; /* Every year of age */
                   5939:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5940:   agelim = AGESUP;
                   5941:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5942:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5943:     if (stepm >= YEARM) hstepm=1;
                   5944:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5945:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5946:     mgp=matrix(1,npar,1,nlstate);
                   5947:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5948:     gp=vector(1,nlstate);
                   5949:     gm=vector(1,nlstate);
                   5950: 
                   5951:     for(theta=1; theta <=npar; theta++){
                   5952:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5953:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5954:       }
1.209     brouard  5955:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5956:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5957:       else
1.235     brouard  5958:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5959:       for(i=1;i<=nlstate;i++){
1.126     brouard  5960:        gp[i] = prlim[i][i];
1.208     brouard  5961:        mgp[theta][i] = prlim[i][i];
                   5962:       }
1.126     brouard  5963:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5964:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5965:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5966:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5967:       else
1.235     brouard  5968:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5969:       for(i=1;i<=nlstate;i++){
1.126     brouard  5970:        gm[i] = prlim[i][i];
1.208     brouard  5971:        mgm[theta][i] = prlim[i][i];
                   5972:       }
1.126     brouard  5973:       for(i=1;i<=nlstate;i++)
                   5974:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5975:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5976:     } /* End theta */
                   5977: 
                   5978:     trgradg =matrix(1,nlstate,1,npar);
                   5979: 
                   5980:     for(j=1; j<=nlstate;j++)
                   5981:       for(theta=1; theta <=npar; theta++)
                   5982:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5983:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5984:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5985:     /*   for(j=1; j<=nlstate;j++){ */
                   5986:     /*         printf(" %d ",j); */
                   5987:     /*         for(theta=1; theta <=npar; theta++) */
                   5988:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5989:     /*         printf("\n "); */
                   5990:     /*   } */
                   5991:     /* } */
                   5992:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5993:     /*   printf("\n gradg %d ",(int)age); */
                   5994:     /*   for(j=1; j<=nlstate;j++){ */
                   5995:     /*         printf("%d ",j); */
                   5996:     /*         for(theta=1; theta <=npar; theta++) */
                   5997:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5998:     /*         printf("\n "); */
                   5999:     /*   } */
                   6000:     /* } */
1.126     brouard  6001: 
                   6002:     for(i=1;i<=nlstate;i++)
                   6003:       varpl[i][(int)age] =0.;
1.209     brouard  6004:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  6005:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6006:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   6007:     }else{
1.126     brouard  6008:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6009:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6010:     }
1.126     brouard  6011:     for(i=1;i<=nlstate;i++)
                   6012:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6013: 
                   6014:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6015:     if(nresult >=1)
                   6016:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  6017:     for(i=1; i<=nlstate;i++)
                   6018:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   6019:     fprintf(ficresvpl,"\n");
                   6020:     free_vector(gp,1,nlstate);
                   6021:     free_vector(gm,1,nlstate);
1.208     brouard  6022:     free_matrix(mgm,1,npar,1,nlstate);
                   6023:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6024:     free_matrix(gradg,1,npar,1,nlstate);
                   6025:     free_matrix(trgradg,1,nlstate,1,npar);
                   6026:   } /* End age */
                   6027: 
                   6028:   free_vector(xp,1,npar);
                   6029:   free_matrix(doldm,1,nlstate,1,npar);
                   6030:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   6031: 
                   6032: }
                   6033: 
                   6034: /************ Variance of one-step probabilities  ******************/
                   6035: 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  6036:  {
                   6037:    int i, j=0,  k1, l1, tj;
                   6038:    int k2, l2, j1,  z1;
                   6039:    int k=0, l;
                   6040:    int first=1, first1, first2;
                   6041:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6042:    double **dnewm,**doldm;
                   6043:    double *xp;
                   6044:    double *gp, *gm;
                   6045:    double **gradg, **trgradg;
                   6046:    double **mu;
                   6047:    double age, cov[NCOVMAX+1];
                   6048:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6049:    int theta;
                   6050:    char fileresprob[FILENAMELENGTH];
                   6051:    char fileresprobcov[FILENAMELENGTH];
                   6052:    char fileresprobcor[FILENAMELENGTH];
                   6053:    double ***varpij;
                   6054: 
                   6055:    strcpy(fileresprob,"PROB_"); 
                   6056:    strcat(fileresprob,fileres);
                   6057:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6058:      printf("Problem with resultfile: %s\n", fileresprob);
                   6059:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6060:    }
                   6061:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6062:    strcat(fileresprobcov,fileresu);
                   6063:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6064:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6065:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6066:    }
                   6067:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6068:    strcat(fileresprobcor,fileresu);
                   6069:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6070:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6071:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6072:    }
                   6073:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6074:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6075:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6076:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6077:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6078:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6079:    pstamp(ficresprob);
                   6080:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6081:    fprintf(ficresprob,"# Age");
                   6082:    pstamp(ficresprobcov);
                   6083:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6084:    fprintf(ficresprobcov,"# Age");
                   6085:    pstamp(ficresprobcor);
                   6086:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6087:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6088: 
                   6089: 
1.222     brouard  6090:    for(i=1; i<=nlstate;i++)
                   6091:      for(j=1; j<=(nlstate+ndeath);j++){
                   6092:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6093:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6094:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6095:      }  
                   6096:    /* fprintf(ficresprob,"\n");
                   6097:       fprintf(ficresprobcov,"\n");
                   6098:       fprintf(ficresprobcor,"\n");
                   6099:    */
                   6100:    xp=vector(1,npar);
                   6101:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6102:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6103:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6104:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6105:    first=1;
                   6106:    fprintf(ficgp,"\n# Routine varprob");
                   6107:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6108:    fprintf(fichtm,"\n");
                   6109: 
                   6110:    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);
                   6111:    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);
                   6112:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6113: and drawn. It helps understanding how is the covariance between two incidences.\
                   6114:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6115:    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  6116: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6117: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6118: standard deviations wide on each axis. <br>\
                   6119:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6120:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6121: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6122: 
1.222     brouard  6123:    cov[1]=1;
                   6124:    /* tj=cptcoveff; */
1.225     brouard  6125:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6126:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6127:    j1=0;
1.224     brouard  6128:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6129:      if  (cptcovn>0) {
                   6130:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6131:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6132:        fprintf(ficresprob, "**********\n#\n");
                   6133:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6134:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6135:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6136:                        
1.222     brouard  6137:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6138:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6139:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6140:                        
                   6141:                        
1.222     brouard  6142:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6143:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6144:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6145:                        
1.222     brouard  6146:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6147:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6148:        fprintf(ficresprobcor, "**********\n#");    
                   6149:        if(invalidvarcomb[j1]){
                   6150:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6151:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6152:         continue;
                   6153:        }
                   6154:      }
                   6155:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6156:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6157:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6158:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6159:      for (age=bage; age<=fage; age ++){ 
                   6160:        cov[2]=age;
                   6161:        if(nagesqr==1)
                   6162:         cov[3]= age*age;
                   6163:        for (k=1; k<=cptcovn;k++) {
                   6164:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6165:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6166:                                                                    * 1  1 1 1 1
                   6167:                                                                    * 2  2 1 1 1
                   6168:                                                                    * 3  1 2 1 1
                   6169:                                                                    */
                   6170:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6171:        }
                   6172:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6173:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6174:        for (k=1; k<=cptcovprod;k++)
                   6175:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6176:                        
                   6177:                        
1.222     brouard  6178:        for(theta=1; theta <=npar; theta++){
                   6179:         for(i=1; i<=npar; i++)
                   6180:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6181:                                
1.222     brouard  6182:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6183:                                
1.222     brouard  6184:         k=0;
                   6185:         for(i=1; i<= (nlstate); i++){
                   6186:           for(j=1; j<=(nlstate+ndeath);j++){
                   6187:             k=k+1;
                   6188:             gp[k]=pmmij[i][j];
                   6189:           }
                   6190:         }
1.220     brouard  6191:                                
1.222     brouard  6192:         for(i=1; i<=npar; i++)
                   6193:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6194:                                
1.222     brouard  6195:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6196:         k=0;
                   6197:         for(i=1; i<=(nlstate); i++){
                   6198:           for(j=1; j<=(nlstate+ndeath);j++){
                   6199:             k=k+1;
                   6200:             gm[k]=pmmij[i][j];
                   6201:           }
                   6202:         }
1.220     brouard  6203:                                
1.222     brouard  6204:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6205:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6206:        }
1.126     brouard  6207: 
1.222     brouard  6208:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6209:         for(theta=1; theta <=npar; theta++)
                   6210:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6211:                        
1.222     brouard  6212:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6213:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6214:                        
1.222     brouard  6215:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6216:                        
1.222     brouard  6217:        k=0;
                   6218:        for(i=1; i<=(nlstate); i++){
                   6219:         for(j=1; j<=(nlstate+ndeath);j++){
                   6220:           k=k+1;
                   6221:           mu[k][(int) age]=pmmij[i][j];
                   6222:         }
                   6223:        }
                   6224:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6225:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6226:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6227:                        
1.222     brouard  6228:        /*printf("\n%d ",(int)age);
                   6229:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6230:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6231:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6232:         }*/
1.220     brouard  6233:                        
1.222     brouard  6234:        fprintf(ficresprob,"\n%d ",(int)age);
                   6235:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6236:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6237:                        
1.222     brouard  6238:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6239:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6240:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6241:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6242:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6243:        }
                   6244:        i=0;
                   6245:        for (k=1; k<=(nlstate);k++){
                   6246:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6247:           i++;
                   6248:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6249:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6250:           for (j=1; j<=i;j++){
                   6251:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6252:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6253:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6254:           }
                   6255:         }
                   6256:        }/* end of loop for state */
                   6257:      } /* end of loop for age */
                   6258:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6259:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6260:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6261:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6262:     
                   6263:      /* Confidence intervalle of pij  */
                   6264:      /*
                   6265:        fprintf(ficgp,"\nunset parametric;unset label");
                   6266:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6267:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6268:        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);
                   6269:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6270:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6271:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6272:      */
                   6273:                
                   6274:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6275:      first1=1;first2=2;
                   6276:      for (k2=1; k2<=(nlstate);k2++){
                   6277:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6278:         if(l2==k2) continue;
                   6279:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6280:         for (k1=1; k1<=(nlstate);k1++){
                   6281:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6282:             if(l1==k1) continue;
                   6283:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6284:             if(i<=j) continue;
                   6285:             for (age=bage; age<=fage; age ++){ 
                   6286:               if ((int)age %5==0){
                   6287:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6288:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6289:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6290:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6291:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6292:                 c12=cv12/sqrt(v1*v2);
                   6293:                 /* Computing eigen value of matrix of covariance */
                   6294:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6295:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6296:                 if ((lc2 <0) || (lc1 <0) ){
                   6297:                   if(first2==1){
                   6298:                     first1=0;
                   6299:                     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);
                   6300:                   }
                   6301:                   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);
                   6302:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6303:                   /* lc2=fabs(lc2); */
                   6304:                 }
1.220     brouard  6305:                                                                
1.222     brouard  6306:                 /* Eigen vectors */
                   6307:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6308:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6309:                 v21=(lc1-v1)/cv12*v11;
                   6310:                 v12=-v21;
                   6311:                 v22=v11;
                   6312:                 tnalp=v21/v11;
                   6313:                 if(first1==1){
                   6314:                   first1=0;
                   6315:                   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);
                   6316:                 }
                   6317:                 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);
                   6318:                 /*printf(fignu*/
                   6319:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6320:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6321:                 if(first==1){
                   6322:                   first=0;
                   6323:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6324:                   fprintf(ficgp,"\nset parametric;unset label");
                   6325:                   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);
                   6326:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6327:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6328:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6329: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6330:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6331:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6332:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6333:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6334:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6335:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6336:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6337:                   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",      \
                   6338:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6339:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6340:                 }else{
                   6341:                   first=0;
                   6342:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6343:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6344:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6345:                   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", \
                   6346:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6347:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6348:                 }/* if first */
                   6349:               } /* age mod 5 */
                   6350:             } /* end loop age */
                   6351:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6352:             first=1;
                   6353:           } /*l12 */
                   6354:         } /* k12 */
                   6355:        } /*l1 */
                   6356:      }/* k1 */
                   6357:    }  /* loop on combination of covariates j1 */
                   6358:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6359:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6360:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6361:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6362:    free_vector(xp,1,npar);
                   6363:    fclose(ficresprob);
                   6364:    fclose(ficresprobcov);
                   6365:    fclose(ficresprobcor);
                   6366:    fflush(ficgp);
                   6367:    fflush(fichtmcov);
                   6368:  }
1.126     brouard  6369: 
                   6370: 
                   6371: /******************* Printing html file ***********/
1.201     brouard  6372: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6373:                  int lastpass, int stepm, int weightopt, char model[],\
                   6374:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6375:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6376:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6377:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6378:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6379: 
                   6380:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6381:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6382: </ul>");
1.237     brouard  6383:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6384: </ul>", model);
1.214     brouard  6385:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6386:    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",
                   6387:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6388:    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  6389:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6390:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6391:    fprintf(fichtm,"\
                   6392:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6393:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6394:    fprintf(fichtm,"\
1.217     brouard  6395:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6396:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6397:    fprintf(fichtm,"\
1.126     brouard  6398:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6399:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6400:    fprintf(fichtm,"\
1.217     brouard  6401:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6402:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6403:    fprintf(fichtm,"\
1.211     brouard  6404:  - (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  6405:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6406:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6407:    if(prevfcast==1){
                   6408:      fprintf(fichtm,"\
                   6409:  - Prevalence projections by age and states:                           \
1.201     brouard  6410:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6411:    }
1.126     brouard  6412: 
1.222     brouard  6413:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6414: 
1.225     brouard  6415:    m=pow(2,cptcoveff);
1.222     brouard  6416:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6417: 
1.222     brouard  6418:    jj1=0;
1.237     brouard  6419: 
                   6420:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6421:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6422:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6423:        continue;
1.220     brouard  6424: 
1.222     brouard  6425:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6426:      jj1++;
                   6427:      if (cptcovn > 0) {
                   6428:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6429:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6430:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6431:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6432:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6433:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6434:        }
1.237     brouard  6435:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6436:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6437:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6438:       }
                   6439:        
1.230     brouard  6440:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6441:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6442:        if(invalidvarcomb[k1]){
                   6443:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6444:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6445:         continue;
                   6446:        }
                   6447:      }
                   6448:      /* aij, bij */
1.241     brouard  6449:      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> \
                   6450: <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  6451:      /* Pij */
1.241     brouard  6452:      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> \
                   6453: <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  6454:      /* Quasi-incidences */
                   6455:      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  6456:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6457:  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  6458: 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> \
                   6459: <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  6460:      /* Survival functions (period) in state j */
                   6461:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6462:        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> \
                   6463: <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  6464:      }
                   6465:      /* State specific survival functions (period) */
                   6466:      for(cpt=1; cpt<=nlstate;cpt++){
                   6467:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6468:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6469:  <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  6470:      }
                   6471:      /* Period (stable) prevalence in each health state */
                   6472:      for(cpt=1; cpt<=nlstate;cpt++){
1.255     brouard  6473:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d some years earlier, knowing that we will be in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
1.241     brouard  6474: <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  6475:      }
                   6476:      if(backcast==1){
                   6477:        /* Period (stable) back prevalence in each health state */
                   6478:        for(cpt=1; cpt<=nlstate;cpt++){
1.255     brouard  6479:         fprintf(fichtm,"<br>\n- Convergence to mixed (stable) back prevalence in state %d. Or probability to be in state %d at a younger age, knowing that we will be in state (1 to %d) at different older ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
1.241     brouard  6480: <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  6481:        }
1.217     brouard  6482:      }
1.222     brouard  6483:      if(prevfcast==1){
                   6484:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6485:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6486:         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> \
                   6487: <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  6488:        }
                   6489:      }
1.220     brouard  6490:         
1.222     brouard  6491:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6492:        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> \
                   6493: <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  6494:      }
                   6495:      /* } /\* end i1 *\/ */
                   6496:    }/* End k1 */
                   6497:    fprintf(fichtm,"</ul>");
1.126     brouard  6498: 
1.222     brouard  6499:    fprintf(fichtm,"\
1.126     brouard  6500: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6501:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6502:  - 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  6503: But because parameters are usually highly correlated (a higher incidence of disability \
                   6504: and a higher incidence of recovery can give very close observed transition) it might \
                   6505: be very useful to look not only at linear confidence intervals estimated from the \
                   6506: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6507: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6508: covariance matrix of the one-step probabilities. \
                   6509: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6510: 
1.222     brouard  6511:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6512:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6513:    fprintf(fichtm,"\
1.126     brouard  6514:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6515:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6516: 
1.222     brouard  6517:    fprintf(fichtm,"\
1.126     brouard  6518:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6519:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6520:    fprintf(fichtm,"\
1.126     brouard  6521:  - 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): \
                   6522:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6523:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6524:    fprintf(fichtm,"\
1.126     brouard  6525:  - (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): \
                   6526:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6527:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6528:    fprintf(fichtm,"\
1.128     brouard  6529:  - 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  6530:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6531:    fprintf(fichtm,"\
1.128     brouard  6532:  - 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  6533:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6534:    fprintf(fichtm,"\
1.126     brouard  6535:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6536:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6537: 
                   6538: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6539: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6540: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6541: /*     <br>",fileres,fileres,fileres,fileres); */
                   6542: /*  else  */
                   6543: /*    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  6544:    fflush(fichtm);
                   6545:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6546: 
1.225     brouard  6547:    m=pow(2,cptcoveff);
1.222     brouard  6548:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6549: 
1.222     brouard  6550:    jj1=0;
1.237     brouard  6551: 
1.241     brouard  6552:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6553:    for(k1=1; k1<=m;k1++){
1.253     brouard  6554:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6555:        continue;
1.222     brouard  6556:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6557:      jj1++;
1.126     brouard  6558:      if (cptcovn > 0) {
                   6559:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6560:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6561:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6562:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6563:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6564:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6565:       }
                   6566: 
1.126     brouard  6567:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6568: 
1.222     brouard  6569:        if(invalidvarcomb[k1]){
                   6570:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6571:         continue;
                   6572:        }
1.126     brouard  6573:      }
                   6574:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6575:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
1.241     brouard  6576: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
                   6577: <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  6578:      }
                   6579:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6580: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6581: true period expectancies (those weighted with period prevalences are also\
                   6582:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6583:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6584: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6585:      /* } /\* end i1 *\/ */
                   6586:    }/* End k1 */
1.241     brouard  6587:   }/* End nres */
1.222     brouard  6588:    fprintf(fichtm,"</ul>");
                   6589:    fflush(fichtm);
1.126     brouard  6590: }
                   6591: 
                   6592: /******************* Gnuplot file **************/
1.223     brouard  6593: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6594: 
                   6595:   char dirfileres[132],optfileres[132];
1.223     brouard  6596:   char gplotcondition[132];
1.237     brouard  6597:   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  6598:   int lv=0, vlv=0, kl=0;
1.130     brouard  6599:   int ng=0;
1.201     brouard  6600:   int vpopbased;
1.223     brouard  6601:   int ioffset; /* variable offset for columns */
1.235     brouard  6602:   int nres=0; /* Index of resultline */
1.219     brouard  6603: 
1.126     brouard  6604: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6605: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6606: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6607: /*   } */
                   6608: 
                   6609:   /*#ifdef windows */
                   6610:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6611:   /*#endif */
1.225     brouard  6612:   m=pow(2,cptcoveff);
1.126     brouard  6613: 
1.202     brouard  6614:   /* Contribution to likelihood */
                   6615:   /* Plot the probability implied in the likelihood */
1.223     brouard  6616:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6617:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6618:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6619:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6620: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6621:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6622: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6623:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6624:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6625:   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));
                   6626:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6627:   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));
                   6628:   for (i=1; i<= nlstate ; i ++) {
                   6629:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6630:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6631:     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);
                   6632:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6633:       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);
                   6634:     }
                   6635:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6636:   }
                   6637:   /* 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 */               
                   6638:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6639:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6640:   fprintf(ficgp,"\nset out;unset log\n");
                   6641:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6642: 
1.126     brouard  6643:   strcpy(dirfileres,optionfilefiname);
                   6644:   strcpy(optfileres,"vpl");
1.223     brouard  6645:   /* 1eme*/
1.238     brouard  6646:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6647:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6648:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6649:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  6650:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  6651:          continue;
                   6652:        /* We are interested in selected combination by the resultline */
1.246     brouard  6653:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.238     brouard  6654:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6655:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6656:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6657:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6658:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6659:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6660:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6661:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  6662:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  6663:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6664:        }
                   6665:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  6666:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  6667:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6668:        }       
1.246     brouard  6669:        /* printf("\n#\n"); */
1.238     brouard  6670:        fprintf(ficgp,"\n#\n");
                   6671:        if(invalidvarcomb[k1]){
                   6672:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6673:          continue;
                   6674:        }
1.235     brouard  6675:       
1.241     brouard  6676:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6677:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   6678:        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  6679:       
1.238     brouard  6680:        for (i=1; i<= nlstate ; i ++) {
                   6681:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6682:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6683:        }
1.242     brouard  6684:        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  6685:        for (i=1; i<= nlstate ; i ++) {
                   6686:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6687:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6688:        } 
1.242     brouard  6689:        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  6690:        for (i=1; i<= nlstate ; i ++) {
                   6691:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6692:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6693:        }  
                   6694:        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));
                   6695:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6696:          /* 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  6697:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6698:          if(cptcoveff ==0){
1.245     brouard  6699:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  6700:          }else{
                   6701:            kl=0;
                   6702:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6703:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6704:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6705:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6706:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6707:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6708:              kl++;
1.238     brouard  6709:              /* 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 *\/ */
                   6710:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6711:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6712:              /* ''  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*/
                   6713:              if(k==cptcoveff){
1.245     brouard  6714:                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  6715:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6716:              }else{
                   6717:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6718:                kl++;
                   6719:              }
                   6720:            } /* end covariate */
                   6721:          } /* end if no covariate */
                   6722:        } /* end if backcast */
                   6723:        fprintf(ficgp,"\nset out \n");
                   6724:       } /* nres */
1.201     brouard  6725:     } /* k1 */
                   6726:   } /* cpt */
1.235     brouard  6727: 
                   6728:   
1.126     brouard  6729:   /*2 eme*/
1.238     brouard  6730:   for (k1=1; k1<= m ; k1 ++){  
                   6731:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6732:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  6733:        continue;
                   6734:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6735:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6736:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6737:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6738:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6739:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6740:        vlv= nbcode[Tvaraff[k]][lv];
                   6741:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6742:       }
1.237     brouard  6743:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6744:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6745:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6746:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6747:       }
1.211     brouard  6748:       fprintf(ficgp,"\n#\n");
1.223     brouard  6749:       if(invalidvarcomb[k1]){
                   6750:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6751:        continue;
                   6752:       }
1.219     brouard  6753:                        
1.241     brouard  6754:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6755:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6756:        if(vpopbased==0)
                   6757:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6758:        else
                   6759:          fprintf(ficgp,"\nreplot ");
                   6760:        for (i=1; i<= nlstate+1 ; i ++) {
                   6761:          k=2*i;
                   6762:          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);
                   6763:          for (j=1; j<= nlstate+1 ; j ++) {
                   6764:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6765:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6766:          }   
                   6767:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6768:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6769:          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);
                   6770:          for (j=1; j<= nlstate+1 ; j ++) {
                   6771:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6772:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6773:          }   
                   6774:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6775:          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);
                   6776:          for (j=1; j<= nlstate+1 ; j ++) {
                   6777:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6778:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6779:          }   
                   6780:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6781:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6782:        } /* state */
                   6783:       } /* vpopbased */
1.244     brouard  6784:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  6785:     } /* end nres */
                   6786:   } /* k1 end 2 eme*/
                   6787:        
                   6788:        
                   6789:   /*3eme*/
                   6790:   for (k1=1; k1<= m ; k1 ++){
                   6791:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6792:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  6793:        continue;
                   6794: 
                   6795:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6796:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6797:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6798:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6799:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6800:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6801:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6802:          vlv= nbcode[Tvaraff[k]][lv];
                   6803:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6804:        }
                   6805:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6806:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6807:        }       
                   6808:        fprintf(ficgp,"\n#\n");
                   6809:        if(invalidvarcomb[k1]){
                   6810:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6811:          continue;
                   6812:        }
                   6813:                        
                   6814:        /*       k=2+nlstate*(2*cpt-2); */
                   6815:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6816:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6817:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6818: 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  6819:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6820:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6821:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6822:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6823:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6824:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6825:                                
1.238     brouard  6826:        */
                   6827:        for (i=1; i< nlstate ; i ++) {
                   6828:          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);
                   6829:          /*    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  6830:                                
1.238     brouard  6831:        } 
                   6832:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6833:       }
                   6834:     } /* end nres */
                   6835:   } /* end kl 3eme */
1.126     brouard  6836:   
1.223     brouard  6837:   /* 4eme */
1.201     brouard  6838:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6839:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6840:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6841:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  6842:        continue;
1.238     brouard  6843:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6844:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6845:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6846:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6847:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6848:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6849:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6850:          vlv= nbcode[Tvaraff[k]][lv];
                   6851:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6852:        }
                   6853:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6854:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6855:        }       
                   6856:        fprintf(ficgp,"\n#\n");
                   6857:        if(invalidvarcomb[k1]){
                   6858:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6859:          continue;
1.223     brouard  6860:        }
1.238     brouard  6861:       
1.241     brouard  6862:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6863:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6864: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6865:        k=3;
                   6866:        for (i=1; i<= nlstate ; i ++){
                   6867:          if(i==1){
                   6868:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6869:          }else{
                   6870:            fprintf(ficgp,", '' ");
                   6871:          }
                   6872:          l=(nlstate+ndeath)*(i-1)+1;
                   6873:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6874:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6875:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6876:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6877:        } /* nlstate */
                   6878:        fprintf(ficgp,"\nset out\n");
                   6879:       } /* end cpt state*/ 
                   6880:     } /* end nres */
                   6881:   } /* end covariate k1 */  
                   6882: 
1.220     brouard  6883: /* 5eme */
1.201     brouard  6884:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6885:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6886:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6887:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  6888:        continue;
1.238     brouard  6889:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6890:        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);
                   6891:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6892:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6893:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6894:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6895:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6896:          vlv= nbcode[Tvaraff[k]][lv];
                   6897:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6898:        }
                   6899:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6900:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6901:        }       
                   6902:        fprintf(ficgp,"\n#\n");
                   6903:        if(invalidvarcomb[k1]){
                   6904:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6905:          continue;
                   6906:        }
1.227     brouard  6907:       
1.241     brouard  6908:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6909:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6910: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6911:        k=3;
                   6912:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6913:          if(j==1)
                   6914:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6915:          else
                   6916:            fprintf(ficgp,", '' ");
                   6917:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6918:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6919:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6920:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6921:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6922:        } /* nlstate */
                   6923:        fprintf(ficgp,", '' ");
                   6924:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6925:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6926:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6927:          if(j < nlstate)
                   6928:            fprintf(ficgp,"$%d +",k+l);
                   6929:          else
                   6930:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6931:        }
                   6932:        fprintf(ficgp,"\nset out\n");
                   6933:       } /* end cpt state*/ 
                   6934:     } /* end covariate */  
                   6935:   } /* end nres */
1.227     brouard  6936:   
1.220     brouard  6937: /* 6eme */
1.202     brouard  6938:   /* CV preval stable (period) for each covariate */
1.237     brouard  6939:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6940:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6941:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6942:       continue;
1.255     brouard  6943:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.227     brouard  6944:       
1.211     brouard  6945:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6946:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6947:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6948:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6949:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6950:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6951:        vlv= nbcode[Tvaraff[k]][lv];
                   6952:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6953:       }
1.237     brouard  6954:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6955:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6956:       }        
1.211     brouard  6957:       fprintf(ficgp,"\n#\n");
1.223     brouard  6958:       if(invalidvarcomb[k1]){
1.227     brouard  6959:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6960:        continue;
1.223     brouard  6961:       }
1.227     brouard  6962:       
1.241     brouard  6963:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6964:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6965: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6966:       k=3; /* Offset */
1.255     brouard  6967:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  6968:        if(i==1)
                   6969:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6970:        else
                   6971:          fprintf(ficgp,", '' ");
1.255     brouard  6972:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  6973:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6974:        for (j=2; j<= nlstate ; j ++)
                   6975:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6976:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6977:       } /* nlstate */
1.201     brouard  6978:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6979:     } /* end cpt state*/ 
                   6980:   } /* end covariate */  
1.227     brouard  6981:   
                   6982:   
1.220     brouard  6983: /* 7eme */
1.218     brouard  6984:   if(backcast == 1){
1.217     brouard  6985:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6986:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6987:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6988:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6989:        continue;
1.255     brouard  6990:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life ending state */
                   6991:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  6992:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6993:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6994:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6995:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6996:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6997:          vlv= nbcode[Tvaraff[k]][lv];
                   6998:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6999:        }
1.237     brouard  7000:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7001:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7002:        }       
1.227     brouard  7003:        fprintf(ficgp,"\n#\n");
                   7004:        if(invalidvarcomb[k1]){
                   7005:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7006:          continue;
                   7007:        }
                   7008:        
1.241     brouard  7009:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  7010:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7011: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7012:        k=3; /* Offset */
1.255     brouard  7013:        for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7014:          if(i==1)
                   7015:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7016:          else
                   7017:            fprintf(ficgp,", '' ");
                   7018:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7019:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7020:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7021:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
1.255     brouard  7022:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7023:          /* for (j=2; j<= nlstate ; j ++) */
                   7024:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7025:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   7026:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   7027:        } /* nlstate */
                   7028:        fprintf(ficgp,"\nset out\n");
1.218     brouard  7029:       } /* end cpt state*/ 
                   7030:     } /* end covariate */  
                   7031:   } /* End if backcast */
                   7032:   
1.223     brouard  7033:   /* 8eme */
1.218     brouard  7034:   if(prevfcast==1){
                   7035:     /* Projection from cross-sectional to stable (period) for each covariate */
                   7036:     
1.237     brouard  7037:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7038:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7039:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7040:        continue;
1.211     brouard  7041:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  7042:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   7043:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7044:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7045:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7046:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7047:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7048:          vlv= nbcode[Tvaraff[k]][lv];
                   7049:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7050:        }
1.237     brouard  7051:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7052:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7053:        }       
1.227     brouard  7054:        fprintf(ficgp,"\n#\n");
                   7055:        if(invalidvarcomb[k1]){
                   7056:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7057:          continue;
                   7058:        }
                   7059:        
                   7060:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7061:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  7062:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7063: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7064:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7065:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7066:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7067:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7068:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7069:          if(i==1){
                   7070:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7071:          }else{
                   7072:            fprintf(ficgp,",\\\n '' ");
                   7073:          }
                   7074:          if(cptcoveff ==0){ /* No covariate */
                   7075:            ioffset=2; /* Age is in 2 */
                   7076:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7077:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7078:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7079:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7080:            fprintf(ficgp," u %d:(", ioffset); 
                   7081:            if(i==nlstate+1)
                   7082:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   7083:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7084:            else
                   7085:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7086:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7087:          }else{ /* more than 2 covariates */
                   7088:            if(cptcoveff ==1){
                   7089:              ioffset=4; /* Age is in 4 */
                   7090:            }else{
                   7091:              ioffset=6; /* Age is in 6 */
                   7092:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7093:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7094:            }   
                   7095:            fprintf(ficgp," u %d:(",ioffset); 
                   7096:            kl=0;
                   7097:            strcpy(gplotcondition,"(");
                   7098:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7099:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7100:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7101:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7102:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7103:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7104:              kl++;
                   7105:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7106:              kl++;
                   7107:              if(k <cptcoveff && cptcoveff>1)
                   7108:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7109:            }
                   7110:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7111:            /* 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 *\/ */
                   7112:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7113:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7114:            /* ''  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*/
                   7115:            if(i==nlstate+1){
                   7116:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   7117:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7118:            }else{
                   7119:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7120:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7121:            }
                   7122:          } /* end if covariate */
                   7123:        } /* nlstate */
                   7124:        fprintf(ficgp,"\nset out\n");
1.223     brouard  7125:       } /* end cpt state*/
                   7126:     } /* end covariate */
                   7127:   } /* End if prevfcast */
1.227     brouard  7128:   
                   7129:   
1.238     brouard  7130:   /* 9eme writing MLE parameters */
                   7131:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7132:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7133:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7134:     for(k=1; k <=(nlstate+ndeath); k++){
                   7135:       if (k != i) {
1.227     brouard  7136:        fprintf(ficgp,"#   current state %d\n",k);
                   7137:        for(j=1; j <=ncovmodel; j++){
                   7138:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7139:          jk++; 
                   7140:        }
                   7141:        fprintf(ficgp,"\n");
1.126     brouard  7142:       }
                   7143:     }
1.223     brouard  7144:   }
1.187     brouard  7145:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7146:   
1.145     brouard  7147:   /*goto avoid;*/
1.238     brouard  7148:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7149:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7150:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7151:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7152:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7153:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7154:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7155:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7156:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7157:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7158:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7159:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7160:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7161:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7162:   fprintf(ficgp,"#\n");
1.223     brouard  7163:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7164:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7165:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7166:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  7167:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7168:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   7169:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7170:       if(m != 1 && TKresult[nres]!= jk)
1.237     brouard  7171:        continue;
                   7172:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   7173:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7174:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7175:       }        
                   7176:       fprintf(ficgp,"\n#\n");
1.241     brouard  7177:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  7178:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7179:       if (ng==1){
                   7180:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7181:        fprintf(ficgp,"\nunset log y");
                   7182:       }else if (ng==2){
                   7183:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7184:        fprintf(ficgp,"\nset log y");
                   7185:       }else if (ng==3){
                   7186:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7187:        fprintf(ficgp,"\nset log y");
                   7188:       }else
                   7189:        fprintf(ficgp,"\nunset title ");
                   7190:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7191:       i=1;
                   7192:       for(k2=1; k2<=nlstate; k2++) {
                   7193:        k3=i;
                   7194:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7195:          if (k != k2){
                   7196:            switch( ng) {
                   7197:            case 1:
                   7198:              if(nagesqr==0)
                   7199:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7200:              else /* nagesqr =1 */
                   7201:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7202:              break;
                   7203:            case 2: /* ng=2 */
                   7204:              if(nagesqr==0)
                   7205:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7206:              else /* nagesqr =1 */
                   7207:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7208:              break;
                   7209:            case 3:
                   7210:              if(nagesqr==0)
                   7211:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7212:              else /* nagesqr =1 */
                   7213:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7214:              break;
                   7215:            }
                   7216:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  7217:            ijp=1; /* product no age */
                   7218:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   7219:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  7220:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  7221:              if(j==Tage[ij]) { /* Product by age */
                   7222:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  7223:                  if(DummyV[j]==0){
1.237     brouard  7224:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   7225:                  }else{ /* quantitative */
                   7226:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   7227:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7228:                  }
                   7229:                  ij++;
                   7230:                }
                   7231:              }else if(j==Tprod[ijp]) { /* */ 
                   7232:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   7233:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  7234:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   7235:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  7236:                      /* 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)]); */
                   7237:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   7238:                    }else{ /* Vn is dummy and Vm is quanti */
                   7239:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   7240:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7241:                    }
                   7242:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  7243:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  7244:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   7245:                    }else{ /* Both quanti */
                   7246:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7247:                    }
                   7248:                  }
1.238     brouard  7249:                  ijp++;
1.237     brouard  7250:                }
                   7251:              } else{  /* simple covariate */
                   7252:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   7253:                if(Dummy[j]==0){
                   7254:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   7255:                }else{ /* quantitative */
                   7256:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  7257:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7258:                }
1.237     brouard  7259:              } /* end simple */
                   7260:            } /* end j */
1.223     brouard  7261:          }else{
                   7262:            i=i-ncovmodel;
                   7263:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7264:              fprintf(ficgp," (1.");
                   7265:          }
1.227     brouard  7266:          
1.223     brouard  7267:          if(ng != 1){
                   7268:            fprintf(ficgp,")/(1");
1.227     brouard  7269:            
1.223     brouard  7270:            for(k1=1; k1 <=nlstate; k1++){ 
                   7271:              if(nagesqr==0)
                   7272:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7273:              else /* nagesqr =1 */
                   7274:                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  7275:               
1.223     brouard  7276:              ij=1;
                   7277:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7278:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7279:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7280:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7281:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7282:                    ij++;
                   7283:                  }
                   7284:                }
                   7285:                else
1.225     brouard  7286:                  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  7287:              }
                   7288:              fprintf(ficgp,")");
                   7289:            }
                   7290:            fprintf(ficgp,")");
                   7291:            if(ng ==2)
                   7292:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7293:            else /* ng= 3 */
                   7294:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7295:          }else{ /* end ng <> 1 */
                   7296:            if( k !=k2) /* logit p11 is hard to draw */
                   7297:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7298:          }
                   7299:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7300:            fprintf(ficgp,",");
                   7301:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7302:            fprintf(ficgp,",");
                   7303:          i=i+ncovmodel;
                   7304:        } /* end k */
                   7305:       } /* end k2 */
                   7306:       fprintf(ficgp,"\n set out\n");
                   7307:     } /* end jk */
                   7308:   } /* end ng */
                   7309:   /* avoid: */
                   7310:   fflush(ficgp); 
1.126     brouard  7311: }  /* end gnuplot */
                   7312: 
                   7313: 
                   7314: /*************** Moving average **************/
1.219     brouard  7315: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7316:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7317:    
1.222     brouard  7318:    int i, cpt, cptcod;
                   7319:    int modcovmax =1;
                   7320:    int mobilavrange, mob;
                   7321:    int iage=0;
                   7322: 
                   7323:    double sum=0.;
                   7324:    double age;
                   7325:    double *sumnewp, *sumnewm;
                   7326:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7327:   
                   7328:   
1.225     brouard  7329:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7330:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7331: 
                   7332:    sumnewp = vector(1,ncovcombmax);
                   7333:    sumnewm = vector(1,ncovcombmax);
                   7334:    agemingood = vector(1,ncovcombmax); 
                   7335:    agemaxgood = vector(1,ncovcombmax);
                   7336: 
                   7337:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7338:      sumnewm[cptcod]=0.;
                   7339:      sumnewp[cptcod]=0.;
                   7340:      agemingood[cptcod]=0;
                   7341:      agemaxgood[cptcod]=0;
                   7342:    }
                   7343:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7344:   
                   7345:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7346:      if(mobilav==1) mobilavrange=5; /* default */
                   7347:      else mobilavrange=mobilav;
                   7348:      for (age=bage; age<=fage; age++)
                   7349:        for (i=1; i<=nlstate;i++)
                   7350:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7351:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7352:      /* We keep the original values on the extreme ages bage, fage and for 
                   7353:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7354:        we use a 5 terms etc. until the borders are no more concerned. 
                   7355:      */ 
                   7356:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7357:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7358:         for (i=1; i<=nlstate;i++){
                   7359:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7360:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7361:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7362:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7363:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7364:             }
                   7365:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7366:           }
                   7367:         }
                   7368:        }/* end age */
                   7369:      }/* end mob */
                   7370:    }else
                   7371:      return -1;
                   7372:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7373:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7374:      if(invalidvarcomb[cptcod]){
                   7375:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7376:        continue;
                   7377:      }
1.219     brouard  7378: 
1.222     brouard  7379:      agemingood[cptcod]=fage-(mob-1)/2;
                   7380:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7381:        sumnewm[cptcod]=0.;
                   7382:        for (i=1; i<=nlstate;i++){
                   7383:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7384:        }
                   7385:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7386:         agemingood[cptcod]=age;
                   7387:        }else{ /* bad */
                   7388:         for (i=1; i<=nlstate;i++){
                   7389:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7390:         } /* i */
                   7391:        } /* end bad */
                   7392:      }/* age */
                   7393:      sum=0.;
                   7394:      for (i=1; i<=nlstate;i++){
                   7395:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7396:      }
                   7397:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7398:        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);
                   7399:        /* for (i=1; i<=nlstate;i++){ */
                   7400:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7401:        /* } /\* i *\/ */
                   7402:      } /* end bad */
                   7403:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7404:      /* From youngest, finding the oldest wrong */
                   7405:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7406:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7407:        sumnewm[cptcod]=0.;
                   7408:        for (i=1; i<=nlstate;i++){
                   7409:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7410:        }
                   7411:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7412:         agemaxgood[cptcod]=age;
                   7413:        }else{ /* bad */
                   7414:         for (i=1; i<=nlstate;i++){
                   7415:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7416:         } /* i */
                   7417:        } /* end bad */
                   7418:      }/* age */
                   7419:      sum=0.;
                   7420:      for (i=1; i<=nlstate;i++){
                   7421:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7422:      }
                   7423:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7424:        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);
                   7425:        /* for (i=1; i<=nlstate;i++){ */
                   7426:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7427:        /* } /\* i *\/ */
                   7428:      } /* end bad */
                   7429:                
                   7430:      for (age=bage; age<=fage; age++){
1.235     brouard  7431:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7432:        sumnewp[cptcod]=0.;
                   7433:        sumnewm[cptcod]=0.;
                   7434:        for (i=1; i<=nlstate;i++){
                   7435:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7436:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7437:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7438:        }
                   7439:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7440:      }
                   7441:      /* printf("\n"); */
                   7442:      /* } */
                   7443:      /* brutal averaging */
                   7444:      for (i=1; i<=nlstate;i++){
                   7445:        for (age=1; age<=bage; age++){
                   7446:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7447:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7448:        }       
                   7449:        for (age=fage; age<=AGESUP; age++){
                   7450:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7451:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7452:        }
                   7453:      } /* end i status */
                   7454:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7455:        for (age=1; age<=AGESUP; age++){
                   7456:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7457:         mobaverage[(int)age][i][cptcod]=0.;
                   7458:        }
                   7459:      }
                   7460:    }/* end cptcod */
                   7461:    free_vector(sumnewm,1, ncovcombmax);
                   7462:    free_vector(sumnewp,1, ncovcombmax);
                   7463:    free_vector(agemaxgood,1, ncovcombmax);
                   7464:    free_vector(agemingood,1, ncovcombmax);
                   7465:    return 0;
                   7466:  }/* End movingaverage */
1.218     brouard  7467:  
1.126     brouard  7468: 
                   7469: /************** Forecasting ******************/
1.235     brouard  7470:  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  7471:   /* proj1, year, month, day of starting projection 
                   7472:      agemin, agemax range of age
                   7473:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7474:      anproj2 year of en of projection (same day and month as proj1).
                   7475:   */
1.235     brouard  7476:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7477:   double agec; /* generic age */
                   7478:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7479:   double *popeffectif,*popcount;
                   7480:   double ***p3mat;
1.218     brouard  7481:   /* double ***mobaverage; */
1.126     brouard  7482:   char fileresf[FILENAMELENGTH];
                   7483: 
                   7484:   agelim=AGESUP;
1.211     brouard  7485:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7486:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7487:      We still use firstpass and lastpass as another selection.
                   7488:   */
1.214     brouard  7489:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7490:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7491:  
1.201     brouard  7492:   strcpy(fileresf,"F_"); 
                   7493:   strcat(fileresf,fileresu);
1.126     brouard  7494:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7495:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7496:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7497:   }
1.235     brouard  7498:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7499:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7500: 
1.225     brouard  7501:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7502: 
                   7503: 
                   7504:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7505:   if (stepm<=12) stepsize=1;
                   7506:   if(estepm < stepm){
                   7507:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7508:   }
                   7509:   else  hstepm=estepm;   
                   7510: 
                   7511:   hstepm=hstepm/stepm; 
                   7512:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7513:                                fractional in yp1 */
                   7514:   anprojmean=yp;
                   7515:   yp2=modf((yp1*12),&yp);
                   7516:   mprojmean=yp;
                   7517:   yp1=modf((yp2*30.5),&yp);
                   7518:   jprojmean=yp;
                   7519:   if(jprojmean==0) jprojmean=1;
                   7520:   if(mprojmean==0) jprojmean=1;
                   7521: 
1.227     brouard  7522:   i1=pow(2,cptcoveff);
1.126     brouard  7523:   if (cptcovn < 1){i1=1;}
                   7524:   
                   7525:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7526:   
                   7527:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7528:   
1.126     brouard  7529: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7530:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7531:   for(k=1; k<=i1;k++){
1.253     brouard  7532:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  7533:       continue;
1.227     brouard  7534:     if(invalidvarcomb[k]){
                   7535:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7536:       continue;
                   7537:     }
                   7538:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7539:     for(j=1;j<=cptcoveff;j++) {
                   7540:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7541:     }
1.235     brouard  7542:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7543:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7544:     }
1.227     brouard  7545:     fprintf(ficresf," yearproj age");
                   7546:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7547:       for(i=1; i<=nlstate;i++)               
                   7548:        fprintf(ficresf," p%d%d",i,j);
                   7549:       fprintf(ficresf," wp.%d",j);
                   7550:     }
                   7551:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7552:       fprintf(ficresf,"\n");
                   7553:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7554:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7555:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7556:        nhstepm = nhstepm/hstepm; 
                   7557:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7558:        oldm=oldms;savm=savms;
1.235     brouard  7559:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7560:        
                   7561:        for (h=0; h<=nhstepm; h++){
                   7562:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7563:            fprintf(ficresf,"\n");
                   7564:            for(j=1;j<=cptcoveff;j++) 
                   7565:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7566:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7567:          } 
                   7568:          for(j=1; j<=nlstate+ndeath;j++) {
                   7569:            ppij=0.;
                   7570:            for(i=1; i<=nlstate;i++) {
                   7571:              if (mobilav==1) 
                   7572:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7573:              else {
                   7574:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7575:              }
                   7576:              if (h*hstepm/YEARM*stepm== yearp) {
                   7577:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7578:              }
                   7579:            } /* end i */
                   7580:            if (h*hstepm/YEARM*stepm==yearp) {
                   7581:              fprintf(ficresf," %.3f", ppij);
                   7582:            }
                   7583:          }/* end j */
                   7584:        } /* end h */
                   7585:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7586:       } /* end agec */
                   7587:     } /* end yearp */
                   7588:   } /* end  k */
1.219     brouard  7589:        
1.126     brouard  7590:   fclose(ficresf);
1.215     brouard  7591:   printf("End of Computing forecasting \n");
                   7592:   fprintf(ficlog,"End of Computing forecasting\n");
                   7593: 
1.126     brouard  7594: }
                   7595: 
1.218     brouard  7596: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7597: /* 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  7598: /*   /\* back1, year, month, day of starting backection  */
                   7599: /*      agemin, agemax range of age */
                   7600: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7601: /*      anback2 year of en of backection (same day and month as back1). */
                   7602: /*   *\/ */
                   7603: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7604: /*   double agec; /\* generic age *\/ */
                   7605: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7606: /*   double *popeffectif,*popcount; */
                   7607: /*   double ***p3mat; */
                   7608: /*   /\* double ***mobaverage; *\/ */
                   7609: /*   char fileresfb[FILENAMELENGTH]; */
                   7610:        
                   7611: /*   agelim=AGESUP; */
                   7612: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7613: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7614: /*      We still use firstpass and lastpass as another selection. */
                   7615: /*   *\/ */
                   7616: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7617: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7618: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7619:        
                   7620: /*   strcpy(fileresfb,"FB_");  */
                   7621: /*   strcat(fileresfb,fileresu); */
                   7622: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7623: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7624: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7625: /*   } */
                   7626: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7627: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7628:        
1.225     brouard  7629: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7630:        
                   7631: /*   /\* if (mobilav!=0) { *\/ */
                   7632: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7633: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7634: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7635: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7636: /*   /\*   } *\/ */
                   7637: /*   /\* } *\/ */
                   7638:        
                   7639: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7640: /*   if (stepm<=12) stepsize=1; */
                   7641: /*   if(estepm < stepm){ */
                   7642: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7643: /*   } */
                   7644: /*   else  hstepm=estepm;    */
                   7645:        
                   7646: /*   hstepm=hstepm/stepm;  */
                   7647: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7648: /*                                fractional in yp1 *\/ */
                   7649: /*   anprojmean=yp; */
                   7650: /*   yp2=modf((yp1*12),&yp); */
                   7651: /*   mprojmean=yp; */
                   7652: /*   yp1=modf((yp2*30.5),&yp); */
                   7653: /*   jprojmean=yp; */
                   7654: /*   if(jprojmean==0) jprojmean=1; */
                   7655: /*   if(mprojmean==0) jprojmean=1; */
                   7656:        
1.225     brouard  7657: /*   i1=cptcoveff; */
1.218     brouard  7658: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7659:   
1.218     brouard  7660: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7661:   
1.218     brouard  7662: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7663:        
                   7664: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7665: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7666: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7667: /*       k=k+1; */
                   7668: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7669: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7670: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7671: /*       } */
                   7672: /*       fprintf(ficresfb," yearbproj age"); */
                   7673: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7674: /*                             for(i=1; i<=nlstate;i++)               */
                   7675: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7676: /*                             fprintf(ficresfb," p.%d",j); */
                   7677: /*       } */
                   7678: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7679: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7680: /*                             fprintf(ficresfb,"\n"); */
                   7681: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7682: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7683: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7684: /*                                     nhstepm = nhstepm/hstepm;  */
                   7685: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7686: /*                                     oldm=oldms;savm=savms; */
                   7687: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7688: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7689: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7690: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7691: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7692: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7693: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7694: /*                                             }  */
                   7695: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7696: /*                                                     ppij=0.; */
                   7697: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7698: /*                                                             if (mobilav==1)  */
                   7699: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7700: /*                                                             else { */
                   7701: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7702: /*                                                             } */
                   7703: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7704: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7705: /*                                                             } */
                   7706: /*                                                     } /\* end i *\/ */
                   7707: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7708: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7709: /*                                                     } */
                   7710: /*                                             }/\* end j *\/ */
                   7711: /*                                     } /\* end h *\/ */
                   7712: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7713: /*                             } /\* end agec *\/ */
                   7714: /*       } /\* end yearp *\/ */
                   7715: /*     } /\* end cptcod *\/ */
                   7716: /*   } /\* end  cptcov *\/ */
                   7717:        
                   7718: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7719:        
                   7720: /*   fclose(ficresfb); */
                   7721: /*   printf("End of Computing Back forecasting \n"); */
                   7722: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7723:        
1.218     brouard  7724: /* } */
1.217     brouard  7725: 
1.126     brouard  7726: /************** Forecasting *****not tested NB*************/
1.227     brouard  7727: /* 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  7728:   
1.227     brouard  7729: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7730: /*   int *popage; */
                   7731: /*   double calagedatem, agelim, kk1, kk2; */
                   7732: /*   double *popeffectif,*popcount; */
                   7733: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7734: /*   /\* double ***mobaverage; *\/ */
                   7735: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7736: 
1.227     brouard  7737: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7738: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7739: /*   agelim=AGESUP; */
                   7740: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7741:   
1.227     brouard  7742: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7743:   
                   7744:   
1.227     brouard  7745: /*   strcpy(filerespop,"POP_");  */
                   7746: /*   strcat(filerespop,fileresu); */
                   7747: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7748: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7749: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7750: /*   } */
                   7751: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7752: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7753: 
1.227     brouard  7754: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7755: 
1.227     brouard  7756: /*   /\* if (mobilav!=0) { *\/ */
                   7757: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7758: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7759: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7760: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7761: /*   /\*   } *\/ */
                   7762: /*   /\* } *\/ */
1.126     brouard  7763: 
1.227     brouard  7764: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7765: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7766:   
1.227     brouard  7767: /*   agelim=AGESUP; */
1.126     brouard  7768:   
1.227     brouard  7769: /*   hstepm=1; */
                   7770: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7771:        
1.227     brouard  7772: /*   if (popforecast==1) { */
                   7773: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7774: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7775: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7776: /*     }  */
                   7777: /*     popage=ivector(0,AGESUP); */
                   7778: /*     popeffectif=vector(0,AGESUP); */
                   7779: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7780:     
1.227     brouard  7781: /*     i=1;    */
                   7782: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7783:     
1.227     brouard  7784: /*     imx=i; */
                   7785: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7786: /*   } */
1.218     brouard  7787:   
1.227     brouard  7788: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7789: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7790: /*       k=k+1; */
                   7791: /*       fprintf(ficrespop,"\n#******"); */
                   7792: /*       for(j=1;j<=cptcoveff;j++) { */
                   7793: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7794: /*       } */
                   7795: /*       fprintf(ficrespop,"******\n"); */
                   7796: /*       fprintf(ficrespop,"# Age"); */
                   7797: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7798: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7799:       
1.227     brouard  7800: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7801: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7802:        
1.227     brouard  7803: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7804: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7805: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7806:          
1.227     brouard  7807: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7808: /*       oldm=oldms;savm=savms; */
                   7809: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7810:          
1.227     brouard  7811: /*       for (h=0; h<=nhstepm; h++){ */
                   7812: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7813: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7814: /*         }  */
                   7815: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7816: /*           kk1=0.;kk2=0; */
                   7817: /*           for(i=1; i<=nlstate;i++) {               */
                   7818: /*             if (mobilav==1)  */
                   7819: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7820: /*             else { */
                   7821: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7822: /*             } */
                   7823: /*           } */
                   7824: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7825: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7826: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7827: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7828: /*           } */
                   7829: /*         } */
                   7830: /*         for(i=1; i<=nlstate;i++){ */
                   7831: /*           kk1=0.; */
                   7832: /*           for(j=1; j<=nlstate;j++){ */
                   7833: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7834: /*           } */
                   7835: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7836: /*         } */
1.218     brouard  7837:            
1.227     brouard  7838: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7839: /*           for(j=1; j<=nlstate;j++)  */
                   7840: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7841: /*       } */
                   7842: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7843: /*     } */
                   7844: /*       } */
1.218     brouard  7845:       
1.227     brouard  7846: /*       /\******\/ */
1.218     brouard  7847:       
1.227     brouard  7848: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7849: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7850: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7851: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7852: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7853:          
1.227     brouard  7854: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7855: /*       oldm=oldms;savm=savms; */
                   7856: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7857: /*       for (h=0; h<=nhstepm; h++){ */
                   7858: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7859: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7860: /*         }  */
                   7861: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7862: /*           kk1=0.;kk2=0; */
                   7863: /*           for(i=1; i<=nlstate;i++) {               */
                   7864: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7865: /*           } */
                   7866: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7867: /*         } */
                   7868: /*       } */
                   7869: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7870: /*     } */
                   7871: /*       } */
                   7872: /*     }  */
                   7873: /*   } */
1.218     brouard  7874:   
1.227     brouard  7875: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7876:   
1.227     brouard  7877: /*   if (popforecast==1) { */
                   7878: /*     free_ivector(popage,0,AGESUP); */
                   7879: /*     free_vector(popeffectif,0,AGESUP); */
                   7880: /*     free_vector(popcount,0,AGESUP); */
                   7881: /*   } */
                   7882: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7883: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7884: /*   fclose(ficrespop); */
                   7885: /* } /\* End of popforecast *\/ */
1.218     brouard  7886:  
1.126     brouard  7887: int fileappend(FILE *fichier, char *optionfich)
                   7888: {
                   7889:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7890:     printf("Problem with file: %s\n", optionfich);
                   7891:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7892:     return (0);
                   7893:   }
                   7894:   fflush(fichier);
                   7895:   return (1);
                   7896: }
                   7897: 
                   7898: 
                   7899: /**************** function prwizard **********************/
                   7900: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7901: {
                   7902: 
                   7903:   /* Wizard to print covariance matrix template */
                   7904: 
1.164     brouard  7905:   char ca[32], cb[32];
                   7906:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7907:   int numlinepar;
                   7908: 
                   7909:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7910:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7911:   for(i=1; i <=nlstate; i++){
                   7912:     jj=0;
                   7913:     for(j=1; j <=nlstate+ndeath; j++){
                   7914:       if(j==i) continue;
                   7915:       jj++;
                   7916:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7917:       printf("%1d%1d",i,j);
                   7918:       fprintf(ficparo,"%1d%1d",i,j);
                   7919:       for(k=1; k<=ncovmodel;k++){
                   7920:        /*        printf(" %lf",param[i][j][k]); */
                   7921:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7922:        printf(" 0.");
                   7923:        fprintf(ficparo," 0.");
                   7924:       }
                   7925:       printf("\n");
                   7926:       fprintf(ficparo,"\n");
                   7927:     }
                   7928:   }
                   7929:   printf("# Scales (for hessian or gradient estimation)\n");
                   7930:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7931:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7932:   for(i=1; i <=nlstate; i++){
                   7933:     jj=0;
                   7934:     for(j=1; j <=nlstate+ndeath; j++){
                   7935:       if(j==i) continue;
                   7936:       jj++;
                   7937:       fprintf(ficparo,"%1d%1d",i,j);
                   7938:       printf("%1d%1d",i,j);
                   7939:       fflush(stdout);
                   7940:       for(k=1; k<=ncovmodel;k++){
                   7941:        /*      printf(" %le",delti3[i][j][k]); */
                   7942:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7943:        printf(" 0.");
                   7944:        fprintf(ficparo," 0.");
                   7945:       }
                   7946:       numlinepar++;
                   7947:       printf("\n");
                   7948:       fprintf(ficparo,"\n");
                   7949:     }
                   7950:   }
                   7951:   printf("# Covariance matrix\n");
                   7952: /* # 121 Var(a12)\n\ */
                   7953: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7954: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7955: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7956: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7957: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7958: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7959: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7960:   fflush(stdout);
                   7961:   fprintf(ficparo,"# Covariance matrix\n");
                   7962:   /* # 121 Var(a12)\n\ */
                   7963:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7964:   /* #   ...\n\ */
                   7965:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7966:   
                   7967:   for(itimes=1;itimes<=2;itimes++){
                   7968:     jj=0;
                   7969:     for(i=1; i <=nlstate; i++){
                   7970:       for(j=1; j <=nlstate+ndeath; j++){
                   7971:        if(j==i) continue;
                   7972:        for(k=1; k<=ncovmodel;k++){
                   7973:          jj++;
                   7974:          ca[0]= k+'a'-1;ca[1]='\0';
                   7975:          if(itimes==1){
                   7976:            printf("#%1d%1d%d",i,j,k);
                   7977:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7978:          }else{
                   7979:            printf("%1d%1d%d",i,j,k);
                   7980:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7981:            /*  printf(" %.5le",matcov[i][j]); */
                   7982:          }
                   7983:          ll=0;
                   7984:          for(li=1;li <=nlstate; li++){
                   7985:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7986:              if(lj==li) continue;
                   7987:              for(lk=1;lk<=ncovmodel;lk++){
                   7988:                ll++;
                   7989:                if(ll<=jj){
                   7990:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7991:                  if(ll<jj){
                   7992:                    if(itimes==1){
                   7993:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7994:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7995:                    }else{
                   7996:                      printf(" 0.");
                   7997:                      fprintf(ficparo," 0.");
                   7998:                    }
                   7999:                  }else{
                   8000:                    if(itimes==1){
                   8001:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   8002:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   8003:                    }else{
                   8004:                      printf(" 0.");
                   8005:                      fprintf(ficparo," 0.");
                   8006:                    }
                   8007:                  }
                   8008:                }
                   8009:              } /* end lk */
                   8010:            } /* end lj */
                   8011:          } /* end li */
                   8012:          printf("\n");
                   8013:          fprintf(ficparo,"\n");
                   8014:          numlinepar++;
                   8015:        } /* end k*/
                   8016:       } /*end j */
                   8017:     } /* end i */
                   8018:   } /* end itimes */
                   8019: 
                   8020: } /* end of prwizard */
                   8021: /******************* Gompertz Likelihood ******************************/
                   8022: double gompertz(double x[])
                   8023: { 
                   8024:   double A,B,L=0.0,sump=0.,num=0.;
                   8025:   int i,n=0; /* n is the size of the sample */
                   8026: 
1.220     brouard  8027:   for (i=1;i<=imx ; i++) {
1.126     brouard  8028:     sump=sump+weight[i];
                   8029:     /*    sump=sump+1;*/
                   8030:     num=num+1;
                   8031:   }
                   8032:  
                   8033:  
                   8034:   /* for (i=0; i<=imx; i++) 
                   8035:      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]);*/
                   8036: 
                   8037:   for (i=1;i<=imx ; i++)
                   8038:     {
                   8039:       if (cens[i] == 1 && wav[i]>1)
                   8040:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   8041:       
                   8042:       if (cens[i] == 0 && wav[i]>1)
                   8043:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   8044:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   8045:       
                   8046:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   8047:       if (wav[i] > 1 ) { /* ??? */
                   8048:        L=L+A*weight[i];
                   8049:        /*      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]);*/
                   8050:       }
                   8051:     }
                   8052: 
                   8053:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   8054:  
                   8055:   return -2*L*num/sump;
                   8056: }
                   8057: 
1.136     brouard  8058: #ifdef GSL
                   8059: /******************* Gompertz_f Likelihood ******************************/
                   8060: double gompertz_f(const gsl_vector *v, void *params)
                   8061: { 
                   8062:   double A,B,LL=0.0,sump=0.,num=0.;
                   8063:   double *x= (double *) v->data;
                   8064:   int i,n=0; /* n is the size of the sample */
                   8065: 
                   8066:   for (i=0;i<=imx-1 ; i++) {
                   8067:     sump=sump+weight[i];
                   8068:     /*    sump=sump+1;*/
                   8069:     num=num+1;
                   8070:   }
                   8071:  
                   8072:  
                   8073:   /* for (i=0; i<=imx; i++) 
                   8074:      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]);*/
                   8075:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   8076:   for (i=1;i<=imx ; i++)
                   8077:     {
                   8078:       if (cens[i] == 1 && wav[i]>1)
                   8079:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   8080:       
                   8081:       if (cens[i] == 0 && wav[i]>1)
                   8082:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   8083:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   8084:       
                   8085:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   8086:       if (wav[i] > 1 ) { /* ??? */
                   8087:        LL=LL+A*weight[i];
                   8088:        /*      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]);*/
                   8089:       }
                   8090:     }
                   8091: 
                   8092:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   8093:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   8094:  
                   8095:   return -2*LL*num/sump;
                   8096: }
                   8097: #endif
                   8098: 
1.126     brouard  8099: /******************* Printing html file ***********/
1.201     brouard  8100: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8101:                  int lastpass, int stepm, int weightopt, char model[],\
                   8102:                  int imx,  double p[],double **matcov,double agemortsup){
                   8103:   int i,k;
                   8104: 
                   8105:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   8106:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   8107:   for (i=1;i<=2;i++) 
                   8108:     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  8109:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  8110:   fprintf(fichtm,"</ul>");
                   8111: 
                   8112: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   8113: 
                   8114:  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>");
                   8115: 
                   8116:  for (k=agegomp;k<(agemortsup-2);k++) 
                   8117:    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]);
                   8118: 
                   8119:  
                   8120:   fflush(fichtm);
                   8121: }
                   8122: 
                   8123: /******************* Gnuplot file **************/
1.201     brouard  8124: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  8125: 
                   8126:   char dirfileres[132],optfileres[132];
1.164     brouard  8127: 
1.126     brouard  8128:   int ng;
                   8129: 
                   8130: 
                   8131:   /*#ifdef windows */
                   8132:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   8133:     /*#endif */
                   8134: 
                   8135: 
                   8136:   strcpy(dirfileres,optionfilefiname);
                   8137:   strcpy(optfileres,"vpl");
1.199     brouard  8138:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  8139:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  8140:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  8141:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  8142:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   8143: 
                   8144: } 
                   8145: 
1.136     brouard  8146: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   8147: {
1.126     brouard  8148: 
1.136     brouard  8149:   /*-------- data file ----------*/
                   8150:   FILE *fic;
                   8151:   char dummy[]="                         ";
1.240     brouard  8152:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  8153:   int lstra;
1.136     brouard  8154:   int linei, month, year,iout;
                   8155:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  8156:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  8157:   char *stratrunc;
1.223     brouard  8158: 
1.240     brouard  8159:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   8160:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  8161: 
1.240     brouard  8162:   for(v=1; v <=ncovcol;v++){
                   8163:     DummyV[v]=0;
                   8164:     FixedV[v]=0;
                   8165:   }
                   8166:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   8167:     DummyV[v]=1;
                   8168:     FixedV[v]=0;
                   8169:   }
                   8170:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   8171:     DummyV[v]=0;
                   8172:     FixedV[v]=1;
                   8173:   }
                   8174:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   8175:     DummyV[v]=1;
                   8176:     FixedV[v]=1;
                   8177:   }
                   8178:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   8179:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   8180:     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]);
                   8181:   }
1.126     brouard  8182: 
1.136     brouard  8183:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  8184:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   8185:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  8186:   }
1.126     brouard  8187: 
1.136     brouard  8188:   i=1;
                   8189:   linei=0;
                   8190:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   8191:     linei=linei+1;
                   8192:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   8193:       if(line[j] == '\t')
                   8194:        line[j] = ' ';
                   8195:     }
                   8196:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   8197:       ;
                   8198:     };
                   8199:     line[j+1]=0;  /* Trims blanks at end of line */
                   8200:     if(line[0]=='#'){
                   8201:       fprintf(ficlog,"Comment line\n%s\n",line);
                   8202:       printf("Comment line\n%s\n",line);
                   8203:       continue;
                   8204:     }
                   8205:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  8206:     strcpy(line, linetmp);
1.223     brouard  8207:     
                   8208:     /* Loops on waves */
                   8209:     for (j=maxwav;j>=1;j--){
                   8210:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  8211:        cutv(stra, strb, line, ' '); 
                   8212:        if(strb[0]=='.') { /* Missing value */
                   8213:          lval=-1;
                   8214:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   8215:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   8216:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   8217:            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);
                   8218:            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);
                   8219:            return 1;
                   8220:          }
                   8221:        }else{
                   8222:          errno=0;
                   8223:          /* what_kind_of_number(strb); */
                   8224:          dval=strtod(strb,&endptr); 
                   8225:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   8226:          /* if(strb != endptr && *endptr == '\0') */
                   8227:          /*    dval=dlval; */
                   8228:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8229:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8230:            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);
                   8231:            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);
                   8232:            return 1;
                   8233:          }
                   8234:          cotqvar[j][iv][i]=dval; 
                   8235:          cotvar[j][ntv+iv][i]=dval; 
                   8236:        }
                   8237:        strcpy(line,stra);
1.223     brouard  8238:       }/* end loop ntqv */
1.225     brouard  8239:       
1.223     brouard  8240:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  8241:        cutv(stra, strb, line, ' '); 
                   8242:        if(strb[0]=='.') { /* Missing value */
                   8243:          lval=-1;
                   8244:        }else{
                   8245:          errno=0;
                   8246:          lval=strtol(strb,&endptr,10); 
                   8247:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8248:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8249:            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);
                   8250:            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);
                   8251:            return 1;
                   8252:          }
                   8253:        }
                   8254:        if(lval <-1 || lval >1){
                   8255:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8256:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8257:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8258:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8259:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8260:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8261:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8262:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8263:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8264:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8265:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8266:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8267:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8268:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8269:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8270:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8271:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8272:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8273:          return 1;
                   8274:        }
                   8275:        cotvar[j][iv][i]=(double)(lval);
                   8276:        strcpy(line,stra);
1.223     brouard  8277:       }/* end loop ntv */
1.225     brouard  8278:       
1.223     brouard  8279:       /* Statuses  at wave */
1.137     brouard  8280:       cutv(stra, strb, line, ' '); 
1.223     brouard  8281:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8282:        lval=-1;
1.136     brouard  8283:       }else{
1.238     brouard  8284:        errno=0;
                   8285:        lval=strtol(strb,&endptr,10); 
                   8286:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8287:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8288:          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);
                   8289:          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);
                   8290:          return 1;
                   8291:        }
1.136     brouard  8292:       }
1.225     brouard  8293:       
1.136     brouard  8294:       s[j][i]=lval;
1.225     brouard  8295:       
1.223     brouard  8296:       /* Date of Interview */
1.136     brouard  8297:       strcpy(line,stra);
                   8298:       cutv(stra, strb,line,' ');
1.169     brouard  8299:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8300:       }
1.169     brouard  8301:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8302:        month=99;
                   8303:        year=9999;
1.136     brouard  8304:       }else{
1.225     brouard  8305:        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);
                   8306:        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);
                   8307:        return 1;
1.136     brouard  8308:       }
                   8309:       anint[j][i]= (double) year; 
                   8310:       mint[j][i]= (double)month; 
                   8311:       strcpy(line,stra);
1.223     brouard  8312:     } /* End loop on waves */
1.225     brouard  8313:     
1.223     brouard  8314:     /* Date of death */
1.136     brouard  8315:     cutv(stra, strb,line,' '); 
1.169     brouard  8316:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8317:     }
1.169     brouard  8318:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8319:       month=99;
                   8320:       year=9999;
                   8321:     }else{
1.141     brouard  8322:       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  8323:       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);
                   8324:       return 1;
1.136     brouard  8325:     }
                   8326:     andc[i]=(double) year; 
                   8327:     moisdc[i]=(double) month; 
                   8328:     strcpy(line,stra);
                   8329:     
1.223     brouard  8330:     /* Date of birth */
1.136     brouard  8331:     cutv(stra, strb,line,' '); 
1.169     brouard  8332:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8333:     }
1.169     brouard  8334:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8335:       month=99;
                   8336:       year=9999;
                   8337:     }else{
1.141     brouard  8338:       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);
                   8339:       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  8340:       return 1;
1.136     brouard  8341:     }
                   8342:     if (year==9999) {
1.141     brouard  8343:       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);
                   8344:       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  8345:       return 1;
                   8346:       
1.136     brouard  8347:     }
                   8348:     annais[i]=(double)(year);
                   8349:     moisnais[i]=(double)(month); 
                   8350:     strcpy(line,stra);
1.225     brouard  8351:     
1.223     brouard  8352:     /* Sample weight */
1.136     brouard  8353:     cutv(stra, strb,line,' '); 
                   8354:     errno=0;
                   8355:     dval=strtod(strb,&endptr); 
                   8356:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8357:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8358:       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  8359:       fflush(ficlog);
                   8360:       return 1;
                   8361:     }
                   8362:     weight[i]=dval; 
                   8363:     strcpy(line,stra);
1.225     brouard  8364:     
1.223     brouard  8365:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8366:       cutv(stra, strb, line, ' '); 
                   8367:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8368:        lval=-1;
1.223     brouard  8369:       }else{
1.225     brouard  8370:        errno=0;
                   8371:        /* what_kind_of_number(strb); */
                   8372:        dval=strtod(strb,&endptr);
                   8373:        /* if(strb != endptr && *endptr == '\0') */
                   8374:        /*   dval=dlval; */
                   8375:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8376:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8377:          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);
                   8378:          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);
                   8379:          return 1;
                   8380:        }
                   8381:        coqvar[iv][i]=dval; 
1.226     brouard  8382:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8383:       }
                   8384:       strcpy(line,stra);
                   8385:     }/* end loop nqv */
1.136     brouard  8386:     
1.223     brouard  8387:     /* Covariate values */
1.136     brouard  8388:     for (j=ncovcol;j>=1;j--){
                   8389:       cutv(stra, strb,line,' '); 
1.223     brouard  8390:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8391:        lval=-1;
1.136     brouard  8392:       }else{
1.225     brouard  8393:        errno=0;
                   8394:        lval=strtol(strb,&endptr,10); 
                   8395:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8396:          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);
                   8397:          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);
                   8398:          return 1;
                   8399:        }
1.136     brouard  8400:       }
                   8401:       if(lval <-1 || lval >1){
1.225     brouard  8402:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8403:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8404:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8405:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8406:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8407:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8408:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8409:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8410:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8411:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8412:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8413:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8414:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8415:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8416:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8417:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8418:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8419:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8420:        return 1;
1.136     brouard  8421:       }
                   8422:       covar[j][i]=(double)(lval);
                   8423:       strcpy(line,stra);
                   8424:     }  
                   8425:     lstra=strlen(stra);
1.225     brouard  8426:     
1.136     brouard  8427:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8428:       stratrunc = &(stra[lstra-9]);
                   8429:       num[i]=atol(stratrunc);
                   8430:     }
                   8431:     else
                   8432:       num[i]=atol(stra);
                   8433:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8434:       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;}*/
                   8435:     
                   8436:     i=i+1;
                   8437:   } /* End loop reading  data */
1.225     brouard  8438:   
1.136     brouard  8439:   *imax=i-1; /* Number of individuals */
                   8440:   fclose(fic);
1.225     brouard  8441:   
1.136     brouard  8442:   return (0);
1.164     brouard  8443:   /* endread: */
1.225     brouard  8444:   printf("Exiting readdata: ");
                   8445:   fclose(fic);
                   8446:   return (1);
1.223     brouard  8447: }
1.126     brouard  8448: 
1.234     brouard  8449: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8450:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8451:   while (*p2 == ' ')
1.234     brouard  8452:     p2++; 
                   8453:   /* while ((*p1++ = *p2++) !=0) */
                   8454:   /*   ; */
                   8455:   /* do */
                   8456:   /*   while (*p2 == ' ') */
                   8457:   /*     p2++; */
                   8458:   /* while (*p1++ == *p2++); */
                   8459:   *stri=p2; 
1.145     brouard  8460: }
                   8461: 
1.235     brouard  8462: int decoderesult ( char resultline[], int nres)
1.230     brouard  8463: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8464: {
1.235     brouard  8465:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8466:   char resultsav[MAXLINE];
1.234     brouard  8467:   int resultmodel[MAXLINE];
                   8468:   int modelresult[MAXLINE];
1.230     brouard  8469:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8470: 
1.234     brouard  8471:   removefirstspace(&resultline);
1.233     brouard  8472:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8473: 
                   8474:   if (strstr(resultline,"v") !=0){
                   8475:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8476:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8477:     return 1;
                   8478:   }
                   8479:   trimbb(resultsav, resultline);
                   8480:   if (strlen(resultsav) >1){
                   8481:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8482:   }
1.253     brouard  8483:   if(j == 0){ /* Resultline but no = */
                   8484:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   8485:     return (0);
                   8486:   }
                   8487:     
1.234     brouard  8488:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8489:     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);
                   8490:     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);
                   8491:   }
                   8492:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8493:     if(nbocc(resultsav,'=') >1){
                   8494:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8495:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8496:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8497:     }else
                   8498:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8499:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8500:     
1.230     brouard  8501:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8502:     Tvarsel[k]=atoi(strc);
                   8503:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8504:     /* cptcovsel++;     */
                   8505:     if (nbocc(stra,'=') >0)
                   8506:       strcpy(resultsav,stra); /* and analyzes it */
                   8507:   }
1.235     brouard  8508:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8509:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8510:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8511:       match=0;
1.236     brouard  8512:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8513:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8514:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8515:          match=1;
                   8516:          break;
                   8517:        }
                   8518:       }
                   8519:       if(match == 0){
                   8520:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8521:       }
                   8522:     }
                   8523:   }
1.235     brouard  8524:   /* Checking for missing or useless values in comparison of current model needs */
                   8525:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8526:     match=0;
1.235     brouard  8527:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8528:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8529:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8530:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8531:          ++match;
                   8532:        }
                   8533:       }
                   8534:     }
                   8535:     if(match == 0){
                   8536:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8537:     }else if(match > 1){
                   8538:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8539:     }
                   8540:   }
1.235     brouard  8541:       
1.234     brouard  8542:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8543:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8544:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8545:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8546:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8547:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8548:   /*    1 0 0 0 */
                   8549:   /*    2 1 0 0 */
                   8550:   /*    3 0 1 0 */ 
                   8551:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8552:   /*    5 0 0 1 */
                   8553:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8554:   /*    7 0 1 1 */
                   8555:   /*    8 1 1 1 */
1.237     brouard  8556:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8557:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8558:   /* V5*age V5 known which value for nres?  */
                   8559:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8560:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8561:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8562:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8563:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8564:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8565:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8566:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8567:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8568:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8569:       k4++;;
                   8570:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8571:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8572:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8573:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8574:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8575:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8576:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8577:       k4q++;;
                   8578:     }
                   8579:   }
1.234     brouard  8580:   
1.235     brouard  8581:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8582:   return (0);
                   8583: }
1.235     brouard  8584: 
1.230     brouard  8585: int decodemodel( char model[], int lastobs)
                   8586:  /**< This routine decodes the model and returns:
1.224     brouard  8587:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8588:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8589:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8590:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8591:        * - cptcovage number of covariates with age*products =2
                   8592:        * - cptcovs number of simple covariates
                   8593:        * - 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
                   8594:        *     which is a new column after the 9 (ncovcol) variables. 
                   8595:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8596:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8597:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8598:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8599:        */
1.136     brouard  8600: {
1.238     brouard  8601:   int i, j, k, ks, v;
1.227     brouard  8602:   int  j1, k1, k2, k3, k4;
1.136     brouard  8603:   char modelsav[80];
1.145     brouard  8604:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8605:   char *strpt;
1.136     brouard  8606: 
1.145     brouard  8607:   /*removespace(model);*/
1.136     brouard  8608:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8609:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8610:     if (strstr(model,"AGE") !=0){
1.192     brouard  8611:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8612:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8613:       return 1;
                   8614:     }
1.141     brouard  8615:     if (strstr(model,"v") !=0){
                   8616:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8617:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8618:       return 1;
                   8619:     }
1.187     brouard  8620:     strcpy(modelsav,model); 
                   8621:     if ((strpt=strstr(model,"age*age")) !=0){
                   8622:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8623:       if(strpt != model){
1.234     brouard  8624:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8625:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8626:  corresponding column of parameters.\n",model);
1.234     brouard  8627:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8628:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8629:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8630:        return 1;
1.225     brouard  8631:       }
1.187     brouard  8632:       nagesqr=1;
                   8633:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8634:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8635:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8636:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8637:       else 
1.234     brouard  8638:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8639:     }else
                   8640:       nagesqr=0;
                   8641:     if (strlen(modelsav) >1){
                   8642:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8643:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8644:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8645:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8646:                     * cst, age and age*age 
                   8647:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8648:       /* including age products which are counted in cptcovage.
                   8649:        * but the covariates which are products must be treated 
                   8650:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8651:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8652:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8653:       
                   8654:       
1.187     brouard  8655:       /*   Design
                   8656:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8657:        *  <          ncovcol=8                >
                   8658:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8659:        *   k=  1    2      3       4     5       6      7        8
                   8660:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8661:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8662:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8663:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8664:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8665:        *  Tage[++cptcovage]=k
                   8666:        *       if products, new covar are created after ncovcol with k1
                   8667:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8668:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8669:        *  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
                   8670:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8671:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8672:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8673:        *  <          ncovcol=8                >
                   8674:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8675:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8676:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8677:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8678:        * p Tprod[1]@2={                         6, 5}
                   8679:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8680:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8681:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8682:        *How to reorganize?
                   8683:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8684:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8685:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8686:        * Struct []
                   8687:        */
1.225     brouard  8688:       
1.187     brouard  8689:       /* This loop fills the array Tvar from the string 'model'.*/
                   8690:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8691:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8692:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8693:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8694:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8695:       /*       k=1 Tvar[1]=2 (from V2) */
                   8696:       /*       k=5 Tvar[5] */
                   8697:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8698:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8699:       /*       } */
1.198     brouard  8700:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8701:       /*
                   8702:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8703:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8704:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8705:       }
1.187     brouard  8706:       cptcovage=0;
                   8707:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8708:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8709:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8710:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8711:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8712:        /*scanf("%d",i);*/
                   8713:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8714:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8715:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8716:            /* covar is not filled and then is empty */
                   8717:            cptcovprod--;
                   8718:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8719:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8720:            Typevar[k]=1;  /* 1 for age product */
                   8721:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8722:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8723:            /*printf("stre=%s ", stre);*/
                   8724:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8725:            cptcovprod--;
                   8726:            cutl(stre,strb,strc,'V');
                   8727:            Tvar[k]=atoi(stre);
                   8728:            Typevar[k]=1;  /* 1 for age product */
                   8729:            cptcovage++;
                   8730:            Tage[cptcovage]=k;
                   8731:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8732:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8733:            cptcovn++;
                   8734:            cptcovprodnoage++;k1++;
                   8735:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8736:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8737:                                                because this model-covariate is a construction we invent a new column
                   8738:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8739:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8740:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8741:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8742:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8743:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8744:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8745:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8746:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8747:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8748:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8749:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8750:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8751:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8752:            for (i=1; i<=lastobs;i++){
                   8753:              /* Computes the new covariate which is a product of
                   8754:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8755:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8756:            }
                   8757:          } /* End age is not in the model */
                   8758:        } /* End if model includes a product */
                   8759:        else { /* no more sum */
                   8760:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8761:          /*  scanf("%d",i);*/
                   8762:          cutl(strd,strc,strb,'V');
                   8763:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8764:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8765:          Tvar[k]=atoi(strd);
                   8766:          Typevar[k]=0;  /* 0 for simple covariates */
                   8767:        }
                   8768:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8769:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8770:                                  scanf("%d",i);*/
1.187     brouard  8771:       } /* end of loop + on total covariates */
                   8772:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8773:   } /* end if strlen(model == 0) */
1.136     brouard  8774:   
                   8775:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8776:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8777:   
1.136     brouard  8778:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8779:      printf("cptcovprod=%d ", cptcovprod);
                   8780:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8781:      scanf("%d ",i);*/
                   8782: 
                   8783: 
1.230     brouard  8784: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8785:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8786: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8787:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8788:    k =           1    2   3     4       5       6      7      8        9
                   8789:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8790:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8791:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8792:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8793:          Tmodelind[combination of covar]=k;
1.225     brouard  8794: */  
                   8795: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8796:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8797:   /* 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  8798:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8799:   printf("Model=%s\n\
                   8800: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8801: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8802: 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);
                   8803:   fprintf(ficlog,"Model=%s\n\
                   8804: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8805: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8806: 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  8807:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8808:   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 */
                   8809:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8810:       Fixed[k]= 0;
                   8811:       Dummy[k]= 0;
1.225     brouard  8812:       ncoveff++;
1.232     brouard  8813:       ncovf++;
1.234     brouard  8814:       nsd++;
                   8815:       modell[k].maintype= FTYPE;
                   8816:       TvarsD[nsd]=Tvar[k];
                   8817:       TvarsDind[nsd]=k;
                   8818:       TvarF[ncovf]=Tvar[k];
                   8819:       TvarFind[ncovf]=k;
                   8820:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8821:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8822:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8823:       Fixed[k]= 0;
                   8824:       Dummy[k]= 0;
                   8825:       ncoveff++;
                   8826:       ncovf++;
                   8827:       modell[k].maintype= FTYPE;
                   8828:       TvarF[ncovf]=Tvar[k];
                   8829:       TvarFind[ncovf]=k;
1.230     brouard  8830:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8831:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8832:     }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  8833:       Fixed[k]= 0;
                   8834:       Dummy[k]= 1;
1.230     brouard  8835:       nqfveff++;
1.234     brouard  8836:       modell[k].maintype= FTYPE;
                   8837:       modell[k].subtype= FQ;
                   8838:       nsq++;
                   8839:       TvarsQ[nsq]=Tvar[k];
                   8840:       TvarsQind[nsq]=k;
1.232     brouard  8841:       ncovf++;
1.234     brouard  8842:       TvarF[ncovf]=Tvar[k];
                   8843:       TvarFind[ncovf]=k;
1.231     brouard  8844:       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  8845:       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  8846:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8847:       Fixed[k]= 1;
                   8848:       Dummy[k]= 0;
1.225     brouard  8849:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8850:       modell[k].maintype= VTYPE;
                   8851:       modell[k].subtype= VD;
                   8852:       nsd++;
                   8853:       TvarsD[nsd]=Tvar[k];
                   8854:       TvarsDind[nsd]=k;
                   8855:       ncovv++; /* Only simple time varying variables */
                   8856:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8857:       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  8858:       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 */
                   8859:       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  8860:       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);
                   8861:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8862:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8863:       Fixed[k]= 1;
                   8864:       Dummy[k]= 1;
                   8865:       nqtveff++;
                   8866:       modell[k].maintype= VTYPE;
                   8867:       modell[k].subtype= VQ;
                   8868:       ncovv++; /* Only simple time varying variables */
                   8869:       nsq++;
                   8870:       TvarsQ[nsq]=Tvar[k];
                   8871:       TvarsQind[nsq]=k;
                   8872:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8873:       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  8874:       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 */
                   8875:       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  8876:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8877:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8878:       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  8879:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8880:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8881:       ncova++;
                   8882:       TvarA[ncova]=Tvar[k];
                   8883:       TvarAind[ncova]=k;
1.231     brouard  8884:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8885:        Fixed[k]= 2;
                   8886:        Dummy[k]= 2;
                   8887:        modell[k].maintype= ATYPE;
                   8888:        modell[k].subtype= APFD;
                   8889:        /* ncoveff++; */
1.227     brouard  8890:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8891:        Fixed[k]= 2;
                   8892:        Dummy[k]= 3;
                   8893:        modell[k].maintype= ATYPE;
                   8894:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8895:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8896:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8897:        Fixed[k]= 3;
                   8898:        Dummy[k]= 2;
                   8899:        modell[k].maintype= ATYPE;
                   8900:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8901:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8902:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8903:        Fixed[k]= 3;
                   8904:        Dummy[k]= 3;
                   8905:        modell[k].maintype= ATYPE;
                   8906:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8907:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8908:       }
                   8909:     }else if (Typevar[k] == 2) {  /* product without age */
                   8910:       k1=Tposprod[k];
                   8911:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8912:        if(Tvard[k1][2] <=ncovcol){
                   8913:          Fixed[k]= 1;
                   8914:          Dummy[k]= 0;
                   8915:          modell[k].maintype= FTYPE;
                   8916:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8917:          ncovf++; /* Fixed variables without age */
                   8918:          TvarF[ncovf]=Tvar[k];
                   8919:          TvarFind[ncovf]=k;
                   8920:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8921:          Fixed[k]= 0;  /* or 2 ?*/
                   8922:          Dummy[k]= 1;
                   8923:          modell[k].maintype= FTYPE;
                   8924:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8925:          ncovf++; /* Varying variables without age */
                   8926:          TvarF[ncovf]=Tvar[k];
                   8927:          TvarFind[ncovf]=k;
                   8928:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8929:          Fixed[k]= 1;
                   8930:          Dummy[k]= 0;
                   8931:          modell[k].maintype= VTYPE;
                   8932:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8933:          ncovv++; /* Varying variables without age */
                   8934:          TvarV[ncovv]=Tvar[k];
                   8935:          TvarVind[ncovv]=k;
                   8936:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8937:          Fixed[k]= 1;
                   8938:          Dummy[k]= 1;
                   8939:          modell[k].maintype= VTYPE;
                   8940:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8941:          ncovv++; /* Varying variables without age */
                   8942:          TvarV[ncovv]=Tvar[k];
                   8943:          TvarVind[ncovv]=k;
                   8944:        }
1.227     brouard  8945:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8946:        if(Tvard[k1][2] <=ncovcol){
                   8947:          Fixed[k]= 0;  /* or 2 ?*/
                   8948:          Dummy[k]= 1;
                   8949:          modell[k].maintype= FTYPE;
                   8950:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8951:          ncovf++; /* Fixed variables without age */
                   8952:          TvarF[ncovf]=Tvar[k];
                   8953:          TvarFind[ncovf]=k;
                   8954:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8955:          Fixed[k]= 1;
                   8956:          Dummy[k]= 1;
                   8957:          modell[k].maintype= VTYPE;
                   8958:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8959:          ncovv++; /* Varying variables without age */
                   8960:          TvarV[ncovv]=Tvar[k];
                   8961:          TvarVind[ncovv]=k;
                   8962:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8963:          Fixed[k]= 1;
                   8964:          Dummy[k]= 1;
                   8965:          modell[k].maintype= VTYPE;
                   8966:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8967:          ncovv++; /* Varying variables without age */
                   8968:          TvarV[ncovv]=Tvar[k];
                   8969:          TvarVind[ncovv]=k;
                   8970:          ncovv++; /* Varying variables without age */
                   8971:          TvarV[ncovv]=Tvar[k];
                   8972:          TvarVind[ncovv]=k;
                   8973:        }
1.227     brouard  8974:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8975:        if(Tvard[k1][2] <=ncovcol){
                   8976:          Fixed[k]= 1;
                   8977:          Dummy[k]= 1;
                   8978:          modell[k].maintype= VTYPE;
                   8979:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8980:          ncovv++; /* Varying variables without age */
                   8981:          TvarV[ncovv]=Tvar[k];
                   8982:          TvarVind[ncovv]=k;
                   8983:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8984:          Fixed[k]= 1;
                   8985:          Dummy[k]= 1;
                   8986:          modell[k].maintype= VTYPE;
                   8987:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8988:          ncovv++; /* Varying variables without age */
                   8989:          TvarV[ncovv]=Tvar[k];
                   8990:          TvarVind[ncovv]=k;
                   8991:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8992:          Fixed[k]= 1;
                   8993:          Dummy[k]= 0;
                   8994:          modell[k].maintype= VTYPE;
                   8995:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8996:          ncovv++; /* Varying variables without age */
                   8997:          TvarV[ncovv]=Tvar[k];
                   8998:          TvarVind[ncovv]=k;
                   8999:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9000:          Fixed[k]= 1;
                   9001:          Dummy[k]= 1;
                   9002:          modell[k].maintype= VTYPE;
                   9003:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   9004:          ncovv++; /* Varying variables without age */
                   9005:          TvarV[ncovv]=Tvar[k];
                   9006:          TvarVind[ncovv]=k;
                   9007:        }
1.227     brouard  9008:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9009:        if(Tvard[k1][2] <=ncovcol){
                   9010:          Fixed[k]= 1;
                   9011:          Dummy[k]= 1;
                   9012:          modell[k].maintype= VTYPE;
                   9013:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   9014:          ncovv++; /* Varying variables without age */
                   9015:          TvarV[ncovv]=Tvar[k];
                   9016:          TvarVind[ncovv]=k;
                   9017:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9018:          Fixed[k]= 1;
                   9019:          Dummy[k]= 1;
                   9020:          modell[k].maintype= VTYPE;
                   9021:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   9022:          ncovv++; /* Varying variables without age */
                   9023:          TvarV[ncovv]=Tvar[k];
                   9024:          TvarVind[ncovv]=k;
                   9025:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9026:          Fixed[k]= 1;
                   9027:          Dummy[k]= 1;
                   9028:          modell[k].maintype= VTYPE;
                   9029:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   9030:          ncovv++; /* Varying variables without age */
                   9031:          TvarV[ncovv]=Tvar[k];
                   9032:          TvarVind[ncovv]=k;
                   9033:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9034:          Fixed[k]= 1;
                   9035:          Dummy[k]= 1;
                   9036:          modell[k].maintype= VTYPE;
                   9037:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   9038:          ncovv++; /* Varying variables without age */
                   9039:          TvarV[ncovv]=Tvar[k];
                   9040:          TvarVind[ncovv]=k;
                   9041:        }
1.227     brouard  9042:       }else{
1.240     brouard  9043:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   9044:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   9045:       } /*end k1*/
1.225     brouard  9046:     }else{
1.226     brouard  9047:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   9048:       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  9049:     }
1.227     brouard  9050:     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  9051:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  9052:     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]);
                   9053:   }
                   9054:   /* Searching for doublons in the model */
                   9055:   for(k1=1; k1<= cptcovt;k1++){
                   9056:     for(k2=1; k2 <k1;k2++){
                   9057:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  9058:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   9059:          if(Tvar[k1]==Tvar[k2]){
                   9060:            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]]);
                   9061:            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);
                   9062:            return(1);
                   9063:          }
                   9064:        }else if (Typevar[k1] ==2){
                   9065:          k3=Tposprod[k1];
                   9066:          k4=Tposprod[k2];
                   9067:          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])) ){
                   9068:            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]]);
                   9069:            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);
                   9070:            return(1);
                   9071:          }
                   9072:        }
1.227     brouard  9073:       }
                   9074:     }
1.225     brouard  9075:   }
                   9076:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   9077:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  9078:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   9079:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  9080:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  9081:   /*endread:*/
1.225     brouard  9082:   printf("Exiting decodemodel: ");
                   9083:   return (1);
1.136     brouard  9084: }
                   9085: 
1.169     brouard  9086: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  9087: {/* Check ages at death */
1.136     brouard  9088:   int i, m;
1.218     brouard  9089:   int firstone=0;
                   9090:   
1.136     brouard  9091:   for (i=1; i<=imx; i++) {
                   9092:     for(m=2; (m<= maxwav); m++) {
                   9093:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   9094:        anint[m][i]=9999;
1.216     brouard  9095:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   9096:          s[m][i]=-1;
1.136     brouard  9097:       }
                   9098:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  9099:        *nberr = *nberr + 1;
1.218     brouard  9100:        if(firstone == 0){
                   9101:          firstone=1;
                   9102:        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);
                   9103:        }
                   9104:        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  9105:        s[m][i]=-1;
                   9106:       }
                   9107:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  9108:        (*nberr)++;
1.136     brouard  9109:        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]); 
                   9110:        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]); 
                   9111:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   9112:       }
                   9113:     }
                   9114:   }
                   9115: 
                   9116:   for (i=1; i<=imx; i++)  {
                   9117:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   9118:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  9119:       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  9120:        if (s[m][i] >= nlstate+1) {
1.169     brouard  9121:          if(agedc[i]>0){
                   9122:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  9123:              agev[m][i]=agedc[i];
1.214     brouard  9124:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  9125:            }else {
1.136     brouard  9126:              if ((int)andc[i]!=9999){
                   9127:                nbwarn++;
                   9128:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   9129:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   9130:                agev[m][i]=-1;
                   9131:              }
                   9132:            }
1.169     brouard  9133:          } /* agedc > 0 */
1.214     brouard  9134:        } /* end if */
1.136     brouard  9135:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   9136:                                 years but with the precision of a month */
                   9137:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   9138:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   9139:            agev[m][i]=1;
                   9140:          else if(agev[m][i] < *agemin){ 
                   9141:            *agemin=agev[m][i];
                   9142:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   9143:          }
                   9144:          else if(agev[m][i] >*agemax){
                   9145:            *agemax=agev[m][i];
1.156     brouard  9146:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  9147:          }
                   9148:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   9149:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  9150:        } /* en if 9*/
1.136     brouard  9151:        else { /* =9 */
1.214     brouard  9152:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  9153:          agev[m][i]=1;
                   9154:          s[m][i]=-1;
                   9155:        }
                   9156:       }
1.214     brouard  9157:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  9158:        agev[m][i]=1;
1.214     brouard  9159:       else{
                   9160:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   9161:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   9162:        agev[m][i]=0;
                   9163:       }
                   9164:     } /* End for lastpass */
                   9165:   }
1.136     brouard  9166:     
                   9167:   for (i=1; i<=imx; i++)  {
                   9168:     for(m=firstpass; (m<=lastpass); m++){
                   9169:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  9170:        (*nberr)++;
1.136     brouard  9171:        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);     
                   9172:        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);     
                   9173:        return 1;
                   9174:       }
                   9175:     }
                   9176:   }
                   9177: 
                   9178:   /*for (i=1; i<=imx; i++){
                   9179:   for (m=firstpass; (m<lastpass); m++){
                   9180:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   9181: }
                   9182: 
                   9183: }*/
                   9184: 
                   9185: 
1.139     brouard  9186:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   9187:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  9188: 
                   9189:   return (0);
1.164     brouard  9190:  /* endread:*/
1.136     brouard  9191:     printf("Exiting calandcheckages: ");
                   9192:     return (1);
                   9193: }
                   9194: 
1.172     brouard  9195: #if defined(_MSC_VER)
                   9196: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   9197: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   9198: //#include "stdafx.h"
                   9199: //#include <stdio.h>
                   9200: //#include <tchar.h>
                   9201: //#include <windows.h>
                   9202: //#include <iostream>
                   9203: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   9204: 
                   9205: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   9206: 
                   9207: BOOL IsWow64()
                   9208: {
                   9209:        BOOL bIsWow64 = FALSE;
                   9210: 
                   9211:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   9212:        //  (HANDLE, PBOOL);
                   9213: 
                   9214:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   9215: 
                   9216:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   9217:        const char funcName[] = "IsWow64Process";
                   9218:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   9219:                GetProcAddress(module, funcName);
                   9220: 
                   9221:        if (NULL != fnIsWow64Process)
                   9222:        {
                   9223:                if (!fnIsWow64Process(GetCurrentProcess(),
                   9224:                        &bIsWow64))
                   9225:                        //throw std::exception("Unknown error");
                   9226:                        printf("Unknown error\n");
                   9227:        }
                   9228:        return bIsWow64 != FALSE;
                   9229: }
                   9230: #endif
1.177     brouard  9231: 
1.191     brouard  9232: void syscompilerinfo(int logged)
1.167     brouard  9233:  {
                   9234:    /* #include "syscompilerinfo.h"*/
1.185     brouard  9235:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   9236:    /* /GS /W3 /Gy
                   9237:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   9238:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   9239:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  9240:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   9241:    */ 
                   9242:    /* 64 bits */
1.185     brouard  9243:    /*
                   9244:      /GS /W3 /Gy
                   9245:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   9246:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   9247:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   9248:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   9249:    /* Optimization are useless and O3 is slower than O2 */
                   9250:    /*
                   9251:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   9252:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   9253:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   9254:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   9255:    */
1.186     brouard  9256:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  9257:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   9258:       /PDB:"visual studio
                   9259:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   9260:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   9261:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   9262:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   9263:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   9264:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   9265:       uiAccess='false'"
                   9266:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   9267:       /NOLOGO /TLBID:1
                   9268:    */
1.177     brouard  9269: #if defined __INTEL_COMPILER
1.178     brouard  9270: #if defined(__GNUC__)
                   9271:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9272: #endif
1.177     brouard  9273: #elif defined(__GNUC__) 
1.179     brouard  9274: #ifndef  __APPLE__
1.174     brouard  9275: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9276: #endif
1.177     brouard  9277:    struct utsname sysInfo;
1.178     brouard  9278:    int cross = CROSS;
                   9279:    if (cross){
                   9280:           printf("Cross-");
1.191     brouard  9281:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9282:    }
1.174     brouard  9283: #endif
                   9284: 
1.171     brouard  9285: #include <stdint.h>
1.178     brouard  9286: 
1.191     brouard  9287:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9288: #if defined(__clang__)
1.191     brouard  9289:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9290: #endif
                   9291: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9292:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9293: #endif
                   9294: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9295:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9296: #endif
                   9297: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9298:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9299: #endif
                   9300: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9301:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9302: #endif
                   9303: #if defined(_MSC_VER)
1.191     brouard  9304:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9305: #endif
                   9306: #if defined(__PGI)
1.191     brouard  9307:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9308: #endif
                   9309: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9310:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9311: #endif
1.191     brouard  9312:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9313:    
1.167     brouard  9314: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9315: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9316:     // Windows (x64 and x86)
1.191     brouard  9317:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9318: #elif __unix__ // all unices, not all compilers
                   9319:     // Unix
1.191     brouard  9320:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9321: #elif __linux__
                   9322:     // linux
1.191     brouard  9323:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9324: #elif __APPLE__
1.174     brouard  9325:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9326:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9327: #endif
                   9328: 
                   9329: /*  __MINGW32__          */
                   9330: /*  __CYGWIN__  */
                   9331: /* __MINGW64__  */
                   9332: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9333: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9334: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9335: /* _WIN64  // Defined for applications for Win64. */
                   9336: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9337: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9338: 
1.167     brouard  9339: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9340:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9341: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9342:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9343: #else
1.191     brouard  9344:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9345: #endif
                   9346: 
1.169     brouard  9347: #if defined(__GNUC__)
                   9348: # if defined(__GNUC_PATCHLEVEL__)
                   9349: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9350:                             + __GNUC_MINOR__ * 100 \
                   9351:                             + __GNUC_PATCHLEVEL__)
                   9352: # else
                   9353: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9354:                             + __GNUC_MINOR__ * 100)
                   9355: # endif
1.174     brouard  9356:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9357:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9358: 
                   9359:    if (uname(&sysInfo) != -1) {
                   9360:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9361:         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  9362:    }
                   9363:    else
                   9364:       perror("uname() error");
1.179     brouard  9365:    //#ifndef __INTEL_COMPILER 
                   9366: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9367:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9368:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9369: #endif
1.169     brouard  9370: #endif
1.172     brouard  9371: 
                   9372:    //   void main()
                   9373:    //   {
1.169     brouard  9374: #if defined(_MSC_VER)
1.174     brouard  9375:    if (IsWow64()){
1.191     brouard  9376:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9377:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9378:    }
                   9379:    else{
1.191     brouard  9380:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9381:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9382:    }
1.172     brouard  9383:    //     printf("\nPress Enter to continue...");
                   9384:    //     getchar();
                   9385:    //   }
                   9386: 
1.169     brouard  9387: #endif
                   9388:    
1.167     brouard  9389: 
1.219     brouard  9390: }
1.136     brouard  9391: 
1.219     brouard  9392: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9393:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9394:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9395:   /* double ftolpl = 1.e-10; */
1.180     brouard  9396:   double age, agebase, agelim;
1.203     brouard  9397:   double tot;
1.180     brouard  9398: 
1.202     brouard  9399:   strcpy(filerespl,"PL_");
                   9400:   strcat(filerespl,fileresu);
                   9401:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9402:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9403:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9404:   }
1.227     brouard  9405:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9406:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9407:   pstamp(ficrespl);
1.203     brouard  9408:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9409:   fprintf(ficrespl,"#Age ");
                   9410:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9411:   fprintf(ficrespl,"\n");
1.180     brouard  9412:   
1.219     brouard  9413:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9414: 
1.219     brouard  9415:   agebase=ageminpar;
                   9416:   agelim=agemaxpar;
1.180     brouard  9417: 
1.227     brouard  9418:   /* i1=pow(2,ncoveff); */
1.234     brouard  9419:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9420:   if (cptcovn < 1){i1=1;}
1.180     brouard  9421: 
1.238     brouard  9422:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9423:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  9424:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  9425:        continue;
1.235     brouard  9426: 
1.238     brouard  9427:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9428:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9429:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9430:       /* k=k+1; */
                   9431:       /* to clean */
                   9432:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9433:       fprintf(ficrespl,"#******");
                   9434:       printf("#******");
                   9435:       fprintf(ficlog,"#******");
                   9436:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9437:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9438:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9439:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9440:       }
                   9441:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9442:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9443:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9444:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9445:       }
                   9446:       fprintf(ficrespl,"******\n");
                   9447:       printf("******\n");
                   9448:       fprintf(ficlog,"******\n");
                   9449:       if(invalidvarcomb[k]){
                   9450:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9451:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9452:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9453:        continue;
                   9454:       }
1.219     brouard  9455: 
1.238     brouard  9456:       fprintf(ficrespl,"#Age ");
                   9457:       for(j=1;j<=cptcoveff;j++) {
                   9458:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9459:       }
                   9460:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9461:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9462:     
1.238     brouard  9463:       for (age=agebase; age<=agelim; age++){
                   9464:        /* for (age=agebase; age<=agebase; age++){ */
                   9465:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9466:        fprintf(ficrespl,"%.0f ",age );
                   9467:        for(j=1;j<=cptcoveff;j++)
                   9468:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9469:        tot=0.;
                   9470:        for(i=1; i<=nlstate;i++){
                   9471:          tot +=  prlim[i][i];
                   9472:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9473:        }
                   9474:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9475:       } /* Age */
                   9476:       /* was end of cptcod */
                   9477:     } /* cptcov */
                   9478:   } /* nres */
1.219     brouard  9479:   return 0;
1.180     brouard  9480: }
                   9481: 
1.218     brouard  9482: 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){
                   9483:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9484:        
                   9485:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9486:    * at any age between ageminpar and agemaxpar
                   9487:         */
1.235     brouard  9488:   int i, j, k, i1, nres=0 ;
1.217     brouard  9489:   /* double ftolpl = 1.e-10; */
                   9490:   double age, agebase, agelim;
                   9491:   double tot;
1.218     brouard  9492:   /* double ***mobaverage; */
                   9493:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9494: 
                   9495:   strcpy(fileresplb,"PLB_");
                   9496:   strcat(fileresplb,fileresu);
                   9497:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9498:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9499:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9500:   }
                   9501:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9502:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9503:   pstamp(ficresplb);
                   9504:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9505:   fprintf(ficresplb,"#Age ");
                   9506:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9507:   fprintf(ficresplb,"\n");
                   9508:   
1.218     brouard  9509:   
                   9510:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9511:   
                   9512:   agebase=ageminpar;
                   9513:   agelim=agemaxpar;
                   9514:   
                   9515:   
1.227     brouard  9516:   i1=pow(2,cptcoveff);
1.218     brouard  9517:   if (cptcovn < 1){i1=1;}
1.227     brouard  9518:   
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 */
1.253     brouard  9521:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  9522:        continue;
                   9523:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9524:       fprintf(ficresplb,"#******");
                   9525:       printf("#******");
                   9526:       fprintf(ficlog,"#******");
                   9527:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9528:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9529:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9530:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9531:       }
                   9532:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9533:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9534:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9535:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9536:       }
                   9537:       fprintf(ficresplb,"******\n");
                   9538:       printf("******\n");
                   9539:       fprintf(ficlog,"******\n");
                   9540:       if(invalidvarcomb[k]){
                   9541:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9542:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9543:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9544:        continue;
                   9545:       }
1.218     brouard  9546:     
1.238     brouard  9547:       fprintf(ficresplb,"#Age ");
                   9548:       for(j=1;j<=cptcoveff;j++) {
                   9549:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9550:       }
                   9551:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9552:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9553:     
                   9554:     
1.238     brouard  9555:       for (age=agebase; age<=agelim; age++){
                   9556:        /* for (age=agebase; age<=agebase; age++){ */
                   9557:        if(mobilavproj > 0){
                   9558:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9559:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9560:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9561:        }else if (mobilavproj == 0){
                   9562:          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);
                   9563:          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);
                   9564:          exit(1);
                   9565:        }else{
                   9566:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9567:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9568:        }
                   9569:        fprintf(ficresplb,"%.0f ",age );
                   9570:        for(j=1;j<=cptcoveff;j++)
                   9571:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9572:        tot=0.;
                   9573:        for(i=1; i<=nlstate;i++){
                   9574:          tot +=  bprlim[i][i];
                   9575:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9576:        }
                   9577:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9578:       } /* Age */
                   9579:       /* was end of cptcod */
1.255     brouard  9580:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  9581:     } /* end of any combination */
                   9582:   } /* end of nres */  
1.218     brouard  9583:   /* hBijx(p, bage, fage); */
                   9584:   /* fclose(ficrespijb); */
                   9585:   
                   9586:   return 0;
1.217     brouard  9587: }
1.218     brouard  9588:  
1.180     brouard  9589: int hPijx(double *p, int bage, int fage){
                   9590:     /*------------- h Pij x at various ages ------------*/
                   9591: 
                   9592:   int stepsize;
                   9593:   int agelim;
                   9594:   int hstepm;
                   9595:   int nhstepm;
1.235     brouard  9596:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9597: 
                   9598:   double agedeb;
                   9599:   double ***p3mat;
                   9600: 
1.201     brouard  9601:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9602:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9603:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9604:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9605:     }
                   9606:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9607:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9608:   
                   9609:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9610:     /*if (stepm<=24) stepsize=2;*/
                   9611: 
                   9612:     agelim=AGESUP;
                   9613:     hstepm=stepsize*YEARM; /* Every year of age */
                   9614:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9615:                
1.180     brouard  9616:     /* hstepm=1;   aff par mois*/
                   9617:     pstamp(ficrespij);
                   9618:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9619:     i1= pow(2,cptcoveff);
1.218     brouard  9620:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9621:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9622:                /*      k=k+1;  */
1.235     brouard  9623:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9624:     for(k=1; k<=i1;k++){
1.253     brouard  9625:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9626:        continue;
1.183     brouard  9627:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9628:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9629:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9630:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9631:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9632:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9633:       }
1.183     brouard  9634:       fprintf(ficrespij,"******\n");
                   9635:       
                   9636:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9637:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9638:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9639:        
                   9640:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9641:        
1.183     brouard  9642:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9643:        oldm=oldms;savm=savms;
1.235     brouard  9644:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9645:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9646:        for(i=1; i<=nlstate;i++)
                   9647:          for(j=1; j<=nlstate+ndeath;j++)
                   9648:            fprintf(ficrespij," %1d-%1d",i,j);
                   9649:        fprintf(ficrespij,"\n");
                   9650:        for (h=0; h<=nhstepm; h++){
                   9651:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9652:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9653:          for(i=1; i<=nlstate;i++)
                   9654:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9655:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9656:          fprintf(ficrespij,"\n");
                   9657:        }
1.183     brouard  9658:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9659:        fprintf(ficrespij,"\n");
                   9660:       }
1.180     brouard  9661:       /*}*/
                   9662:     }
1.218     brouard  9663:     return 0;
1.180     brouard  9664: }
1.218     brouard  9665:  
                   9666:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9667:     /*------------- h Bij x at various ages ------------*/
                   9668: 
                   9669:   int stepsize;
1.218     brouard  9670:   /* int agelim; */
                   9671:        int ageminl;
1.217     brouard  9672:   int hstepm;
                   9673:   int nhstepm;
1.238     brouard  9674:   int h, i, i1, j, k, nres;
1.218     brouard  9675:        
1.217     brouard  9676:   double agedeb;
                   9677:   double ***p3mat;
1.218     brouard  9678:        
                   9679:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9680:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9681:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9682:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9683:   }
                   9684:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9685:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9686:   
                   9687:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9688:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9689:   
1.218     brouard  9690:   /* agelim=AGESUP; */
                   9691:   ageminl=30;
                   9692:   hstepm=stepsize*YEARM; /* Every year of age */
                   9693:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9694:   
                   9695:   /* hstepm=1;   aff par mois*/
                   9696:   pstamp(ficrespijb);
1.255     brouard  9697:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
1.227     brouard  9698:   i1= pow(2,cptcoveff);
1.218     brouard  9699:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9700:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9701:   /*   k=k+1;  */
1.238     brouard  9702:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9703:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  9704:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  9705:        continue;
                   9706:       fprintf(ficrespijb,"\n#****** ");
                   9707:       for(j=1;j<=cptcoveff;j++)
                   9708:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9709:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9710:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9711:       }
                   9712:       fprintf(ficrespijb,"******\n");
                   9713:       if(invalidvarcomb[k]){
                   9714:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9715:        continue;
                   9716:       }
                   9717:       
                   9718:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9719:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9720:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9721:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9722:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9723:        
                   9724:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9725:        
                   9726:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9727:        /* oldm=oldms;savm=savms; */
                   9728:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9729:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9730:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  9731:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  9732:        for(i=1; i<=nlstate;i++)
                   9733:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9734:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9735:        fprintf(ficrespijb,"\n");
1.238     brouard  9736:        for (h=0; h<=nhstepm; h++){
                   9737:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9738:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9739:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9740:          for(i=1; i<=nlstate;i++)
                   9741:            for(j=1; j<=nlstate+ndeath;j++)
                   9742:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9743:          fprintf(ficrespijb,"\n");
                   9744:        }
                   9745:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9746:        fprintf(ficrespijb,"\n");
                   9747:       } /* end age deb */
                   9748:     } /* end combination */
                   9749:   } /* end nres */
1.218     brouard  9750:   return 0;
                   9751:  } /*  hBijx */
1.217     brouard  9752: 
1.180     brouard  9753: 
1.136     brouard  9754: /***********************************************/
                   9755: /**************** Main Program *****************/
                   9756: /***********************************************/
                   9757: 
                   9758: int main(int argc, char *argv[])
                   9759: {
                   9760: #ifdef GSL
                   9761:   const gsl_multimin_fminimizer_type *T;
                   9762:   size_t iteri = 0, it;
                   9763:   int rval = GSL_CONTINUE;
                   9764:   int status = GSL_SUCCESS;
                   9765:   double ssval;
                   9766: #endif
                   9767:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9768:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9769:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9770:   int jj, ll, li, lj, lk;
1.136     brouard  9771:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9772:   int num_filled;
1.136     brouard  9773:   int itimes;
                   9774:   int NDIM=2;
                   9775:   int vpopbased=0;
1.235     brouard  9776:   int nres=0;
1.136     brouard  9777: 
1.164     brouard  9778:   char ca[32], cb[32];
1.136     brouard  9779:   /*  FILE *fichtm; *//* Html File */
                   9780:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9781:   struct stat info;
1.191     brouard  9782:   double agedeb=0.;
1.194     brouard  9783: 
                   9784:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9785:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9786: 
1.165     brouard  9787:   double fret;
1.191     brouard  9788:   double dum=0.; /* Dummy variable */
1.136     brouard  9789:   double ***p3mat;
1.218     brouard  9790:   /* double ***mobaverage; */
1.164     brouard  9791: 
                   9792:   char line[MAXLINE];
1.197     brouard  9793:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9794: 
1.234     brouard  9795:   char  modeltemp[MAXLINE];
1.230     brouard  9796:   char resultline[MAXLINE];
                   9797:   
1.136     brouard  9798:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9799:   char *tok, *val; /* pathtot */
1.136     brouard  9800:   int firstobs=1, lastobs=10;
1.195     brouard  9801:   int c,  h , cpt, c2;
1.191     brouard  9802:   int jl=0;
                   9803:   int i1, j1, jk, stepsize=0;
1.194     brouard  9804:   int count=0;
                   9805: 
1.164     brouard  9806:   int *tab; 
1.136     brouard  9807:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9808:   int backcast=0;
1.136     brouard  9809:   int mobilav=0,popforecast=0;
1.191     brouard  9810:   int hstepm=0, nhstepm=0;
1.136     brouard  9811:   int agemortsup;
                   9812:   float  sumlpop=0.;
                   9813:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9814:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9815: 
1.191     brouard  9816:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9817:   double ftolpl=FTOL;
                   9818:   double **prlim;
1.217     brouard  9819:   double **bprlim;
1.136     brouard  9820:   double ***param; /* Matrix of parameters */
1.251     brouard  9821:   double ***paramstart; /* Matrix of starting parameter values */
                   9822:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  9823:   double **matcov; /* Matrix of covariance */
1.203     brouard  9824:   double **hess; /* Hessian matrix */
1.136     brouard  9825:   double ***delti3; /* Scale */
                   9826:   double *delti; /* Scale */
                   9827:   double ***eij, ***vareij;
                   9828:   double **varpl; /* Variances of prevalence limits by age */
                   9829:   double *epj, vepp;
1.164     brouard  9830: 
1.136     brouard  9831:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9832:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9833: 
1.136     brouard  9834:   double **ximort;
1.145     brouard  9835:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9836:   int *dcwave;
                   9837: 
1.164     brouard  9838:   char z[1]="c";
1.136     brouard  9839: 
                   9840:   /*char  *strt;*/
                   9841:   char strtend[80];
1.126     brouard  9842: 
1.164     brouard  9843: 
1.126     brouard  9844: /*   setlocale (LC_ALL, ""); */
                   9845: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9846: /*   textdomain (PACKAGE); */
                   9847: /*   setlocale (LC_CTYPE, ""); */
                   9848: /*   setlocale (LC_MESSAGES, ""); */
                   9849: 
                   9850:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9851:   rstart_time = time(NULL);  
                   9852:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9853:   start_time = *localtime(&rstart_time);
1.126     brouard  9854:   curr_time=start_time;
1.157     brouard  9855:   /*tml = *localtime(&start_time.tm_sec);*/
                   9856:   /* strcpy(strstart,asctime(&tml)); */
                   9857:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9858: 
                   9859: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9860: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9861: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9862: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9863: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9864: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9865: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9866: /*   strt=asctime(&tmg); */
                   9867: /*   printf("Time(after) =%s",strstart);  */
                   9868: /*  (void) time (&time_value);
                   9869: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9870: *  tm = *localtime(&time_value);
                   9871: *  strstart=asctime(&tm);
                   9872: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9873: */
                   9874: 
                   9875:   nberr=0; /* Number of errors and warnings */
                   9876:   nbwarn=0;
1.184     brouard  9877: #ifdef WIN32
                   9878:   _getcwd(pathcd, size);
                   9879: #else
1.126     brouard  9880:   getcwd(pathcd, size);
1.184     brouard  9881: #endif
1.191     brouard  9882:   syscompilerinfo(0);
1.196     brouard  9883:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9884:   if(argc <=1){
                   9885:     printf("\nEnter the parameter file name: ");
1.205     brouard  9886:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9887:       printf("ERROR Empty parameter file name\n");
                   9888:       goto end;
                   9889:     }
1.126     brouard  9890:     i=strlen(pathr);
                   9891:     if(pathr[i-1]=='\n')
                   9892:       pathr[i-1]='\0';
1.156     brouard  9893:     i=strlen(pathr);
1.205     brouard  9894:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9895:       pathr[i-1]='\0';
1.205     brouard  9896:     }
                   9897:     i=strlen(pathr);
                   9898:     if( i==0 ){
                   9899:       printf("ERROR Empty parameter file name\n");
                   9900:       goto end;
                   9901:     }
                   9902:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9903:       printf("Pathr |%s|\n",pathr);
                   9904:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9905:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9906:       strcpy (pathtot, val);
                   9907:       if(pathr[0] == '\0') break; /* Dirty */
                   9908:     }
                   9909:   }
                   9910:   else{
                   9911:     strcpy(pathtot,argv[1]);
                   9912:   }
                   9913:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9914:   /*cygwin_split_path(pathtot,path,optionfile);
                   9915:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9916:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9917: 
                   9918:   /* Split argv[0], imach program to get pathimach */
                   9919:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9920:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9921:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9922:  /*   strcpy(pathimach,argv[0]); */
                   9923:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9924:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9925:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9926: #ifdef WIN32
                   9927:   _chdir(path); /* Can be a relative path */
                   9928:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9929: #else
1.126     brouard  9930:   chdir(path); /* Can be a relative path */
1.184     brouard  9931:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9932: #endif
                   9933:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9934:   strcpy(command,"mkdir ");
                   9935:   strcat(command,optionfilefiname);
                   9936:   if((outcmd=system(command)) != 0){
1.169     brouard  9937:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9938:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9939:     /* fclose(ficlog); */
                   9940: /*     exit(1); */
                   9941:   }
                   9942: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9943: /*     perror("mkdir"); */
                   9944: /*   } */
                   9945: 
                   9946:   /*-------- arguments in the command line --------*/
                   9947: 
1.186     brouard  9948:   /* Main Log file */
1.126     brouard  9949:   strcat(filelog, optionfilefiname);
                   9950:   strcat(filelog,".log");    /* */
                   9951:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9952:     printf("Problem with logfile %s\n",filelog);
                   9953:     goto end;
                   9954:   }
                   9955:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9956:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9957:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9958:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9959:  path=%s \n\
                   9960:  optionfile=%s\n\
                   9961:  optionfilext=%s\n\
1.156     brouard  9962:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9963: 
1.197     brouard  9964:   syscompilerinfo(1);
1.167     brouard  9965: 
1.126     brouard  9966:   printf("Local time (at start):%s",strstart);
                   9967:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9968:   fflush(ficlog);
                   9969: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9970: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9971: 
                   9972:   /* */
                   9973:   strcpy(fileres,"r");
                   9974:   strcat(fileres, optionfilefiname);
1.201     brouard  9975:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9976:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9977:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9978: 
1.186     brouard  9979:   /* Main ---------arguments file --------*/
1.126     brouard  9980: 
                   9981:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9982:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9983:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9984:     fflush(ficlog);
1.149     brouard  9985:     /* goto end; */
                   9986:     exit(70); 
1.126     brouard  9987:   }
                   9988: 
                   9989: 
                   9990: 
                   9991:   strcpy(filereso,"o");
1.201     brouard  9992:   strcat(filereso,fileresu);
1.126     brouard  9993:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9994:     printf("Problem with Output resultfile: %s\n", filereso);
                   9995:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9996:     fflush(ficlog);
                   9997:     goto end;
                   9998:   }
                   9999: 
                   10000:   /* Reads comments: lines beginning with '#' */
                   10001:   numlinepar=0;
1.197     brouard  10002: 
                   10003:     /* First parameter line */
                   10004:   while(fgets(line, MAXLINE, ficpar)) {
                   10005:     /* If line starts with a # it is a comment */
                   10006:     if (line[0] == '#') {
                   10007:       numlinepar++;
                   10008:       fputs(line,stdout);
                   10009:       fputs(line,ficparo);
                   10010:       fputs(line,ficlog);
                   10011:       continue;
                   10012:     }else
                   10013:       break;
                   10014:   }
                   10015:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   10016:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   10017:     if (num_filled != 5) {
                   10018:       printf("Should be 5 parameters\n");
                   10019:     }
1.126     brouard  10020:     numlinepar++;
1.197     brouard  10021:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   10022:   }
                   10023:   /* Second parameter line */
                   10024:   while(fgets(line, MAXLINE, ficpar)) {
                   10025:     /* If line starts with a # it is a comment */
                   10026:     if (line[0] == '#') {
                   10027:       numlinepar++;
                   10028:       fputs(line,stdout);
                   10029:       fputs(line,ficparo);
                   10030:       fputs(line,ficlog);
                   10031:       continue;
                   10032:     }else
                   10033:       break;
                   10034:   }
1.223     brouard  10035:   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", \
                   10036:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   10037:     if (num_filled != 11) {
                   10038:       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  10039:       printf("but line=%s\n",line);
1.197     brouard  10040:     }
1.223     brouard  10041:     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  10042:   }
1.203     brouard  10043:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  10044:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  10045:   /* Third parameter line */
                   10046:   while(fgets(line, MAXLINE, ficpar)) {
                   10047:     /* If line starts with a # it is a comment */
                   10048:     if (line[0] == '#') {
                   10049:       numlinepar++;
                   10050:       fputs(line,stdout);
                   10051:       fputs(line,ficparo);
                   10052:       fputs(line,ficlog);
                   10053:       continue;
                   10054:     }else
                   10055:       break;
                   10056:   }
1.201     brouard  10057:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   10058:     if (num_filled == 0)
                   10059:             model[0]='\0';
                   10060:     else if (num_filled != 1){
1.197     brouard  10061:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   10062:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   10063:       model[0]='\0';
                   10064:       goto end;
                   10065:     }
                   10066:     else{
                   10067:       if (model[0]=='+'){
                   10068:        for(i=1; i<=strlen(model);i++)
                   10069:          modeltemp[i-1]=model[i];
1.201     brouard  10070:        strcpy(model,modeltemp); 
1.197     brouard  10071:       }
                   10072:     }
1.199     brouard  10073:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  10074:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  10075:   }
                   10076:   /* 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); */
                   10077:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   10078:   /* 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  10079:   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);
                   10080:   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  10081:   fflush(ficlog);
1.190     brouard  10082:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   10083:   if(model[0]=='#'){
1.187     brouard  10084:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   10085:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   10086:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   10087:     if(mle != -1){
                   10088:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   10089:       exit(1);
                   10090:     }
                   10091:   }
1.126     brouard  10092:   while((c=getc(ficpar))=='#' && c!= EOF){
                   10093:     ungetc(c,ficpar);
                   10094:     fgets(line, MAXLINE, ficpar);
                   10095:     numlinepar++;
1.195     brouard  10096:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   10097:       z[0]=line[1];
                   10098:     }
                   10099:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  10100:     fputs(line, stdout);
                   10101:     //puts(line);
1.126     brouard  10102:     fputs(line,ficparo);
                   10103:     fputs(line,ficlog);
                   10104:   }
                   10105:   ungetc(c,ficpar);
                   10106: 
                   10107:    
1.145     brouard  10108:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  10109:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  10110:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  10111:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  10112:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   10113:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   10114:      v1+v2*age+v2*v3 makes cptcovn = 3
                   10115:   */
                   10116:   if (strlen(model)>1) 
1.187     brouard  10117:     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  10118:   else
1.187     brouard  10119:     ncovmodel=2; /* Constant and age */
1.133     brouard  10120:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   10121:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  10122:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   10123:     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);
                   10124:     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);
                   10125:     fflush(stdout);
                   10126:     fclose (ficlog);
                   10127:     goto end;
                   10128:   }
1.126     brouard  10129:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   10130:   delti=delti3[1][1];
                   10131:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   10132:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  10133: /* We could also provide initial parameters values giving by simple logistic regression 
                   10134:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   10135:       /* for(i=1;i<nlstate;i++){ */
                   10136:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   10137:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   10138:       /* } */
1.126     brouard  10139:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  10140:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   10141:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  10142:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   10143:     fclose (ficparo);
                   10144:     fclose (ficlog);
                   10145:     goto end;
                   10146:     exit(0);
1.220     brouard  10147:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  10148:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  10149:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   10150:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  10151:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   10152:     matcov=matrix(1,npar,1,npar);
1.203     brouard  10153:     hess=matrix(1,npar,1,npar);
1.220     brouard  10154:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  10155:     /* Read guessed parameters */
1.126     brouard  10156:     /* Reads comments: lines beginning with '#' */
                   10157:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10158:       ungetc(c,ficpar);
                   10159:       fgets(line, MAXLINE, ficpar);
                   10160:       numlinepar++;
1.141     brouard  10161:       fputs(line,stdout);
1.126     brouard  10162:       fputs(line,ficparo);
                   10163:       fputs(line,ficlog);
                   10164:     }
                   10165:     ungetc(c,ficpar);
                   10166:     
                   10167:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  10168:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  10169:     for(i=1; i <=nlstate; i++){
1.234     brouard  10170:       j=0;
1.126     brouard  10171:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  10172:        if(jj==i) continue;
                   10173:        j++;
                   10174:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   10175:        if ((i1 != i) || (j1 != jj)){
                   10176:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  10177: It might be a problem of design; if ncovcol and the model are correct\n \
                   10178: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  10179:          exit(1);
                   10180:        }
                   10181:        fprintf(ficparo,"%1d%1d",i1,j1);
                   10182:        if(mle==1)
                   10183:          printf("%1d%1d",i,jj);
                   10184:        fprintf(ficlog,"%1d%1d",i,jj);
                   10185:        for(k=1; k<=ncovmodel;k++){
                   10186:          fscanf(ficpar," %lf",&param[i][j][k]);
                   10187:          if(mle==1){
                   10188:            printf(" %lf",param[i][j][k]);
                   10189:            fprintf(ficlog," %lf",param[i][j][k]);
                   10190:          }
                   10191:          else
                   10192:            fprintf(ficlog," %lf",param[i][j][k]);
                   10193:          fprintf(ficparo," %lf",param[i][j][k]);
                   10194:        }
                   10195:        fscanf(ficpar,"\n");
                   10196:        numlinepar++;
                   10197:        if(mle==1)
                   10198:          printf("\n");
                   10199:        fprintf(ficlog,"\n");
                   10200:        fprintf(ficparo,"\n");
1.126     brouard  10201:       }
                   10202:     }  
                   10203:     fflush(ficlog);
1.234     brouard  10204:     
1.251     brouard  10205:     /* Reads parameters values */
1.126     brouard  10206:     p=param[1][1];
1.251     brouard  10207:     pstart=paramstart[1][1];
1.126     brouard  10208:     
                   10209:     /* Reads comments: lines beginning with '#' */
                   10210:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10211:       ungetc(c,ficpar);
                   10212:       fgets(line, MAXLINE, ficpar);
                   10213:       numlinepar++;
1.141     brouard  10214:       fputs(line,stdout);
1.126     brouard  10215:       fputs(line,ficparo);
                   10216:       fputs(line,ficlog);
                   10217:     }
                   10218:     ungetc(c,ficpar);
                   10219: 
                   10220:     for(i=1; i <=nlstate; i++){
                   10221:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  10222:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   10223:        if ( (i1-i) * (j1-j) != 0){
                   10224:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   10225:          exit(1);
                   10226:        }
                   10227:        printf("%1d%1d",i,j);
                   10228:        fprintf(ficparo,"%1d%1d",i1,j1);
                   10229:        fprintf(ficlog,"%1d%1d",i1,j1);
                   10230:        for(k=1; k<=ncovmodel;k++){
                   10231:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   10232:          printf(" %le",delti3[i][j][k]);
                   10233:          fprintf(ficparo," %le",delti3[i][j][k]);
                   10234:          fprintf(ficlog," %le",delti3[i][j][k]);
                   10235:        }
                   10236:        fscanf(ficpar,"\n");
                   10237:        numlinepar++;
                   10238:        printf("\n");
                   10239:        fprintf(ficparo,"\n");
                   10240:        fprintf(ficlog,"\n");
1.126     brouard  10241:       }
                   10242:     }
                   10243:     fflush(ficlog);
1.234     brouard  10244:     
1.145     brouard  10245:     /* Reads covariance matrix */
1.126     brouard  10246:     delti=delti3[1][1];
1.220     brouard  10247:                
                   10248:                
1.126     brouard  10249:     /* 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  10250:                
1.126     brouard  10251:     /* Reads comments: lines beginning with '#' */
                   10252:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10253:       ungetc(c,ficpar);
                   10254:       fgets(line, MAXLINE, ficpar);
                   10255:       numlinepar++;
1.141     brouard  10256:       fputs(line,stdout);
1.126     brouard  10257:       fputs(line,ficparo);
                   10258:       fputs(line,ficlog);
                   10259:     }
                   10260:     ungetc(c,ficpar);
1.220     brouard  10261:                
1.126     brouard  10262:     matcov=matrix(1,npar,1,npar);
1.203     brouard  10263:     hess=matrix(1,npar,1,npar);
1.131     brouard  10264:     for(i=1; i <=npar; i++)
                   10265:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  10266:                
1.194     brouard  10267:     /* Scans npar lines */
1.126     brouard  10268:     for(i=1; i <=npar; i++){
1.226     brouard  10269:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  10270:       if(count != 3){
1.226     brouard  10271:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10272: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10273: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10274:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10275: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10276: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10277:        exit(1);
1.220     brouard  10278:       }else{
1.226     brouard  10279:        if(mle==1)
                   10280:          printf("%1d%1d%d",i1,j1,jk);
                   10281:       }
                   10282:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10283:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10284:       for(j=1; j <=i; j++){
1.226     brouard  10285:        fscanf(ficpar," %le",&matcov[i][j]);
                   10286:        if(mle==1){
                   10287:          printf(" %.5le",matcov[i][j]);
                   10288:        }
                   10289:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10290:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10291:       }
                   10292:       fscanf(ficpar,"\n");
                   10293:       numlinepar++;
                   10294:       if(mle==1)
1.220     brouard  10295:                                printf("\n");
1.126     brouard  10296:       fprintf(ficlog,"\n");
                   10297:       fprintf(ficparo,"\n");
                   10298:     }
1.194     brouard  10299:     /* End of read covariance matrix npar lines */
1.126     brouard  10300:     for(i=1; i <=npar; i++)
                   10301:       for(j=i+1;j<=npar;j++)
1.226     brouard  10302:        matcov[i][j]=matcov[j][i];
1.126     brouard  10303:     
                   10304:     if(mle==1)
                   10305:       printf("\n");
                   10306:     fprintf(ficlog,"\n");
                   10307:     
                   10308:     fflush(ficlog);
                   10309:     
                   10310:     /*-------- Rewriting parameter file ----------*/
                   10311:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10312:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10313:     strcat(rfileres,".");    /* */
                   10314:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10315:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10316:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10317:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10318:     }
                   10319:     fprintf(ficres,"#%s\n",version);
                   10320:   }    /* End of mle != -3 */
1.218     brouard  10321:   
1.186     brouard  10322:   /*  Main data
                   10323:    */
1.126     brouard  10324:   n= lastobs;
                   10325:   num=lvector(1,n);
                   10326:   moisnais=vector(1,n);
                   10327:   annais=vector(1,n);
                   10328:   moisdc=vector(1,n);
                   10329:   andc=vector(1,n);
1.220     brouard  10330:   weight=vector(1,n);
1.126     brouard  10331:   agedc=vector(1,n);
                   10332:   cod=ivector(1,n);
1.220     brouard  10333:   for(i=1;i<=n;i++){
1.234     brouard  10334:     num[i]=0;
                   10335:     moisnais[i]=0;
                   10336:     annais[i]=0;
                   10337:     moisdc[i]=0;
                   10338:     andc[i]=0;
                   10339:     agedc[i]=0;
                   10340:     cod[i]=0;
                   10341:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10342:   }
1.126     brouard  10343:   mint=matrix(1,maxwav,1,n);
                   10344:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10345:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10346:   tab=ivector(1,NCOVMAX);
1.144     brouard  10347:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10348:   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  10349: 
1.136     brouard  10350:   /* Reads data from file datafile */
                   10351:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10352:     goto end;
                   10353: 
                   10354:   /* Calculation of the number of parameters from char model */
1.234     brouard  10355:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10356:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10357:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10358:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10359:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10360:   */
                   10361:   
                   10362:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10363:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10364:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10365:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10366:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10367:   TvarF=ivector(1,NCOVMAX); /*  */
                   10368:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10369:   TvarV=ivector(1,NCOVMAX); /*  */
                   10370:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10371:   TvarA=ivector(1,NCOVMAX); /*  */
                   10372:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10373:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10374:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10375:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10376:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10377:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10378:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10379:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10380:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10381: 
1.230     brouard  10382:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10383:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10384:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10385:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10386:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10387:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10388:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10389:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10390:   */
                   10391:   /* For model-covariate k tells which data-covariate to use but
                   10392:     because this model-covariate is a construction we invent a new column
                   10393:     ncovcol + k1
                   10394:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10395:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10396:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10397:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10398:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10399:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10400:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10401:   */
1.145     brouard  10402:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10403:   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  10404:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10405:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10406:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10407:                         4 covariates (3 plus signs)
                   10408:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10409:                      */  
1.230     brouard  10410:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10411:                                * individual dummy, fixed or varying:
                   10412:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10413:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10414:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10415:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10416:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10417:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10418:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10419:                                * individual quantitative, fixed or varying:
                   10420:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10421:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10422:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10423: /* Main decodemodel */
                   10424: 
1.187     brouard  10425: 
1.223     brouard  10426:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10427:     goto end;
                   10428: 
1.137     brouard  10429:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10430:     nbwarn++;
                   10431:     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); 
                   10432:     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); 
                   10433:   }
1.136     brouard  10434:     /*  if(mle==1){*/
1.137     brouard  10435:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10436:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10437:   }
                   10438: 
                   10439:     /*-calculation of age at interview from date of interview and age at death -*/
                   10440:   agev=matrix(1,maxwav,1,imx);
                   10441: 
                   10442:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10443:     goto end;
                   10444: 
1.126     brouard  10445: 
1.136     brouard  10446:   agegomp=(int)agemin;
                   10447:   free_vector(moisnais,1,n);
                   10448:   free_vector(annais,1,n);
1.126     brouard  10449:   /* free_matrix(mint,1,maxwav,1,n);
                   10450:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10451:   /* free_vector(moisdc,1,n); */
                   10452:   /* free_vector(andc,1,n); */
1.145     brouard  10453:   /* */
                   10454:   
1.126     brouard  10455:   wav=ivector(1,imx);
1.214     brouard  10456:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10457:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10458:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10459:   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.*/
                   10460:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10461:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10462:    
                   10463:   /* Concatenates waves */
1.214     brouard  10464:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10465:      Death is a valid wave (if date is known).
                   10466:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10467:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10468:      and mw[mi+1][i]. dh depends on stepm.
                   10469:   */
                   10470: 
1.126     brouard  10471:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  10472:   /* Concatenates waves */
1.145     brouard  10473:  
1.215     brouard  10474:   free_vector(moisdc,1,n);
                   10475:   free_vector(andc,1,n);
                   10476: 
1.126     brouard  10477:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10478:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10479:   ncodemax[1]=1;
1.145     brouard  10480:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10481:   cptcoveff=0;
1.220     brouard  10482:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10483:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10484:   }
                   10485:   
                   10486:   ncovcombmax=pow(2,cptcoveff);
                   10487:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10488:   for(i=1;i<ncovcombmax;i++)
                   10489:     invalidvarcomb[i]=0;
                   10490:   
1.211     brouard  10491:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10492:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10493:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10494:   
1.200     brouard  10495:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10496:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10497:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10498:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10499:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10500:    * (currently 0 or 1) in the data.
                   10501:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10502:    * corresponding modality (h,j).
                   10503:    */
                   10504: 
1.145     brouard  10505:   h=0;
                   10506:   /*if (cptcovn > 0) */
1.126     brouard  10507:   m=pow(2,cptcoveff);
                   10508:  
1.144     brouard  10509:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10510:           * For k=4 covariates, h goes from 1 to m=2**k
                   10511:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10512:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10513:           *     h\k   1     2     3     4
1.143     brouard  10514:           *______________________________  
                   10515:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10516:           *     2     2     1     1     1
                   10517:           *     3 i=2 1     2     1     1
                   10518:           *     4     2     2     1     1
                   10519:           *     5 i=3 1 i=2 1     2     1
                   10520:           *     6     2     1     2     1
                   10521:           *     7 i=4 1     2     2     1
                   10522:           *     8     2     2     2     1
1.197     brouard  10523:           *     9 i=5 1 i=3 1 i=2 1     2
                   10524:           *    10     2     1     1     2
                   10525:           *    11 i=6 1     2     1     2
                   10526:           *    12     2     2     1     2
                   10527:           *    13 i=7 1 i=4 1     2     2    
                   10528:           *    14     2     1     2     2
                   10529:           *    15 i=8 1     2     2     2
                   10530:           *    16     2     2     2     2
1.143     brouard  10531:           */
1.212     brouard  10532:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10533:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10534:      * and the value of each covariate?
                   10535:      * V1=1, V2=1, V3=2, V4=1 ?
                   10536:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10537:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10538:      * In order to get the real value in the data, we use nbcode
                   10539:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10540:      * We are keeping this crazy system in order to be able (in the future?) 
                   10541:      * to have more than 2 values (0 or 1) for a covariate.
                   10542:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10543:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10544:      *              bbbbbbbb
                   10545:      *              76543210     
                   10546:      *   h-1        00000101 (6-1=5)
1.219     brouard  10547:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10548:      *           &
                   10549:      *     1        00000001 (1)
1.219     brouard  10550:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10551:      *          +1= 00000001 =1 
1.211     brouard  10552:      *
                   10553:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10554:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10555:      *    >>k'            11
                   10556:      *          &   00000001
                   10557:      *            = 00000001
                   10558:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10559:      * Reverse h=6 and m=16?
                   10560:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10561:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10562:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10563:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10564:      * V3=decodtabm(14,3,2**4)=2
                   10565:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10566:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10567:      *          &1 000000001
                   10568:      *           = 000000001
                   10569:      *         +1= 000000010 =2
                   10570:      *                  2211
                   10571:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10572:      *                  V3=2
1.220     brouard  10573:                 * codtabm and decodtabm are identical
1.211     brouard  10574:      */
                   10575: 
1.145     brouard  10576: 
                   10577:  free_ivector(Ndum,-1,NCOVMAX);
                   10578: 
                   10579: 
1.126     brouard  10580:     
1.186     brouard  10581:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10582:   strcpy(optionfilegnuplot,optionfilefiname);
                   10583:   if(mle==-3)
1.201     brouard  10584:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10585:   strcat(optionfilegnuplot,".gp");
                   10586: 
                   10587:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10588:     printf("Problem with file %s",optionfilegnuplot);
                   10589:   }
                   10590:   else{
1.204     brouard  10591:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10592:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10593:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10594:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10595:   }
                   10596:   /*  fclose(ficgp);*/
1.186     brouard  10597: 
                   10598: 
                   10599:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10600: 
                   10601:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10602:   if(mle==-3)
1.201     brouard  10603:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10604:   strcat(optionfilehtm,".htm");
                   10605:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10606:     printf("Problem with %s \n",optionfilehtm);
                   10607:     exit(0);
1.126     brouard  10608:   }
                   10609: 
                   10610:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10611:   strcat(optionfilehtmcov,"-cov.htm");
                   10612:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10613:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10614:   }
                   10615:   else{
                   10616:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10617: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10618: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10619:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10620:   }
                   10621: 
1.213     brouard  10622:   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  10623: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10624: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10625: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10626: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10627: \n\
                   10628: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10629:  <ul><li><h4>Parameter files</h4>\n\
                   10630:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10631:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10632:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10633:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10634:  - Date and time at start: %s</ul>\n",\
                   10635:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10636:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10637:          fileres,fileres,\
                   10638:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10639:   fflush(fichtm);
                   10640: 
                   10641:   strcpy(pathr,path);
                   10642:   strcat(pathr,optionfilefiname);
1.184     brouard  10643: #ifdef WIN32
                   10644:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10645: #else
1.126     brouard  10646:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10647: #endif
                   10648:          
1.126     brouard  10649:   
1.220     brouard  10650:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10651:                 and for any valid combination of covariates
1.126     brouard  10652:      and prints on file fileres'p'. */
1.251     brouard  10653:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  10654:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10655: 
                   10656:   fprintf(fichtm,"\n");
                   10657:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10658: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10659: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10660:          imx,agemin,agemax,jmin,jmax,jmean);
                   10661:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10662:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10663:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10664:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10665:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10666: 
1.126     brouard  10667:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10668:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10669:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10670: 
                   10671:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10672:   /* For mortality only */
1.126     brouard  10673:   if (mle==-3){
1.136     brouard  10674:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  10675:     for(i=1;i<=NDIM;i++)
                   10676:       for(j=1;j<=NDIM;j++)
                   10677:        ximort[i][j]=0.;
1.186     brouard  10678:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10679:     cens=ivector(1,n);
                   10680:     ageexmed=vector(1,n);
                   10681:     agecens=vector(1,n);
                   10682:     dcwave=ivector(1,n);
1.223     brouard  10683:                
1.126     brouard  10684:     for (i=1; i<=imx; i++){
                   10685:       dcwave[i]=-1;
                   10686:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10687:        if (s[m][i]>nlstate) {
                   10688:          dcwave[i]=m;
                   10689:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10690:          break;
                   10691:        }
1.126     brouard  10692:     }
1.226     brouard  10693:     
1.126     brouard  10694:     for (i=1; i<=imx; i++) {
                   10695:       if (wav[i]>0){
1.226     brouard  10696:        ageexmed[i]=agev[mw[1][i]][i];
                   10697:        j=wav[i];
                   10698:        agecens[i]=1.; 
                   10699:        
                   10700:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10701:          agecens[i]=agev[mw[j][i]][i];
                   10702:          cens[i]= 1;
                   10703:        }else if (ageexmed[i]< 1) 
                   10704:          cens[i]= -1;
                   10705:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10706:          cens[i]=0 ;
1.126     brouard  10707:       }
                   10708:       else cens[i]=-1;
                   10709:     }
                   10710:     
                   10711:     for (i=1;i<=NDIM;i++) {
                   10712:       for (j=1;j<=NDIM;j++)
1.226     brouard  10713:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10714:     }
                   10715:     
1.145     brouard  10716:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10717:     /*printf("%lf %lf", p[1], p[2]);*/
                   10718:     
                   10719:     
1.136     brouard  10720: #ifdef GSL
                   10721:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10722: #else
1.126     brouard  10723:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10724: #endif
1.201     brouard  10725:     strcpy(filerespow,"POW-MORT_"); 
                   10726:     strcat(filerespow,fileresu);
1.126     brouard  10727:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10728:       printf("Problem with resultfile: %s\n", filerespow);
                   10729:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10730:     }
1.136     brouard  10731: #ifdef GSL
                   10732:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10733: #else
1.126     brouard  10734:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10735: #endif
1.126     brouard  10736:     /*  for (i=1;i<=nlstate;i++)
                   10737:        for(j=1;j<=nlstate+ndeath;j++)
                   10738:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10739:     */
                   10740:     fprintf(ficrespow,"\n");
1.136     brouard  10741: #ifdef GSL
                   10742:     /* gsl starts here */ 
                   10743:     T = gsl_multimin_fminimizer_nmsimplex;
                   10744:     gsl_multimin_fminimizer *sfm = NULL;
                   10745:     gsl_vector *ss, *x;
                   10746:     gsl_multimin_function minex_func;
                   10747: 
                   10748:     /* Initial vertex size vector */
                   10749:     ss = gsl_vector_alloc (NDIM);
                   10750:     
                   10751:     if (ss == NULL){
                   10752:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10753:     }
                   10754:     /* Set all step sizes to 1 */
                   10755:     gsl_vector_set_all (ss, 0.001);
                   10756: 
                   10757:     /* Starting point */
1.126     brouard  10758:     
1.136     brouard  10759:     x = gsl_vector_alloc (NDIM);
                   10760:     
                   10761:     if (x == NULL){
                   10762:       gsl_vector_free(ss);
                   10763:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10764:     }
                   10765:   
                   10766:     /* Initialize method and iterate */
                   10767:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10768:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10769:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10770:     gsl_vector_set(x, 0, p[1]);
                   10771:     gsl_vector_set(x, 1, p[2]);
                   10772: 
                   10773:     minex_func.f = &gompertz_f;
                   10774:     minex_func.n = NDIM;
                   10775:     minex_func.params = (void *)&p; /* ??? */
                   10776:     
                   10777:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10778:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10779:     
                   10780:     printf("Iterations beginning .....\n\n");
                   10781:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10782: 
                   10783:     iteri=0;
                   10784:     while (rval == GSL_CONTINUE){
                   10785:       iteri++;
                   10786:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10787:       
                   10788:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10789:       fflush(0);
                   10790:       
                   10791:       if (status) 
                   10792:         break;
                   10793:       
                   10794:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10795:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10796:       
                   10797:       if (rval == GSL_SUCCESS)
                   10798:         printf ("converged to a local maximum at\n");
                   10799:       
                   10800:       printf("%5d ", iteri);
                   10801:       for (it = 0; it < NDIM; it++){
                   10802:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10803:       }
                   10804:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10805:     }
                   10806:     
                   10807:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10808:     
                   10809:     gsl_vector_free(x); /* initial values */
                   10810:     gsl_vector_free(ss); /* inital step size */
                   10811:     for (it=0; it<NDIM; it++){
                   10812:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10813:       fprintf(ficrespow," %.12lf", p[it]);
                   10814:     }
                   10815:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10816: #endif
                   10817: #ifdef POWELL
                   10818:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10819: #endif  
1.126     brouard  10820:     fclose(ficrespow);
                   10821:     
1.203     brouard  10822:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10823: 
                   10824:     for(i=1; i <=NDIM; i++)
                   10825:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10826:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10827:     
                   10828:     printf("\nCovariance matrix\n ");
1.203     brouard  10829:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10830:     for(i=1; i <=NDIM; i++) {
                   10831:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10832:                                printf("%f ",matcov[i][j]);
                   10833:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10834:       }
1.203     brouard  10835:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10836:     }
                   10837:     
                   10838:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10839:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10840:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10841:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10842:     }
1.126     brouard  10843:     lsurv=vector(1,AGESUP);
                   10844:     lpop=vector(1,AGESUP);
                   10845:     tpop=vector(1,AGESUP);
                   10846:     lsurv[agegomp]=100000;
                   10847:     
                   10848:     for (k=agegomp;k<=AGESUP;k++) {
                   10849:       agemortsup=k;
                   10850:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10851:     }
                   10852:     
                   10853:     for (k=agegomp;k<agemortsup;k++)
                   10854:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10855:     
                   10856:     for (k=agegomp;k<agemortsup;k++){
                   10857:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10858:       sumlpop=sumlpop+lpop[k];
                   10859:     }
                   10860:     
                   10861:     tpop[agegomp]=sumlpop;
                   10862:     for (k=agegomp;k<(agemortsup-3);k++){
                   10863:       /*  tpop[k+1]=2;*/
                   10864:       tpop[k+1]=tpop[k]-lpop[k];
                   10865:     }
                   10866:     
                   10867:     
                   10868:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10869:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10870:       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]);
                   10871:     
                   10872:     
                   10873:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10874:                ageminpar=50;
                   10875:                agemaxpar=100;
1.194     brouard  10876:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10877:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10878: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10879: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10880:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10881: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10882: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10883:     }else{
                   10884:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10885:                        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  10886:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10887:                }
1.201     brouard  10888:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10889:                     stepm, weightopt,\
                   10890:                     model,imx,p,matcov,agemortsup);
                   10891:     
                   10892:     free_vector(lsurv,1,AGESUP);
                   10893:     free_vector(lpop,1,AGESUP);
                   10894:     free_vector(tpop,1,AGESUP);
1.220     brouard  10895:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10896:     free_ivector(cens,1,n);
                   10897:     free_vector(agecens,1,n);
                   10898:     free_ivector(dcwave,1,n);
1.220     brouard  10899: #ifdef GSL
1.136     brouard  10900: #endif
1.186     brouard  10901:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10902:   /* Standard  */
                   10903:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10904:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10905:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10906:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10907:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10908:     for (k=1; k<=npar;k++)
                   10909:       printf(" %d %8.5f",k,p[k]);
                   10910:     printf("\n");
1.205     brouard  10911:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10912:       /* mlikeli uses func not funcone */
1.247     brouard  10913:       /* for(i=1;i<nlstate;i++){ */
                   10914:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   10915:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   10916:       /* } */
1.205     brouard  10917:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10918:     }
                   10919:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10920:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10921:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10922:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10923:     }
                   10924:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10925:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10926:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10927:     for (k=1; k<=npar;k++)
                   10928:       printf(" %d %8.5f",k,p[k]);
                   10929:     printf("\n");
                   10930:     
                   10931:     /*--------- results files --------------*/
1.224     brouard  10932:     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  10933:     
                   10934:     
                   10935:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10936:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10937:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10938:     for(i=1,jk=1; i <=nlstate; i++){
                   10939:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10940:        if (k != i) {
                   10941:          printf("%d%d ",i,k);
                   10942:          fprintf(ficlog,"%d%d ",i,k);
                   10943:          fprintf(ficres,"%1d%1d ",i,k);
                   10944:          for(j=1; j <=ncovmodel; j++){
                   10945:            printf("%12.7f ",p[jk]);
                   10946:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10947:            fprintf(ficres,"%12.7f ",p[jk]);
                   10948:            jk++; 
                   10949:          }
                   10950:          printf("\n");
                   10951:          fprintf(ficlog,"\n");
                   10952:          fprintf(ficres,"\n");
                   10953:        }
1.126     brouard  10954:       }
                   10955:     }
1.203     brouard  10956:     if(mle != 0){
                   10957:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10958:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10959:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10960:       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");
                   10961:       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");
                   10962:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10963:        for(k=1; k <=(nlstate+ndeath); k++){
                   10964:          if (k != i) {
                   10965:            printf("%d%d ",i,k);
                   10966:            fprintf(ficlog,"%d%d ",i,k);
                   10967:            for(j=1; j <=ncovmodel; j++){
                   10968:              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]));
                   10969:              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]));
                   10970:              jk++; 
                   10971:            }
                   10972:            printf("\n");
                   10973:            fprintf(ficlog,"\n");
                   10974:          }
                   10975:        }
1.193     brouard  10976:       }
1.203     brouard  10977:     } /* end of hesscov and Wald tests */
1.225     brouard  10978:     
1.203     brouard  10979:     /*  */
1.126     brouard  10980:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10981:     printf("# Scales (for hessian or gradient estimation)\n");
                   10982:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10983:     for(i=1,jk=1; i <=nlstate; i++){
                   10984:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10985:        if (j!=i) {
                   10986:          fprintf(ficres,"%1d%1d",i,j);
                   10987:          printf("%1d%1d",i,j);
                   10988:          fprintf(ficlog,"%1d%1d",i,j);
                   10989:          for(k=1; k<=ncovmodel;k++){
                   10990:            printf(" %.5e",delti[jk]);
                   10991:            fprintf(ficlog," %.5e",delti[jk]);
                   10992:            fprintf(ficres," %.5e",delti[jk]);
                   10993:            jk++;
                   10994:          }
                   10995:          printf("\n");
                   10996:          fprintf(ficlog,"\n");
                   10997:          fprintf(ficres,"\n");
                   10998:        }
1.126     brouard  10999:       }
                   11000:     }
                   11001:     
                   11002:     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  11003:     if(mle >= 1) /* To big for the screen */
1.126     brouard  11004:       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");
                   11005:     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");
                   11006:     /* # 121 Var(a12)\n\ */
                   11007:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   11008:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   11009:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   11010:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   11011:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   11012:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   11013:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   11014:     
                   11015:     
                   11016:     /* Just to have a covariance matrix which will be more understandable
                   11017:        even is we still don't want to manage dictionary of variables
                   11018:     */
                   11019:     for(itimes=1;itimes<=2;itimes++){
                   11020:       jj=0;
                   11021:       for(i=1; i <=nlstate; i++){
1.225     brouard  11022:        for(j=1; j <=nlstate+ndeath; j++){
                   11023:          if(j==i) continue;
                   11024:          for(k=1; k<=ncovmodel;k++){
                   11025:            jj++;
                   11026:            ca[0]= k+'a'-1;ca[1]='\0';
                   11027:            if(itimes==1){
                   11028:              if(mle>=1)
                   11029:                printf("#%1d%1d%d",i,j,k);
                   11030:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   11031:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   11032:            }else{
                   11033:              if(mle>=1)
                   11034:                printf("%1d%1d%d",i,j,k);
                   11035:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   11036:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   11037:            }
                   11038:            ll=0;
                   11039:            for(li=1;li <=nlstate; li++){
                   11040:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   11041:                if(lj==li) continue;
                   11042:                for(lk=1;lk<=ncovmodel;lk++){
                   11043:                  ll++;
                   11044:                  if(ll<=jj){
                   11045:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   11046:                    if(ll<jj){
                   11047:                      if(itimes==1){
                   11048:                        if(mle>=1)
                   11049:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11050:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11051:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11052:                      }else{
                   11053:                        if(mle>=1)
                   11054:                          printf(" %.5e",matcov[jj][ll]); 
                   11055:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   11056:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   11057:                      }
                   11058:                    }else{
                   11059:                      if(itimes==1){
                   11060:                        if(mle>=1)
                   11061:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   11062:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   11063:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   11064:                      }else{
                   11065:                        if(mle>=1)
                   11066:                          printf(" %.7e",matcov[jj][ll]); 
                   11067:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   11068:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   11069:                      }
                   11070:                    }
                   11071:                  }
                   11072:                } /* end lk */
                   11073:              } /* end lj */
                   11074:            } /* end li */
                   11075:            if(mle>=1)
                   11076:              printf("\n");
                   11077:            fprintf(ficlog,"\n");
                   11078:            fprintf(ficres,"\n");
                   11079:            numlinepar++;
                   11080:          } /* end k*/
                   11081:        } /*end j */
1.126     brouard  11082:       } /* end i */
                   11083:     } /* end itimes */
                   11084:     
                   11085:     fflush(ficlog);
                   11086:     fflush(ficres);
1.225     brouard  11087:     while(fgets(line, MAXLINE, ficpar)) {
                   11088:       /* If line starts with a # it is a comment */
                   11089:       if (line[0] == '#') {
                   11090:        numlinepar++;
                   11091:        fputs(line,stdout);
                   11092:        fputs(line,ficparo);
                   11093:        fputs(line,ficlog);
                   11094:        continue;
                   11095:       }else
                   11096:        break;
                   11097:     }
                   11098:     
1.209     brouard  11099:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   11100:     /*   ungetc(c,ficpar); */
                   11101:     /*   fgets(line, MAXLINE, ficpar); */
                   11102:     /*   fputs(line,stdout); */
                   11103:     /*   fputs(line,ficparo); */
                   11104:     /* } */
                   11105:     /* ungetc(c,ficpar); */
1.126     brouard  11106:     
                   11107:     estepm=0;
1.209     brouard  11108:     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  11109:       
                   11110:       if (num_filled != 6) {
                   11111:        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);
                   11112:        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);
                   11113:        goto end;
                   11114:       }
                   11115:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   11116:     }
                   11117:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   11118:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   11119:     
1.209     brouard  11120:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  11121:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   11122:     if (fage <= 2) {
                   11123:       bage = ageminpar;
                   11124:       fage = agemaxpar;
                   11125:     }
                   11126:     
                   11127:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  11128:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   11129:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  11130:                
1.186     brouard  11131:     /* Other stuffs, more or less useful */    
1.254     brouard  11132:     while(fgets(line, MAXLINE, ficpar)) {
                   11133:       /* If line starts with a # it is a comment */
                   11134:       if (line[0] == '#') {
                   11135:        numlinepar++;
                   11136:        fputs(line,stdout);
                   11137:        fputs(line,ficparo);
                   11138:        fputs(line,ficlog);
                   11139:        continue;
                   11140:       }else
                   11141:        break;
                   11142:     }
                   11143: 
                   11144:     if((num_filled=sscanf(line,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav)) !=EOF){
                   11145:       
                   11146:       if (num_filled != 7) {
                   11147:        printf("Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11148:        fprintf(ficlog,"Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11149:        goto end;
                   11150:       }
                   11151:     /* 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); */
                   11152:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   11153:       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);
                   11154:       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);
                   11155:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   11156:       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);
1.126     brouard  11157:     }
1.254     brouard  11158: 
                   11159:     while(fgets(line, MAXLINE, ficpar)) {
                   11160:       /* If line starts with a # it is a comment */
                   11161:       if (line[0] == '#') {
                   11162:        numlinepar++;
                   11163:        fputs(line,stdout);
                   11164:        fputs(line,ficparo);
                   11165:        fputs(line,ficlog);
                   11166:        continue;
                   11167:       }else
                   11168:        break;
1.126     brouard  11169:     }
                   11170:     
                   11171:     
                   11172:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   11173:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   11174:     
1.254     brouard  11175:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   11176:       if (num_filled != 1) {
                   11177:        printf("Error: Not 1 (data)parameters in line but %d, for example:pop_based=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11178:        fprintf(ficlog,"Error: Not 1 (data)parameters in line but %d, for example: pop_based=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11179:        goto end;
                   11180:       }
                   11181:       printf("pop_based=%d\n",popbased);
                   11182:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   11183:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   11184:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   11185:     }
                   11186:      
                   11187:     while(fgets(line, MAXLINE, ficpar)) {
                   11188:       /* If line starts with a # it is a comment */
                   11189:       if (line[0] == '#') {
                   11190:        numlinepar++;
                   11191:        fputs(line,stdout);
                   11192:        fputs(line,ficparo);
                   11193:        fputs(line,ficlog);
                   11194:        continue;
                   11195:       }else
                   11196:        break;
1.126     brouard  11197:     }
1.254     brouard  11198:    /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   11199:    /*    ungetc(c,ficpar); */
                   11200:    /*    fgets(line, MAXLINE, ficpar); */
                   11201:    /*    fputs(line,stdout); */
                   11202:    /*    fputs(line,ficres); */
                   11203:    /*    fputs(line,ficparo); */
                   11204:    /*  } */
                   11205:    /*  ungetc(c,ficpar); */
                   11206:     
                   11207:     /* 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); */
                   11208:     if((num_filled=sscanf(line,"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)) !=EOF){
                   11209:       if (num_filled != 8) {
                   11210:        printf("Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11211:        fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11212:        goto end;
                   11213:       }
                   11214:      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);
                   11215:      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);
                   11216:      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);
                   11217:      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);
1.126     brouard  11218:     /* day and month of proj2 are not used but only year anproj2.*/
1.217     brouard  11219:     }
1.254     brouard  11220:      while(fgets(line, MAXLINE, ficpar)) {
                   11221:       /* If line starts with a # it is a comment */
                   11222:       if (line[0] == '#') {
                   11223:        numlinepar++;
                   11224:        fputs(line,stdout);
                   11225:        fputs(line,ficparo);
                   11226:        fputs(line,ficlog);
                   11227:        continue;
                   11228:       }else
                   11229:        break;
                   11230:     }
                   11231:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   11232:     /*   ungetc(c,ficpar); */
                   11233:     /*   fgets(line, MAXLINE, ficpar); */
                   11234:     /*   fputs(line,stdout); */
                   11235:     /*   fputs(line,ficparo); */
                   11236:     /*   fputs(line,ficres); */
                   11237:     /* } */
                   11238:     /* ungetc(c,ficpar); */
1.217     brouard  11239:     
                   11240:     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.254     brouard  11241:     if((num_filled=sscanf(line,"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)) !=EOF){
                   11242:       if (num_filled != 8) {
                   11243:        printf("Error: Not 8 (data)parameters in line but %d, for example:backcast=1 starting-back-date=1/1/1990 finloal-back-date=1/1/1970 mobil_average=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11244:        fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:backcast=1 starting-back-date=1/1/1990 finloal-back-date=1/1/1970 mobil_average=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11245:        goto end;
                   11246:       }
                   11247:       printf("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);
                   11248:       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);
                   11249:       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);
                   11250:       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  11251:     /* day and month of proj2 are not used but only year anproj2.*/
1.254     brouard  11252:     }
1.230     brouard  11253:     /* Results */
1.235     brouard  11254:     nresult=0;
1.230     brouard  11255:     while(fgets(line, MAXLINE, ficpar)) {
                   11256:       /* If line starts with a # it is a comment */
                   11257:       if (line[0] == '#') {
                   11258:        numlinepar++;
                   11259:        fputs(line,stdout);
                   11260:        fputs(line,ficparo);
                   11261:        fputs(line,ficlog);
1.238     brouard  11262:        fputs(line,ficres);
1.230     brouard  11263:        continue;
                   11264:       }else
                   11265:        break;
                   11266:     }
1.240     brouard  11267:     if (!feof(ficpar))
1.230     brouard  11268:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240     brouard  11269:       if (num_filled == 0){
1.230     brouard  11270:        resultline[0]='\0';
1.253     brouard  11271:        printf("Warning %d: no result line should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
1.240     brouard  11272:       break;
                   11273:       } else if (num_filled != 1){
1.253     brouard  11274:        printf("ERROR %d: result line should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
1.230     brouard  11275:       }
1.235     brouard  11276:       nresult++; /* Sum of resultlines */
                   11277:       printf("Result %d: result=%s\n",nresult, resultline);
                   11278:       if(nresult > MAXRESULTLINES){
                   11279:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   11280:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   11281:        goto end;
                   11282:       }
                   11283:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  11284:       fprintf(ficparo,"result: %s\n",resultline);
                   11285:       fprintf(ficres,"result: %s\n",resultline);
                   11286:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  11287:       while(fgets(line, MAXLINE, ficpar)) {
                   11288:        /* If line starts with a # it is a comment */
                   11289:        if (line[0] == '#') {
                   11290:          numlinepar++;
                   11291:          fputs(line,stdout);
                   11292:          fputs(line,ficparo);
1.238     brouard  11293:          fputs(line,ficres);
1.230     brouard  11294:          fputs(line,ficlog);
                   11295:          continue;
                   11296:        }else
                   11297:          break;
                   11298:       }
                   11299:       if (feof(ficpar))
                   11300:        break;
                   11301:       else{ /* Processess output results for this combination of covariate values */
                   11302:       }                                   
1.240     brouard  11303:     } /* end while */
1.230     brouard  11304: 
                   11305: 
1.126     brouard  11306:     
1.230     brouard  11307:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  11308:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  11309:     
                   11310:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  11311:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  11312:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11313: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11314: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  11315:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11316: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11317: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  11318:     }else{
1.218     brouard  11319:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  11320:     }
                   11321:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  11322:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   11323:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  11324:                
1.225     brouard  11325:     /*------------ free_vector  -------------*/
                   11326:     /*  chdir(path); */
1.220     brouard  11327:                
1.215     brouard  11328:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   11329:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   11330:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   11331:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  11332:     free_lvector(num,1,n);
                   11333:     free_vector(agedc,1,n);
                   11334:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   11335:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   11336:     fclose(ficparo);
                   11337:     fclose(ficres);
1.220     brouard  11338:                
                   11339:                
1.186     brouard  11340:     /* Other results (useful)*/
1.220     brouard  11341:                
                   11342:                
1.126     brouard  11343:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11344:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11345:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11346:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11347:     fclose(ficrespl);
                   11348: 
                   11349:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11350:     /*#include "hpijx.h"*/
                   11351:     hPijx(p, bage, fage);
1.145     brouard  11352:     fclose(ficrespij);
1.227     brouard  11353:     
1.220     brouard  11354:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11355:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11356:     k=1;
1.126     brouard  11357:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11358:     
1.219     brouard  11359:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11360:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11361:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11362:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11363:        for(k=1;k<=ncovcombmax;k++)
                   11364:          probs[i][j][k]=0.;
1.219     brouard  11365:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11366:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11367:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11368:       for(i=1;i<=AGESUP;i++)
                   11369:        for(j=1;j<=nlstate;j++)
                   11370:          for(k=1;k<=ncovcombmax;k++)
                   11371:            mobaverages[i][j][k]=0.;
1.219     brouard  11372:       mobaverage=mobaverages;
                   11373:       if (mobilav!=0) {
1.235     brouard  11374:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  11375:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11376:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11377:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11378:        }
1.219     brouard  11379:       }
                   11380:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11381:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11382:       else if (mobilavproj !=0) {
1.235     brouard  11383:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  11384:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11385:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11386:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11387:        }
1.219     brouard  11388:       }
                   11389:     }/* end if moving average */
1.227     brouard  11390:     
1.126     brouard  11391:     /*---------- Forecasting ------------------*/
                   11392:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11393:     if(prevfcast==1){
                   11394:       /*    if(stepm ==1){*/
1.225     brouard  11395:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11396:     }
1.217     brouard  11397:     if(backcast==1){
1.219     brouard  11398:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11399:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11400:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11401: 
                   11402:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11403: 
                   11404:       bprlim=matrix(1,nlstate,1,nlstate);
                   11405:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11406:       fclose(ficresplb);
                   11407: 
1.222     brouard  11408:       hBijx(p, bage, fage, mobaverage);
                   11409:       fclose(ficrespijb);
1.219     brouard  11410:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11411: 
                   11412:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11413:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11414:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11415:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11416:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11417:     }
1.217     brouard  11418:     
1.186     brouard  11419:  
                   11420:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11421: 
1.215     brouard  11422:     free_ivector(wav,1,imx);
                   11423:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11424:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11425:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11426:                
                   11427:                
1.127     brouard  11428:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11429:                
1.201     brouard  11430:     strcpy(filerese,"E_");
                   11431:     strcat(filerese,fileresu);
1.126     brouard  11432:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11433:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11434:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11435:     }
1.208     brouard  11436:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11437:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11438: 
                   11439:     pstamp(ficreseij);
1.219     brouard  11440:                
1.235     brouard  11441:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11442:     if (cptcovn < 1){i1=1;}
                   11443:     
                   11444:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11445:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11446:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11447:        continue;
1.219     brouard  11448:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11449:       printf("\n#****** ");
1.225     brouard  11450:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11451:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11452:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11453:       }
                   11454:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11455:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11456:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11457:       }
                   11458:       fprintf(ficreseij,"******\n");
1.235     brouard  11459:       printf("******\n");
1.219     brouard  11460:       
                   11461:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11462:       oldm=oldms;savm=savms;
1.235     brouard  11463:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11464:       
1.219     brouard  11465:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11466:     }
                   11467:     fclose(ficreseij);
1.208     brouard  11468:     printf("done evsij\n");fflush(stdout);
                   11469:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11470:                
1.227     brouard  11471:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11472:                
                   11473:                
1.201     brouard  11474:     strcpy(filerest,"T_");
                   11475:     strcat(filerest,fileresu);
1.127     brouard  11476:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11477:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11478:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11479:     }
1.208     brouard  11480:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11481:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11482:                
1.126     brouard  11483: 
1.201     brouard  11484:     strcpy(fileresstde,"STDE_");
                   11485:     strcat(fileresstde,fileresu);
1.126     brouard  11486:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11487:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11488:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11489:     }
1.227     brouard  11490:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11491:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11492: 
1.201     brouard  11493:     strcpy(filerescve,"CVE_");
                   11494:     strcat(filerescve,fileresu);
1.126     brouard  11495:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11496:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11497:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11498:     }
1.227     brouard  11499:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11500:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11501: 
1.201     brouard  11502:     strcpy(fileresv,"V_");
                   11503:     strcat(fileresv,fileresu);
1.126     brouard  11504:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11505:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11506:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11507:     }
1.227     brouard  11508:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11509:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11510: 
1.145     brouard  11511:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11512:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11513:           
1.235     brouard  11514:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11515:     if (cptcovn < 1){i1=1;}
                   11516:     
                   11517:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11518:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11519:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11520:        continue;
1.242     brouard  11521:       printf("\n#****** Result for:");
                   11522:       fprintf(ficrest,"\n#****** Result for:");
                   11523:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11524:       for(j=1;j<=cptcoveff;j++){ 
                   11525:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11526:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11527:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11528:       }
1.235     brouard  11529:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11530:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11531:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11532:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11533:       }        
1.208     brouard  11534:       fprintf(ficrest,"******\n");
1.227     brouard  11535:       fprintf(ficlog,"******\n");
                   11536:       printf("******\n");
1.208     brouard  11537:       
                   11538:       fprintf(ficresstdeij,"\n#****** ");
                   11539:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11540:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11541:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11542:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11543:       }
1.235     brouard  11544:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11545:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11546:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11547:       }        
1.208     brouard  11548:       fprintf(ficresstdeij,"******\n");
                   11549:       fprintf(ficrescveij,"******\n");
                   11550:       
                   11551:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11552:       /* pstamp(ficresvij); */
1.225     brouard  11553:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11554:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11555:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11556:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11557:       }        
1.208     brouard  11558:       fprintf(ficresvij,"******\n");
                   11559:       
                   11560:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11561:       oldm=oldms;savm=savms;
1.235     brouard  11562:       printf(" cvevsij ");
                   11563:       fprintf(ficlog, " cvevsij ");
                   11564:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11565:       printf(" end cvevsij \n ");
                   11566:       fprintf(ficlog, " end cvevsij \n ");
                   11567:       
                   11568:       /*
                   11569:        */
                   11570:       /* goto endfree; */
                   11571:       
                   11572:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11573:       pstamp(ficrest);
                   11574:       
                   11575:       
                   11576:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11577:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11578:        cptcod= 0; /* To be deleted */
                   11579:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11580:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11581:        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  11582:        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 ");
                   11583:        if(vpopbased==1)
                   11584:          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);
                   11585:        else
                   11586:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11587:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11588:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11589:        fprintf(ficrest,"\n");
                   11590:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11591:        epj=vector(1,nlstate+1);
                   11592:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11593:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11594:        for(age=bage; age <=fage ;age++){
1.235     brouard  11595:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11596:          if (vpopbased==1) {
                   11597:            if(mobilav ==0){
                   11598:              for(i=1; i<=nlstate;i++)
                   11599:                prlim[i][i]=probs[(int)age][i][k];
                   11600:            }else{ /* mobilav */ 
                   11601:              for(i=1; i<=nlstate;i++)
                   11602:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11603:            }
                   11604:          }
1.219     brouard  11605:          
1.227     brouard  11606:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11607:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11608:          /* printf(" age %4.0f ",age); */
                   11609:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11610:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11611:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11612:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11613:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11614:            }
                   11615:            epj[nlstate+1] +=epj[j];
                   11616:          }
                   11617:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11618:          
1.227     brouard  11619:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11620:            for(j=1;j <=nlstate;j++)
                   11621:              vepp += vareij[i][j][(int)age];
                   11622:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11623:          for(j=1;j <=nlstate;j++){
                   11624:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11625:          }
                   11626:          fprintf(ficrest,"\n");
                   11627:        }
1.208     brouard  11628:       } /* End vpopbased */
                   11629:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11630:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11631:       free_vector(epj,1,nlstate+1);
1.235     brouard  11632:       printf("done selection\n");fflush(stdout);
                   11633:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11634:       
1.145     brouard  11635:       /*}*/
1.235     brouard  11636:     } /* End k selection */
1.227     brouard  11637: 
                   11638:     printf("done State-specific expectancies\n");fflush(stdout);
                   11639:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11640: 
1.126     brouard  11641:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11642:     
1.201     brouard  11643:     strcpy(fileresvpl,"VPL_");
                   11644:     strcat(fileresvpl,fileresu);
1.126     brouard  11645:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11646:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11647:       exit(0);
                   11648:     }
1.208     brouard  11649:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11650:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11651:     
1.145     brouard  11652:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11653:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11654:     
1.235     brouard  11655:     i1=pow(2,cptcoveff);
                   11656:     if (cptcovn < 1){i1=1;}
                   11657: 
                   11658:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11659:     for(k=1; k<=i1;k++){
1.253     brouard  11660:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11661:        continue;
1.227     brouard  11662:       fprintf(ficresvpl,"\n#****** ");
                   11663:       printf("\n#****** ");
                   11664:       fprintf(ficlog,"\n#****** ");
                   11665:       for(j=1;j<=cptcoveff;j++) {
                   11666:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11667:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11668:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11669:       }
1.235     brouard  11670:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11671:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11672:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11673:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11674:       }        
1.227     brouard  11675:       fprintf(ficresvpl,"******\n");
                   11676:       printf("******\n");
                   11677:       fprintf(ficlog,"******\n");
                   11678:       
                   11679:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11680:       oldm=oldms;savm=savms;
1.235     brouard  11681:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11682:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11683:       /*}*/
1.126     brouard  11684:     }
1.227     brouard  11685:     
1.126     brouard  11686:     fclose(ficresvpl);
1.208     brouard  11687:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11688:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11689:     
                   11690:     free_vector(weight,1,n);
                   11691:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11692:     free_imatrix(s,1,maxwav+1,1,n);
                   11693:     free_matrix(anint,1,maxwav,1,n); 
                   11694:     free_matrix(mint,1,maxwav,1,n);
                   11695:     free_ivector(cod,1,n);
                   11696:     free_ivector(tab,1,NCOVMAX);
                   11697:     fclose(ficresstdeij);
                   11698:     fclose(ficrescveij);
                   11699:     fclose(ficresvij);
                   11700:     fclose(ficrest);
                   11701:     fclose(ficpar);
                   11702:     
                   11703:     
1.126     brouard  11704:     /*---------- End : free ----------------*/
1.219     brouard  11705:     if (mobilav!=0 ||mobilavproj !=0)
                   11706:       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  11707:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11708:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11709:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11710:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11711:   /* endfree:*/
                   11712:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11713:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11714:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11715:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11716:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11717:   free_matrix(coqvar,1,maxwav,1,n);
                   11718:   free_matrix(covar,0,NCOVMAX,1,n);
                   11719:   free_matrix(matcov,1,npar,1,npar);
                   11720:   free_matrix(hess,1,npar,1,npar);
                   11721:   /*free_vector(delti,1,npar);*/
                   11722:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11723:   free_matrix(agev,1,maxwav,1,imx);
                   11724:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11725:   
                   11726:   free_ivector(ncodemax,1,NCOVMAX);
                   11727:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11728:   free_ivector(Dummy,-1,NCOVMAX);
                   11729:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11730:   free_ivector(DummyV,1,NCOVMAX);
                   11731:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11732:   free_ivector(Typevar,-1,NCOVMAX);
                   11733:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11734:   free_ivector(TvarsQ,1,NCOVMAX);
                   11735:   free_ivector(TvarsQind,1,NCOVMAX);
                   11736:   free_ivector(TvarsD,1,NCOVMAX);
                   11737:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11738:   free_ivector(TvarFD,1,NCOVMAX);
                   11739:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11740:   free_ivector(TvarF,1,NCOVMAX);
                   11741:   free_ivector(TvarFind,1,NCOVMAX);
                   11742:   free_ivector(TvarV,1,NCOVMAX);
                   11743:   free_ivector(TvarVind,1,NCOVMAX);
                   11744:   free_ivector(TvarA,1,NCOVMAX);
                   11745:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11746:   free_ivector(TvarFQ,1,NCOVMAX);
                   11747:   free_ivector(TvarFQind,1,NCOVMAX);
                   11748:   free_ivector(TvarVD,1,NCOVMAX);
                   11749:   free_ivector(TvarVDind,1,NCOVMAX);
                   11750:   free_ivector(TvarVQ,1,NCOVMAX);
                   11751:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11752:   free_ivector(Tvarsel,1,NCOVMAX);
                   11753:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11754:   free_ivector(Tposprod,1,NCOVMAX);
                   11755:   free_ivector(Tprod,1,NCOVMAX);
                   11756:   free_ivector(Tvaraff,1,NCOVMAX);
                   11757:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11758:   free_ivector(Tage,1,NCOVMAX);
                   11759:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11760:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11761:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11762:   
                   11763:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11764:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11765:   fflush(fichtm);
                   11766:   fflush(ficgp);
                   11767:   
1.227     brouard  11768:   
1.126     brouard  11769:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11770:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11771:     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  11772:   }else{
                   11773:     printf("End of Imach\n");
                   11774:     fprintf(ficlog,"End of Imach\n");
                   11775:   }
                   11776:   printf("See log file on %s\n",filelog);
                   11777:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11778:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11779:   rend_time = time(NULL);  
                   11780:   end_time = *localtime(&rend_time);
                   11781:   /* tml = *localtime(&end_time.tm_sec); */
                   11782:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11783:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11784:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11785:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11786:   
1.157     brouard  11787:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11788:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11789:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11790:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11791: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11792:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11793:   fclose(fichtm);
                   11794:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11795:   fclose(fichtmcov);
                   11796:   fclose(ficgp);
                   11797:   fclose(ficlog);
                   11798:   /*------ End -----------*/
1.227     brouard  11799:   
                   11800:   
                   11801:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11802: #ifdef WIN32
1.227     brouard  11803:   if (_chdir(pathcd) != 0)
                   11804:     printf("Can't move to directory %s!\n",path);
                   11805:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11806: #else
1.227     brouard  11807:     if(chdir(pathcd) != 0)
                   11808:       printf("Can't move to directory %s!\n", path);
                   11809:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11810: #endif 
1.126     brouard  11811:     printf("Current directory %s!\n",pathcd);
                   11812:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11813:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11814: #ifdef _WIN32
1.126     brouard  11815:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11816: #endif
                   11817:   if(!stat(plotcmd,&info)){
1.158     brouard  11818:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11819:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11820:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11821:     }else
                   11822:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11823: #ifdef __unix
1.126     brouard  11824:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11825:     if(!stat(plotcmd,&info)){
1.158     brouard  11826:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11827:     }else
                   11828:       strcpy(pplotcmd,plotcmd);
                   11829: #endif
                   11830:   }else
                   11831:     strcpy(pplotcmd,plotcmd);
                   11832:   
                   11833:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11834:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11835:   
1.126     brouard  11836:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11837:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11838:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11839:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11840:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11841:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11842:   }
1.158     brouard  11843:   printf(" Successful, please wait...");
1.126     brouard  11844:   while (z[0] != 'q') {
                   11845:     /* chdir(path); */
1.154     brouard  11846:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11847:     scanf("%s",z);
                   11848: /*     if (z[0] == 'c') system("./imach"); */
                   11849:     if (z[0] == 'e') {
1.158     brouard  11850: #ifdef __APPLE__
1.152     brouard  11851:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11852: #elif __linux
                   11853:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11854: #else
1.152     brouard  11855:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11856: #endif
                   11857:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11858:       system(pplotcmd);
1.126     brouard  11859:     }
                   11860:     else if (z[0] == 'g') system(plotcmd);
                   11861:     else if (z[0] == 'q') exit(0);
                   11862:   }
1.227     brouard  11863: end:
1.126     brouard  11864:   while (z[0] != 'q') {
1.195     brouard  11865:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11866:     scanf("%s",z);
                   11867:   }
                   11868: }

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