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

1.247   ! brouard     1: /* $Id: imach.c,v 1.246 2016/09/02 08:49:22 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.247   ! brouard     4:   Revision 1.246  2016/09/02 08:49:22  brouard
        !             5:   *** empty log message ***
        !             6: 
1.246     brouard     7:   Revision 1.245  2016/09/02 07:25:01  brouard
                      8:   *** empty log message ***
                      9: 
1.245     brouard    10:   Revision 1.244  2016/09/02 07:17:34  brouard
                     11:   *** empty log message ***
                     12: 
1.244     brouard    13:   Revision 1.243  2016/09/02 06:45:35  brouard
                     14:   *** empty log message ***
                     15: 
1.243     brouard    16:   Revision 1.242  2016/08/30 15:01:20  brouard
                     17:   Summary: Fixing a lots
                     18: 
1.242     brouard    19:   Revision 1.241  2016/08/29 17:17:25  brouard
                     20:   Summary: gnuplot problem in Back projection to fix
                     21: 
1.241     brouard    22:   Revision 1.240  2016/08/29 07:53:18  brouard
                     23:   Summary: Better
                     24: 
1.240     brouard    25:   Revision 1.239  2016/08/26 15:51:03  brouard
                     26:   Summary: Improvement in Powell output in order to copy and paste
                     27: 
                     28:   Author:
                     29: 
1.239     brouard    30:   Revision 1.238  2016/08/26 14:23:35  brouard
                     31:   Summary: Starting tests of 0.99
                     32: 
1.238     brouard    33:   Revision 1.237  2016/08/26 09:20:19  brouard
                     34:   Summary: to valgrind
                     35: 
1.237     brouard    36:   Revision 1.236  2016/08/25 10:50:18  brouard
                     37:   *** empty log message ***
                     38: 
1.236     brouard    39:   Revision 1.235  2016/08/25 06:59:23  brouard
                     40:   *** empty log message ***
                     41: 
1.235     brouard    42:   Revision 1.234  2016/08/23 16:51:20  brouard
                     43:   *** empty log message ***
                     44: 
1.234     brouard    45:   Revision 1.233  2016/08/23 07:40:50  brouard
                     46:   Summary: not working
                     47: 
1.233     brouard    48:   Revision 1.232  2016/08/22 14:20:21  brouard
                     49:   Summary: not working
                     50: 
1.232     brouard    51:   Revision 1.231  2016/08/22 07:17:15  brouard
                     52:   Summary: not working
                     53: 
1.231     brouard    54:   Revision 1.230  2016/08/22 06:55:53  brouard
                     55:   Summary: Not working
                     56: 
1.230     brouard    57:   Revision 1.229  2016/07/23 09:45:53  brouard
                     58:   Summary: Completing for func too
                     59: 
1.229     brouard    60:   Revision 1.228  2016/07/22 17:45:30  brouard
                     61:   Summary: Fixing some arrays, still debugging
                     62: 
1.227     brouard    63:   Revision 1.226  2016/07/12 18:42:34  brouard
                     64:   Summary: temp
                     65: 
1.226     brouard    66:   Revision 1.225  2016/07/12 08:40:03  brouard
                     67:   Summary: saving but not running
                     68: 
1.225     brouard    69:   Revision 1.224  2016/07/01 13:16:01  brouard
                     70:   Summary: Fixes
                     71: 
1.224     brouard    72:   Revision 1.223  2016/02/19 09:23:35  brouard
                     73:   Summary: temporary
                     74: 
1.223     brouard    75:   Revision 1.222  2016/02/17 08:14:50  brouard
                     76:   Summary: Probably last 0.98 stable version 0.98r6
                     77: 
1.222     brouard    78:   Revision 1.221  2016/02/15 23:35:36  brouard
                     79:   Summary: minor bug
                     80: 
1.220     brouard    81:   Revision 1.219  2016/02/15 00:48:12  brouard
                     82:   *** empty log message ***
                     83: 
1.219     brouard    84:   Revision 1.218  2016/02/12 11:29:23  brouard
                     85:   Summary: 0.99 Back projections
                     86: 
1.218     brouard    87:   Revision 1.217  2015/12/23 17:18:31  brouard
                     88:   Summary: Experimental backcast
                     89: 
1.217     brouard    90:   Revision 1.216  2015/12/18 17:32:11  brouard
                     91:   Summary: 0.98r4 Warning and status=-2
                     92: 
                     93:   Version 0.98r4 is now:
                     94:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     95:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     96:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     97: 
1.216     brouard    98:   Revision 1.215  2015/12/16 08:52:24  brouard
                     99:   Summary: 0.98r4 working
                    100: 
1.215     brouard   101:   Revision 1.214  2015/12/16 06:57:54  brouard
                    102:   Summary: temporary not working
                    103: 
1.214     brouard   104:   Revision 1.213  2015/12/11 18:22:17  brouard
                    105:   Summary: 0.98r4
                    106: 
1.213     brouard   107:   Revision 1.212  2015/11/21 12:47:24  brouard
                    108:   Summary: minor typo
                    109: 
1.212     brouard   110:   Revision 1.211  2015/11/21 12:41:11  brouard
                    111:   Summary: 0.98r3 with some graph of projected cross-sectional
                    112: 
                    113:   Author: Nicolas Brouard
                    114: 
1.211     brouard   115:   Revision 1.210  2015/11/18 17:41:20  brouard
                    116:   Summary: Start working on projected prevalences
                    117: 
1.210     brouard   118:   Revision 1.209  2015/11/17 22:12:03  brouard
                    119:   Summary: Adding ftolpl parameter
                    120:   Author: N Brouard
                    121: 
                    122:   We had difficulties to get smoothed confidence intervals. It was due
                    123:   to the period prevalence which wasn't computed accurately. The inner
                    124:   parameter ftolpl is now an outer parameter of the .imach parameter
                    125:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    126:   computation are long.
                    127: 
1.209     brouard   128:   Revision 1.208  2015/11/17 14:31:57  brouard
                    129:   Summary: temporary
                    130: 
1.208     brouard   131:   Revision 1.207  2015/10/27 17:36:57  brouard
                    132:   *** empty log message ***
                    133: 
1.207     brouard   134:   Revision 1.206  2015/10/24 07:14:11  brouard
                    135:   *** empty log message ***
                    136: 
1.206     brouard   137:   Revision 1.205  2015/10/23 15:50:53  brouard
                    138:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    139: 
1.205     brouard   140:   Revision 1.204  2015/10/01 16:20:26  brouard
                    141:   Summary: Some new graphs of contribution to likelihood
                    142: 
1.204     brouard   143:   Revision 1.203  2015/09/30 17:45:14  brouard
                    144:   Summary: looking at better estimation of the hessian
                    145: 
                    146:   Also a better criteria for convergence to the period prevalence And
                    147:   therefore adding the number of years needed to converge. (The
                    148:   prevalence in any alive state shold sum to one
                    149: 
1.203     brouard   150:   Revision 1.202  2015/09/22 19:45:16  brouard
                    151:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    152: 
1.202     brouard   153:   Revision 1.201  2015/09/15 17:34:58  brouard
                    154:   Summary: 0.98r0
                    155: 
                    156:   - Some new graphs like suvival functions
                    157:   - Some bugs fixed like model=1+age+V2.
                    158: 
1.201     brouard   159:   Revision 1.200  2015/09/09 16:53:55  brouard
                    160:   Summary: Big bug thanks to Flavia
                    161: 
                    162:   Even model=1+age+V2. did not work anymore
                    163: 
1.200     brouard   164:   Revision 1.199  2015/09/07 14:09:23  brouard
                    165:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    166: 
1.199     brouard   167:   Revision 1.198  2015/09/03 07:14:39  brouard
                    168:   Summary: 0.98q5 Flavia
                    169: 
1.198     brouard   170:   Revision 1.197  2015/09/01 18:24:39  brouard
                    171:   *** empty log message ***
                    172: 
1.197     brouard   173:   Revision 1.196  2015/08/18 23:17:52  brouard
                    174:   Summary: 0.98q5
                    175: 
1.196     brouard   176:   Revision 1.195  2015/08/18 16:28:39  brouard
                    177:   Summary: Adding a hack for testing purpose
                    178: 
                    179:   After reading the title, ftol and model lines, if the comment line has
                    180:   a q, starting with #q, the answer at the end of the run is quit. It
                    181:   permits to run test files in batch with ctest. The former workaround was
                    182:   $ echo q | imach foo.imach
                    183: 
1.195     brouard   184:   Revision 1.194  2015/08/18 13:32:00  brouard
                    185:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    186: 
1.194     brouard   187:   Revision 1.193  2015/08/04 07:17:42  brouard
                    188:   Summary: 0.98q4
                    189: 
1.193     brouard   190:   Revision 1.192  2015/07/16 16:49:02  brouard
                    191:   Summary: Fixing some outputs
                    192: 
1.192     brouard   193:   Revision 1.191  2015/07/14 10:00:33  brouard
                    194:   Summary: Some fixes
                    195: 
1.191     brouard   196:   Revision 1.190  2015/05/05 08:51:13  brouard
                    197:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    198: 
                    199:   Fix 1+age+.
                    200: 
1.190     brouard   201:   Revision 1.189  2015/04/30 14:45:16  brouard
                    202:   Summary: 0.98q2
                    203: 
1.189     brouard   204:   Revision 1.188  2015/04/30 08:27:53  brouard
                    205:   *** empty log message ***
                    206: 
1.188     brouard   207:   Revision 1.187  2015/04/29 09:11:15  brouard
                    208:   *** empty log message ***
                    209: 
1.187     brouard   210:   Revision 1.186  2015/04/23 12:01:52  brouard
                    211:   Summary: V1*age is working now, version 0.98q1
                    212: 
                    213:   Some codes had been disabled in order to simplify and Vn*age was
                    214:   working in the optimization phase, ie, giving correct MLE parameters,
                    215:   but, as usual, outputs were not correct and program core dumped.
                    216: 
1.186     brouard   217:   Revision 1.185  2015/03/11 13:26:42  brouard
                    218:   Summary: Inclusion of compile and links command line for Intel Compiler
                    219: 
1.185     brouard   220:   Revision 1.184  2015/03/11 11:52:39  brouard
                    221:   Summary: Back from Windows 8. Intel Compiler
                    222: 
1.184     brouard   223:   Revision 1.183  2015/03/10 20:34:32  brouard
                    224:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    225: 
                    226:   We use directest instead of original Powell test; probably no
                    227:   incidence on the results, but better justifications;
                    228:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    229:   wrong results.
                    230: 
1.183     brouard   231:   Revision 1.182  2015/02/12 08:19:57  brouard
                    232:   Summary: Trying to keep directest which seems simpler and more general
                    233:   Author: Nicolas Brouard
                    234: 
1.182     brouard   235:   Revision 1.181  2015/02/11 23:22:24  brouard
                    236:   Summary: Comments on Powell added
                    237: 
                    238:   Author:
                    239: 
1.181     brouard   240:   Revision 1.180  2015/02/11 17:33:45  brouard
                    241:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    242: 
1.180     brouard   243:   Revision 1.179  2015/01/04 09:57:06  brouard
                    244:   Summary: back to OS/X
                    245: 
1.179     brouard   246:   Revision 1.178  2015/01/04 09:35:48  brouard
                    247:   *** empty log message ***
                    248: 
1.178     brouard   249:   Revision 1.177  2015/01/03 18:40:56  brouard
                    250:   Summary: Still testing ilc32 on OSX
                    251: 
1.177     brouard   252:   Revision 1.176  2015/01/03 16:45:04  brouard
                    253:   *** empty log message ***
                    254: 
1.176     brouard   255:   Revision 1.175  2015/01/03 16:33:42  brouard
                    256:   *** empty log message ***
                    257: 
1.175     brouard   258:   Revision 1.174  2015/01/03 16:15:49  brouard
                    259:   Summary: Still in cross-compilation
                    260: 
1.174     brouard   261:   Revision 1.173  2015/01/03 12:06:26  brouard
                    262:   Summary: trying to detect cross-compilation
                    263: 
1.173     brouard   264:   Revision 1.172  2014/12/27 12:07:47  brouard
                    265:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    266: 
1.172     brouard   267:   Revision 1.171  2014/12/23 13:26:59  brouard
                    268:   Summary: Back from Visual C
                    269: 
                    270:   Still problem with utsname.h on Windows
                    271: 
1.171     brouard   272:   Revision 1.170  2014/12/23 11:17:12  brouard
                    273:   Summary: Cleaning some \%% back to %%
                    274: 
                    275:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    276: 
1.170     brouard   277:   Revision 1.169  2014/12/22 23:08:31  brouard
                    278:   Summary: 0.98p
                    279: 
                    280:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    281: 
1.169     brouard   282:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   283:   Summary: update
1.169     brouard   284: 
1.168     brouard   285:   Revision 1.167  2014/12/22 13:50:56  brouard
                    286:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    287: 
                    288:   Testing on Linux 64
                    289: 
1.167     brouard   290:   Revision 1.166  2014/12/22 11:40:47  brouard
                    291:   *** empty log message ***
                    292: 
1.166     brouard   293:   Revision 1.165  2014/12/16 11:20:36  brouard
                    294:   Summary: After compiling on Visual C
                    295: 
                    296:   * imach.c (Module): Merging 1.61 to 1.162
                    297: 
1.165     brouard   298:   Revision 1.164  2014/12/16 10:52:11  brouard
                    299:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    300: 
                    301:   * imach.c (Module): Merging 1.61 to 1.162
                    302: 
1.164     brouard   303:   Revision 1.163  2014/12/16 10:30:11  brouard
                    304:   * imach.c (Module): Merging 1.61 to 1.162
                    305: 
1.163     brouard   306:   Revision 1.162  2014/09/25 11:43:39  brouard
                    307:   Summary: temporary backup 0.99!
                    308: 
1.162     brouard   309:   Revision 1.1  2014/09/16 11:06:58  brouard
                    310:   Summary: With some code (wrong) for nlopt
                    311: 
                    312:   Author:
                    313: 
                    314:   Revision 1.161  2014/09/15 20:41:41  brouard
                    315:   Summary: Problem with macro SQR on Intel compiler
                    316: 
1.161     brouard   317:   Revision 1.160  2014/09/02 09:24:05  brouard
                    318:   *** empty log message ***
                    319: 
1.160     brouard   320:   Revision 1.159  2014/09/01 10:34:10  brouard
                    321:   Summary: WIN32
                    322:   Author: Brouard
                    323: 
1.159     brouard   324:   Revision 1.158  2014/08/27 17:11:51  brouard
                    325:   *** empty log message ***
                    326: 
1.158     brouard   327:   Revision 1.157  2014/08/27 16:26:55  brouard
                    328:   Summary: Preparing windows Visual studio version
                    329:   Author: Brouard
                    330: 
                    331:   In order to compile on Visual studio, time.h is now correct and time_t
                    332:   and tm struct should be used. difftime should be used but sometimes I
                    333:   just make the differences in raw time format (time(&now).
                    334:   Trying to suppress #ifdef LINUX
                    335:   Add xdg-open for __linux in order to open default browser.
                    336: 
1.157     brouard   337:   Revision 1.156  2014/08/25 20:10:10  brouard
                    338:   *** empty log message ***
                    339: 
1.156     brouard   340:   Revision 1.155  2014/08/25 18:32:34  brouard
                    341:   Summary: New compile, minor changes
                    342:   Author: Brouard
                    343: 
1.155     brouard   344:   Revision 1.154  2014/06/20 17:32:08  brouard
                    345:   Summary: Outputs now all graphs of convergence to period prevalence
                    346: 
1.154     brouard   347:   Revision 1.153  2014/06/20 16:45:46  brouard
                    348:   Summary: If 3 live state, convergence to period prevalence on same graph
                    349:   Author: Brouard
                    350: 
1.153     brouard   351:   Revision 1.152  2014/06/18 17:54:09  brouard
                    352:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    353: 
1.152     brouard   354:   Revision 1.151  2014/06/18 16:43:30  brouard
                    355:   *** empty log message ***
                    356: 
1.151     brouard   357:   Revision 1.150  2014/06/18 16:42:35  brouard
                    358:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    359:   Author: brouard
                    360: 
1.150     brouard   361:   Revision 1.149  2014/06/18 15:51:14  brouard
                    362:   Summary: Some fixes in parameter files errors
                    363:   Author: Nicolas Brouard
                    364: 
1.149     brouard   365:   Revision 1.148  2014/06/17 17:38:48  brouard
                    366:   Summary: Nothing new
                    367:   Author: Brouard
                    368: 
                    369:   Just a new packaging for OS/X version 0.98nS
                    370: 
1.148     brouard   371:   Revision 1.147  2014/06/16 10:33:11  brouard
                    372:   *** empty log message ***
                    373: 
1.147     brouard   374:   Revision 1.146  2014/06/16 10:20:28  brouard
                    375:   Summary: Merge
                    376:   Author: Brouard
                    377: 
                    378:   Merge, before building revised version.
                    379: 
1.146     brouard   380:   Revision 1.145  2014/06/10 21:23:15  brouard
                    381:   Summary: Debugging with valgrind
                    382:   Author: Nicolas Brouard
                    383: 
                    384:   Lot of changes in order to output the results with some covariates
                    385:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    386:   improve the code.
                    387:   No more memory valgrind error but a lot has to be done in order to
                    388:   continue the work of splitting the code into subroutines.
                    389:   Also, decodemodel has been improved. Tricode is still not
                    390:   optimal. nbcode should be improved. Documentation has been added in
                    391:   the source code.
                    392: 
1.144     brouard   393:   Revision 1.143  2014/01/26 09:45:38  brouard
                    394:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    395: 
                    396:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    397:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    398: 
1.143     brouard   399:   Revision 1.142  2014/01/26 03:57:36  brouard
                    400:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    401: 
                    402:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    403: 
1.142     brouard   404:   Revision 1.141  2014/01/26 02:42:01  brouard
                    405:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    406: 
1.141     brouard   407:   Revision 1.140  2011/09/02 10:37:54  brouard
                    408:   Summary: times.h is ok with mingw32 now.
                    409: 
1.140     brouard   410:   Revision 1.139  2010/06/14 07:50:17  brouard
                    411:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    412:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    413: 
1.139     brouard   414:   Revision 1.138  2010/04/30 18:19:40  brouard
                    415:   *** empty log message ***
                    416: 
1.138     brouard   417:   Revision 1.137  2010/04/29 18:11:38  brouard
                    418:   (Module): Checking covariates for more complex models
                    419:   than V1+V2. A lot of change to be done. Unstable.
                    420: 
1.137     brouard   421:   Revision 1.136  2010/04/26 20:30:53  brouard
                    422:   (Module): merging some libgsl code. Fixing computation
                    423:   of likelione (using inter/intrapolation if mle = 0) in order to
                    424:   get same likelihood as if mle=1.
                    425:   Some cleaning of code and comments added.
                    426: 
1.136     brouard   427:   Revision 1.135  2009/10/29 15:33:14  brouard
                    428:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    429: 
1.135     brouard   430:   Revision 1.134  2009/10/29 13:18:53  brouard
                    431:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    432: 
1.134     brouard   433:   Revision 1.133  2009/07/06 10:21:25  brouard
                    434:   just nforces
                    435: 
1.133     brouard   436:   Revision 1.132  2009/07/06 08:22:05  brouard
                    437:   Many tings
                    438: 
1.132     brouard   439:   Revision 1.131  2009/06/20 16:22:47  brouard
                    440:   Some dimensions resccaled
                    441: 
1.131     brouard   442:   Revision 1.130  2009/05/26 06:44:34  brouard
                    443:   (Module): Max Covariate is now set to 20 instead of 8. A
                    444:   lot of cleaning with variables initialized to 0. Trying to make
                    445:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    446: 
1.130     brouard   447:   Revision 1.129  2007/08/31 13:49:27  lievre
                    448:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    449: 
1.129     lievre    450:   Revision 1.128  2006/06/30 13:02:05  brouard
                    451:   (Module): Clarifications on computing e.j
                    452: 
1.128     brouard   453:   Revision 1.127  2006/04/28 18:11:50  brouard
                    454:   (Module): Yes the sum of survivors was wrong since
                    455:   imach-114 because nhstepm was no more computed in the age
                    456:   loop. Now we define nhstepma in the age loop.
                    457:   (Module): In order to speed up (in case of numerous covariates) we
                    458:   compute health expectancies (without variances) in a first step
                    459:   and then all the health expectancies with variances or standard
                    460:   deviation (needs data from the Hessian matrices) which slows the
                    461:   computation.
                    462:   In the future we should be able to stop the program is only health
                    463:   expectancies and graph are needed without standard deviations.
                    464: 
1.127     brouard   465:   Revision 1.126  2006/04/28 17:23:28  brouard
                    466:   (Module): Yes the sum of survivors was wrong since
                    467:   imach-114 because nhstepm was no more computed in the age
                    468:   loop. Now we define nhstepma in the age loop.
                    469:   Version 0.98h
                    470: 
1.126     brouard   471:   Revision 1.125  2006/04/04 15:20:31  lievre
                    472:   Errors in calculation of health expectancies. Age was not initialized.
                    473:   Forecasting file added.
                    474: 
                    475:   Revision 1.124  2006/03/22 17:13:53  lievre
                    476:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    477:   The log-likelihood is printed in the log file
                    478: 
                    479:   Revision 1.123  2006/03/20 10:52:43  brouard
                    480:   * imach.c (Module): <title> changed, corresponds to .htm file
                    481:   name. <head> headers where missing.
                    482: 
                    483:   * imach.c (Module): Weights can have a decimal point as for
                    484:   English (a comma might work with a correct LC_NUMERIC environment,
                    485:   otherwise the weight is truncated).
                    486:   Modification of warning when the covariates values are not 0 or
                    487:   1.
                    488:   Version 0.98g
                    489: 
                    490:   Revision 1.122  2006/03/20 09:45:41  brouard
                    491:   (Module): Weights can have a decimal point as for
                    492:   English (a comma might work with a correct LC_NUMERIC environment,
                    493:   otherwise the weight is truncated).
                    494:   Modification of warning when the covariates values are not 0 or
                    495:   1.
                    496:   Version 0.98g
                    497: 
                    498:   Revision 1.121  2006/03/16 17:45:01  lievre
                    499:   * imach.c (Module): Comments concerning covariates added
                    500: 
                    501:   * imach.c (Module): refinements in the computation of lli if
                    502:   status=-2 in order to have more reliable computation if stepm is
                    503:   not 1 month. Version 0.98f
                    504: 
                    505:   Revision 1.120  2006/03/16 15:10:38  lievre
                    506:   (Module): refinements in the computation of lli if
                    507:   status=-2 in order to have more reliable computation if stepm is
                    508:   not 1 month. Version 0.98f
                    509: 
                    510:   Revision 1.119  2006/03/15 17:42:26  brouard
                    511:   (Module): Bug if status = -2, the loglikelihood was
                    512:   computed as likelihood omitting the logarithm. Version O.98e
                    513: 
                    514:   Revision 1.118  2006/03/14 18:20:07  brouard
                    515:   (Module): varevsij Comments added explaining the second
                    516:   table of variances if popbased=1 .
                    517:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    518:   (Module): Function pstamp added
                    519:   (Module): Version 0.98d
                    520: 
                    521:   Revision 1.117  2006/03/14 17:16:22  brouard
                    522:   (Module): varevsij Comments added explaining the second
                    523:   table of variances if popbased=1 .
                    524:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    525:   (Module): Function pstamp added
                    526:   (Module): Version 0.98d
                    527: 
                    528:   Revision 1.116  2006/03/06 10:29:27  brouard
                    529:   (Module): Variance-covariance wrong links and
                    530:   varian-covariance of ej. is needed (Saito).
                    531: 
                    532:   Revision 1.115  2006/02/27 12:17:45  brouard
                    533:   (Module): One freematrix added in mlikeli! 0.98c
                    534: 
                    535:   Revision 1.114  2006/02/26 12:57:58  brouard
                    536:   (Module): Some improvements in processing parameter
                    537:   filename with strsep.
                    538: 
                    539:   Revision 1.113  2006/02/24 14:20:24  brouard
                    540:   (Module): Memory leaks checks with valgrind and:
                    541:   datafile was not closed, some imatrix were not freed and on matrix
                    542:   allocation too.
                    543: 
                    544:   Revision 1.112  2006/01/30 09:55:26  brouard
                    545:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    546: 
                    547:   Revision 1.111  2006/01/25 20:38:18  brouard
                    548:   (Module): Lots of cleaning and bugs added (Gompertz)
                    549:   (Module): Comments can be added in data file. Missing date values
                    550:   can be a simple dot '.'.
                    551: 
                    552:   Revision 1.110  2006/01/25 00:51:50  brouard
                    553:   (Module): Lots of cleaning and bugs added (Gompertz)
                    554: 
                    555:   Revision 1.109  2006/01/24 19:37:15  brouard
                    556:   (Module): Comments (lines starting with a #) are allowed in data.
                    557: 
                    558:   Revision 1.108  2006/01/19 18:05:42  lievre
                    559:   Gnuplot problem appeared...
                    560:   To be fixed
                    561: 
                    562:   Revision 1.107  2006/01/19 16:20:37  brouard
                    563:   Test existence of gnuplot in imach path
                    564: 
                    565:   Revision 1.106  2006/01/19 13:24:36  brouard
                    566:   Some cleaning and links added in html output
                    567: 
                    568:   Revision 1.105  2006/01/05 20:23:19  lievre
                    569:   *** empty log message ***
                    570: 
                    571:   Revision 1.104  2005/09/30 16:11:43  lievre
                    572:   (Module): sump fixed, loop imx fixed, and simplifications.
                    573:   (Module): If the status is missing at the last wave but we know
                    574:   that the person is alive, then we can code his/her status as -2
                    575:   (instead of missing=-1 in earlier versions) and his/her
                    576:   contributions to the likelihood is 1 - Prob of dying from last
                    577:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    578:   the healthy state at last known wave). Version is 0.98
                    579: 
                    580:   Revision 1.103  2005/09/30 15:54:49  lievre
                    581:   (Module): sump fixed, loop imx fixed, and simplifications.
                    582: 
                    583:   Revision 1.102  2004/09/15 17:31:30  brouard
                    584:   Add the possibility to read data file including tab characters.
                    585: 
                    586:   Revision 1.101  2004/09/15 10:38:38  brouard
                    587:   Fix on curr_time
                    588: 
                    589:   Revision 1.100  2004/07/12 18:29:06  brouard
                    590:   Add version for Mac OS X. Just define UNIX in Makefile
                    591: 
                    592:   Revision 1.99  2004/06/05 08:57:40  brouard
                    593:   *** empty log message ***
                    594: 
                    595:   Revision 1.98  2004/05/16 15:05:56  brouard
                    596:   New version 0.97 . First attempt to estimate force of mortality
                    597:   directly from the data i.e. without the need of knowing the health
                    598:   state at each age, but using a Gompertz model: log u =a + b*age .
                    599:   This is the basic analysis of mortality and should be done before any
                    600:   other analysis, in order to test if the mortality estimated from the
                    601:   cross-longitudinal survey is different from the mortality estimated
                    602:   from other sources like vital statistic data.
                    603: 
                    604:   The same imach parameter file can be used but the option for mle should be -3.
                    605: 
1.133     brouard   606:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   607:   former routines in order to include the new code within the former code.
                    608: 
                    609:   The output is very simple: only an estimate of the intercept and of
                    610:   the slope with 95% confident intervals.
                    611: 
                    612:   Current limitations:
                    613:   A) Even if you enter covariates, i.e. with the
                    614:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    615:   B) There is no computation of Life Expectancy nor Life Table.
                    616: 
                    617:   Revision 1.97  2004/02/20 13:25:42  lievre
                    618:   Version 0.96d. Population forecasting command line is (temporarily)
                    619:   suppressed.
                    620: 
                    621:   Revision 1.96  2003/07/15 15:38:55  brouard
                    622:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    623:   rewritten within the same printf. Workaround: many printfs.
                    624: 
                    625:   Revision 1.95  2003/07/08 07:54:34  brouard
                    626:   * imach.c (Repository):
                    627:   (Repository): Using imachwizard code to output a more meaningful covariance
                    628:   matrix (cov(a12,c31) instead of numbers.
                    629: 
                    630:   Revision 1.94  2003/06/27 13:00:02  brouard
                    631:   Just cleaning
                    632: 
                    633:   Revision 1.93  2003/06/25 16:33:55  brouard
                    634:   (Module): On windows (cygwin) function asctime_r doesn't
                    635:   exist so I changed back to asctime which exists.
                    636:   (Module): Version 0.96b
                    637: 
                    638:   Revision 1.92  2003/06/25 16:30:45  brouard
                    639:   (Module): On windows (cygwin) function asctime_r doesn't
                    640:   exist so I changed back to asctime which exists.
                    641: 
                    642:   Revision 1.91  2003/06/25 15:30:29  brouard
                    643:   * imach.c (Repository): Duplicated warning errors corrected.
                    644:   (Repository): Elapsed time after each iteration is now output. It
                    645:   helps to forecast when convergence will be reached. Elapsed time
                    646:   is stamped in powell.  We created a new html file for the graphs
                    647:   concerning matrix of covariance. It has extension -cov.htm.
                    648: 
                    649:   Revision 1.90  2003/06/24 12:34:15  brouard
                    650:   (Module): Some bugs corrected for windows. Also, when
                    651:   mle=-1 a template is output in file "or"mypar.txt with the design
                    652:   of the covariance matrix to be input.
                    653: 
                    654:   Revision 1.89  2003/06/24 12:30:52  brouard
                    655:   (Module): Some bugs corrected for windows. Also, when
                    656:   mle=-1 a template is output in file "or"mypar.txt with the design
                    657:   of the covariance matrix to be input.
                    658: 
                    659:   Revision 1.88  2003/06/23 17:54:56  brouard
                    660:   * 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.
                    661: 
                    662:   Revision 1.87  2003/06/18 12:26:01  brouard
                    663:   Version 0.96
                    664: 
                    665:   Revision 1.86  2003/06/17 20:04:08  brouard
                    666:   (Module): Change position of html and gnuplot routines and added
                    667:   routine fileappend.
                    668: 
                    669:   Revision 1.85  2003/06/17 13:12:43  brouard
                    670:   * imach.c (Repository): Check when date of death was earlier that
                    671:   current date of interview. It may happen when the death was just
                    672:   prior to the death. In this case, dh was negative and likelihood
                    673:   was wrong (infinity). We still send an "Error" but patch by
                    674:   assuming that the date of death was just one stepm after the
                    675:   interview.
                    676:   (Repository): Because some people have very long ID (first column)
                    677:   we changed int to long in num[] and we added a new lvector for
                    678:   memory allocation. But we also truncated to 8 characters (left
                    679:   truncation)
                    680:   (Repository): No more line truncation errors.
                    681: 
                    682:   Revision 1.84  2003/06/13 21:44:43  brouard
                    683:   * imach.c (Repository): Replace "freqsummary" at a correct
                    684:   place. It differs from routine "prevalence" which may be called
                    685:   many times. Probs is memory consuming and must be used with
                    686:   parcimony.
                    687:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    688: 
                    689:   Revision 1.83  2003/06/10 13:39:11  lievre
                    690:   *** empty log message ***
                    691: 
                    692:   Revision 1.82  2003/06/05 15:57:20  brouard
                    693:   Add log in  imach.c and  fullversion number is now printed.
                    694: 
                    695: */
                    696: /*
                    697:    Interpolated Markov Chain
                    698: 
                    699:   Short summary of the programme:
                    700:   
1.227     brouard   701:   This program computes Healthy Life Expectancies or State-specific
                    702:   (if states aren't health statuses) Expectancies from
                    703:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    704: 
                    705:   -1- a first survey ("cross") where individuals from different ages
                    706:   are interviewed on their health status or degree of disability (in
                    707:   the case of a health survey which is our main interest)
                    708: 
                    709:   -2- at least a second wave of interviews ("longitudinal") which
                    710:   measure each change (if any) in individual health status.  Health
                    711:   expectancies are computed from the time spent in each health state
                    712:   according to a model. More health states you consider, more time is
                    713:   necessary to reach the Maximum Likelihood of the parameters involved
                    714:   in the model.  The simplest model is the multinomial logistic model
                    715:   where pij is the probability to be observed in state j at the second
                    716:   wave conditional to be observed in state i at the first
                    717:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    718:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    719:   have a more complex model than "constant and age", you should modify
                    720:   the program where the markup *Covariates have to be included here
                    721:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   722:   convergence.
                    723: 
                    724:   The advantage of this computer programme, compared to a simple
                    725:   multinomial logistic model, is clear when the delay between waves is not
                    726:   identical for each individual. Also, if a individual missed an
                    727:   intermediate interview, the information is lost, but taken into
                    728:   account using an interpolation or extrapolation.  
                    729: 
                    730:   hPijx is the probability to be observed in state i at age x+h
                    731:   conditional to the observed state i at age x. The delay 'h' can be
                    732:   split into an exact number (nh*stepm) of unobserved intermediate
                    733:   states. This elementary transition (by month, quarter,
                    734:   semester or year) is modelled as a multinomial logistic.  The hPx
                    735:   matrix is simply the matrix product of nh*stepm elementary matrices
                    736:   and the contribution of each individual to the likelihood is simply
                    737:   hPijx.
                    738: 
                    739:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   740:   of the life expectancies. It also computes the period (stable) prevalence.
                    741: 
                    742: Back prevalence and projections:
1.227     brouard   743: 
                    744:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    745:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    746:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    747:    mobilavproj)
                    748: 
                    749:     Computes the back prevalence limit for any combination of
                    750:     covariate values k at any age between ageminpar and agemaxpar and
                    751:     returns it in **bprlim. In the loops,
                    752: 
                    753:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    754:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    755: 
                    756:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   757:    Computes for any combination of covariates k and any age between bage and fage 
                    758:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    759:                        oldm=oldms;savm=savms;
1.227     brouard   760: 
                    761:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   762:      Computes the transition matrix starting at age 'age' over
                    763:      'nhstepm*hstepm*stepm' months (i.e. until
                    764:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   765:      nhstepm*hstepm matrices. 
                    766: 
                    767:      Returns p3mat[i][j][h] after calling
                    768:      p3mat[i][j][h]=matprod2(newm,
                    769:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    770:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    771:      oldm);
1.226     brouard   772: 
                    773: Important routines
                    774: 
                    775: - func (or funcone), computes logit (pij) distinguishing
                    776:   o fixed variables (single or product dummies or quantitative);
                    777:   o varying variables by:
                    778:    (1) wave (single, product dummies, quantitative), 
                    779:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    780:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    781:        % varying dummy (not done) or quantitative (not done);
                    782: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    783:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    784: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    785:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    786:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   787: 
1.226     brouard   788: 
                    789:   
1.133     brouard   790:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    791:            Institut national d'études démographiques, Paris.
1.126     brouard   792:   This software have been partly granted by Euro-REVES, a concerted action
                    793:   from the European Union.
                    794:   It is copyrighted identically to a GNU software product, ie programme and
                    795:   software can be distributed freely for non commercial use. Latest version
                    796:   can be accessed at http://euroreves.ined.fr/imach .
                    797: 
                    798:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    799:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    800:   
                    801:   **********************************************************************/
                    802: /*
                    803:   main
                    804:   read parameterfile
                    805:   read datafile
                    806:   concatwav
                    807:   freqsummary
                    808:   if (mle >= 1)
                    809:     mlikeli
                    810:   print results files
                    811:   if mle==1 
                    812:      computes hessian
                    813:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    814:       begin-prev-date,...
                    815:   open gnuplot file
                    816:   open html file
1.145     brouard   817:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    818:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    819:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    820:     freexexit2 possible for memory heap.
                    821: 
                    822:   h Pij x                         | pij_nom  ficrestpij
                    823:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    824:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    825:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    826: 
                    827:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    828:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    829:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    830:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    831:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    832: 
1.126     brouard   833:   forecasting if prevfcast==1 prevforecast call prevalence()
                    834:   health expectancies
                    835:   Variance-covariance of DFLE
                    836:   prevalence()
                    837:    movingaverage()
                    838:   varevsij() 
                    839:   if popbased==1 varevsij(,popbased)
                    840:   total life expectancies
                    841:   Variance of period (stable) prevalence
                    842:  end
                    843: */
                    844: 
1.187     brouard   845: /* #define DEBUG */
                    846: /* #define DEBUGBRENT */
1.203     brouard   847: /* #define DEBUGLINMIN */
                    848: /* #define DEBUGHESS */
                    849: #define DEBUGHESSIJ
1.224     brouard   850: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   851: #define POWELL /* Instead of NLOPT */
1.224     brouard   852: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   853: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    854: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   855: 
                    856: #include <math.h>
                    857: #include <stdio.h>
                    858: #include <stdlib.h>
                    859: #include <string.h>
1.226     brouard   860: #include <ctype.h>
1.159     brouard   861: 
                    862: #ifdef _WIN32
                    863: #include <io.h>
1.172     brouard   864: #include <windows.h>
                    865: #include <tchar.h>
1.159     brouard   866: #else
1.126     brouard   867: #include <unistd.h>
1.159     brouard   868: #endif
1.126     brouard   869: 
                    870: #include <limits.h>
                    871: #include <sys/types.h>
1.171     brouard   872: 
                    873: #if defined(__GNUC__)
                    874: #include <sys/utsname.h> /* Doesn't work on Windows */
                    875: #endif
                    876: 
1.126     brouard   877: #include <sys/stat.h>
                    878: #include <errno.h>
1.159     brouard   879: /* extern int errno; */
1.126     brouard   880: 
1.157     brouard   881: /* #ifdef LINUX */
                    882: /* #include <time.h> */
                    883: /* #include "timeval.h" */
                    884: /* #else */
                    885: /* #include <sys/time.h> */
                    886: /* #endif */
                    887: 
1.126     brouard   888: #include <time.h>
                    889: 
1.136     brouard   890: #ifdef GSL
                    891: #include <gsl/gsl_errno.h>
                    892: #include <gsl/gsl_multimin.h>
                    893: #endif
                    894: 
1.167     brouard   895: 
1.162     brouard   896: #ifdef NLOPT
                    897: #include <nlopt.h>
                    898: typedef struct {
                    899:   double (* function)(double [] );
                    900: } myfunc_data ;
                    901: #endif
                    902: 
1.126     brouard   903: /* #include <libintl.h> */
                    904: /* #define _(String) gettext (String) */
                    905: 
1.141     brouard   906: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   907: 
                    908: #define GNUPLOTPROGRAM "gnuplot"
                    909: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    910: #define FILENAMELENGTH 132
                    911: 
                    912: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    913: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    914: 
1.144     brouard   915: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    916: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   917: 
                    918: #define NINTERVMAX 8
1.144     brouard   919: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    920: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    921: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   922: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   923: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    924: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   925: #define MAXN 20000
1.144     brouard   926: #define YEARM 12. /**< Number of months per year */
1.218     brouard   927: /* #define AGESUP 130 */
                    928: #define AGESUP 150
                    929: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   930: #define AGEBASE 40
1.194     brouard   931: #define AGEOVERFLOW 1.e20
1.164     brouard   932: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   933: #ifdef _WIN32
                    934: #define DIRSEPARATOR '\\'
                    935: #define CHARSEPARATOR "\\"
                    936: #define ODIRSEPARATOR '/'
                    937: #else
1.126     brouard   938: #define DIRSEPARATOR '/'
                    939: #define CHARSEPARATOR "/"
                    940: #define ODIRSEPARATOR '\\'
                    941: #endif
                    942: 
1.247   ! brouard   943: /* $Id: imach.c,v 1.246 2016/09/02 08:49:22 brouard Exp $ */
1.126     brouard   944: /* $State: Exp $ */
1.196     brouard   945: #include "version.h"
                    946: char version[]=__IMACH_VERSION__;
1.224     brouard   947: 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.247   ! brouard   948: char fullversion[]="$Revision: 1.246 $ $Date: 2016/09/02 08:49:22 $"; 
1.126     brouard   949: char strstart[80];
                    950: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   951: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   952: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   953: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    954: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    955: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   956: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    957: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   958: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    959: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    960: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   961: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    962: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   963: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   964: int nsd=0; /**< Total number of single dummy variables (output) */
                    965: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   966: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   967: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   968: int ntveff=0; /**< ntveff number of effective time varying variables */
                    969: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   970: int cptcov=0; /* Working variable */
1.218     brouard   971: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   972: int npar=NPARMAX;
                    973: int nlstate=2; /* Number of live states */
                    974: int ndeath=1; /* Number of dead states */
1.130     brouard   975: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   976: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   977: int popbased=0;
                    978: 
                    979: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   980: int maxwav=0; /* Maxim number of waves */
                    981: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    982: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    983: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   984:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   985: int mle=1, weightopt=0;
1.126     brouard   986: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    987: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    988: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    989:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   990: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   991: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    992: 
1.130     brouard   993: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   994: double **matprod2(); /* test */
1.126     brouard   995: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    996: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   997: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    998: 
1.136     brouard   999: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1000: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1001: FILE *ficlog, *ficrespow;
1.130     brouard  1002: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1003: double fretone; /* Only one call to likelihood */
1.130     brouard  1004: long ipmx=0; /* Number of contributions */
1.126     brouard  1005: double sw; /* Sum of weights */
                   1006: char filerespow[FILENAMELENGTH];
                   1007: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1008: FILE *ficresilk;
                   1009: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1010: FILE *ficresprobmorprev;
                   1011: FILE *fichtm, *fichtmcov; /* Html File */
                   1012: FILE *ficreseij;
                   1013: char filerese[FILENAMELENGTH];
                   1014: FILE *ficresstdeij;
                   1015: char fileresstde[FILENAMELENGTH];
                   1016: FILE *ficrescveij;
                   1017: char filerescve[FILENAMELENGTH];
                   1018: FILE  *ficresvij;
                   1019: char fileresv[FILENAMELENGTH];
                   1020: FILE  *ficresvpl;
                   1021: char fileresvpl[FILENAMELENGTH];
                   1022: char title[MAXLINE];
1.234     brouard  1023: char model[MAXLINE]; /**< The model line */
1.217     brouard  1024: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1025: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1026: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1027: char command[FILENAMELENGTH];
                   1028: int  outcmd=0;
                   1029: 
1.217     brouard  1030: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1031: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1032: char filelog[FILENAMELENGTH]; /* Log file */
                   1033: char filerest[FILENAMELENGTH];
                   1034: char fileregp[FILENAMELENGTH];
                   1035: char popfile[FILENAMELENGTH];
                   1036: 
                   1037: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1038: 
1.157     brouard  1039: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1040: /* struct timezone tzp; */
                   1041: /* extern int gettimeofday(); */
                   1042: struct tm tml, *gmtime(), *localtime();
                   1043: 
                   1044: extern time_t time();
                   1045: 
                   1046: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1047: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1048: struct tm tm;
                   1049: 
1.126     brouard  1050: char strcurr[80], strfor[80];
                   1051: 
                   1052: char *endptr;
                   1053: long lval;
                   1054: double dval;
                   1055: 
                   1056: #define NR_END 1
                   1057: #define FREE_ARG char*
                   1058: #define FTOL 1.0e-10
                   1059: 
                   1060: #define NRANSI 
1.240     brouard  1061: #define ITMAX 200
                   1062: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1063: 
                   1064: #define TOL 2.0e-4 
                   1065: 
                   1066: #define CGOLD 0.3819660 
                   1067: #define ZEPS 1.0e-10 
                   1068: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1069: 
                   1070: #define GOLD 1.618034 
                   1071: #define GLIMIT 100.0 
                   1072: #define TINY 1.0e-20 
                   1073: 
                   1074: static double maxarg1,maxarg2;
                   1075: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1076: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1077:   
                   1078: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1079: #define rint(a) floor(a+0.5)
1.166     brouard  1080: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1081: #define mytinydouble 1.0e-16
1.166     brouard  1082: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1083: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1084: /* static double dsqrarg; */
                   1085: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1086: static double sqrarg;
                   1087: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1088: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1089: int agegomp= AGEGOMP;
                   1090: 
                   1091: int imx; 
                   1092: int stepm=1;
                   1093: /* Stepm, step in month: minimum step interpolation*/
                   1094: 
                   1095: int estepm;
                   1096: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1097: 
                   1098: int m,nb;
                   1099: long *num;
1.197     brouard  1100: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1101: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1102:                   covariate for which somebody answered excluding 
                   1103:                   undefined. Usually 2: 0 and 1. */
                   1104: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1105:                             covariate for which somebody answered including 
                   1106:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1107: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1108: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1109: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1110: double *ageexmed,*agecens;
                   1111: double dateintmean=0;
                   1112: 
                   1113: double *weight;
                   1114: int **s; /* Status */
1.141     brouard  1115: double *agedc;
1.145     brouard  1116: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1117:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1118:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1119: double **coqvar; /* Fixed quantitative covariate iqv */
                   1120: double ***cotvar; /* Time varying covariate itv */
                   1121: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1122: double  idx; 
                   1123: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1124: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1125: /*k          1  2   3   4     5    6    7     8    9 */
                   1126: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1127: /* Tndvar[k]    1   2   3               4          5 */
                   1128: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1129: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1130: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1131: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1132: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1133: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1134: /* Tprod[i]=k           4               7            */
                   1135: /* Tage[i]=k                  5               8      */
                   1136: /* */
                   1137: /* Type                    */
                   1138: /* V         1  2  3  4  5 */
                   1139: /*           F  F  V  V  V */
                   1140: /*           D  Q  D  D  Q */
                   1141: /*                         */
                   1142: int *TvarsD;
                   1143: int *TvarsDind;
                   1144: int *TvarsQ;
                   1145: int *TvarsQind;
                   1146: 
1.235     brouard  1147: #define MAXRESULTLINES 10
                   1148: int nresult=0;
                   1149: int TKresult[MAXRESULTLINES];
1.237     brouard  1150: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1151: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1152: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1153: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1154: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1155: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1156: 
1.234     brouard  1157: /* 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  1158: 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 */
                   1159: 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 */
                   1160: 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 */
                   1161: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1162: 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 */
                   1163: 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  1164: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1165: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1166: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1167: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1168: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1169: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1170: 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 */
                   1171: 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 */
                   1172: 
1.230     brouard  1173: int *Tvarsel; /**< Selected covariates for output */
                   1174: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1175: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1176: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1177: 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  1178: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1179: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1180: int *Tage;
1.227     brouard  1181: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1182: 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  1183: 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*/ 
                   1184: 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  1185: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1186: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1187: int **Tvard;
                   1188: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1189: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1190: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1191:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1192:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1193: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1194: double *lsurv, *lpop, *tpop;
                   1195: 
1.231     brouard  1196: #define FD 1; /* Fixed dummy covariate */
                   1197: #define FQ 2; /* Fixed quantitative covariate */
                   1198: #define FP 3; /* Fixed product covariate */
                   1199: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1200: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1201: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1202: #define VD 10; /* Varying dummy covariate */
                   1203: #define VQ 11; /* Varying quantitative covariate */
                   1204: #define VP 12; /* Varying product covariate */
                   1205: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1206: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1207: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1208: #define APFD 16; /* Age product * fixed dummy covariate */
                   1209: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1210: #define APVD 18; /* Age product * varying dummy covariate */
                   1211: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1212: 
                   1213: #define FTYPE 1; /* Fixed covariate */
                   1214: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1215: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1216: 
                   1217: struct kmodel{
                   1218:        int maintype; /* main type */
                   1219:        int subtype; /* subtype */
                   1220: };
                   1221: struct kmodel modell[NCOVMAX];
                   1222: 
1.143     brouard  1223: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1224: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1225: 
                   1226: /**************** split *************************/
                   1227: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1228: {
                   1229:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1230:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1231:   */ 
                   1232:   char *ss;                            /* pointer */
1.186     brouard  1233:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1234: 
                   1235:   l1 = strlen(path );                  /* length of path */
                   1236:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1237:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1238:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1239:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1240:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1241:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1242:     /* get current working directory */
                   1243:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1244: #ifdef WIN32
                   1245:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1246: #else
                   1247:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1248: #endif
1.126     brouard  1249:       return( GLOCK_ERROR_GETCWD );
                   1250:     }
                   1251:     /* got dirc from getcwd*/
                   1252:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1253:   } else {                             /* strip directory from path */
1.126     brouard  1254:     ss++;                              /* after this, the filename */
                   1255:     l2 = strlen( ss );                 /* length of filename */
                   1256:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1257:     strcpy( name, ss );                /* save file name */
                   1258:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1259:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1260:     printf(" DIRC2 = %s \n",dirc);
                   1261:   }
                   1262:   /* We add a separator at the end of dirc if not exists */
                   1263:   l1 = strlen( dirc );                 /* length of directory */
                   1264:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1265:     dirc[l1] =  DIRSEPARATOR;
                   1266:     dirc[l1+1] = 0; 
                   1267:     printf(" DIRC3 = %s \n",dirc);
                   1268:   }
                   1269:   ss = strrchr( name, '.' );           /* find last / */
                   1270:   if (ss >0){
                   1271:     ss++;
                   1272:     strcpy(ext,ss);                    /* save extension */
                   1273:     l1= strlen( name);
                   1274:     l2= strlen(ss)+1;
                   1275:     strncpy( finame, name, l1-l2);
                   1276:     finame[l1-l2]= 0;
                   1277:   }
                   1278: 
                   1279:   return( 0 );                         /* we're done */
                   1280: }
                   1281: 
                   1282: 
                   1283: /******************************************/
                   1284: 
                   1285: void replace_back_to_slash(char *s, char*t)
                   1286: {
                   1287:   int i;
                   1288:   int lg=0;
                   1289:   i=0;
                   1290:   lg=strlen(t);
                   1291:   for(i=0; i<= lg; i++) {
                   1292:     (s[i] = t[i]);
                   1293:     if (t[i]== '\\') s[i]='/';
                   1294:   }
                   1295: }
                   1296: 
1.132     brouard  1297: char *trimbb(char *out, char *in)
1.137     brouard  1298: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1299:   char *s;
                   1300:   s=out;
                   1301:   while (*in != '\0'){
1.137     brouard  1302:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1303:       in++;
                   1304:     }
                   1305:     *out++ = *in++;
                   1306:   }
                   1307:   *out='\0';
                   1308:   return s;
                   1309: }
                   1310: 
1.187     brouard  1311: /* char *substrchaine(char *out, char *in, char *chain) */
                   1312: /* { */
                   1313: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1314: /*   char *s, *t; */
                   1315: /*   t=in;s=out; */
                   1316: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1317: /*     *out++ = *in++; */
                   1318: /*   } */
                   1319: 
                   1320: /*   /\* *in matches *chain *\/ */
                   1321: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1322: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1323: /*   } */
                   1324: /*   in--; chain--; */
                   1325: /*   while ( (*in != '\0')){ */
                   1326: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1327: /*     *out++ = *in++; */
                   1328: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1329: /*   } */
                   1330: /*   *out='\0'; */
                   1331: /*   out=s; */
                   1332: /*   return out; */
                   1333: /* } */
                   1334: char *substrchaine(char *out, char *in, char *chain)
                   1335: {
                   1336:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1337:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1338: 
                   1339:   char *strloc;
                   1340: 
                   1341:   strcpy (out, in); 
                   1342:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1343:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1344:   if(strloc != NULL){ 
                   1345:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1346:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1347:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1348:   }
                   1349:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1350:   return out;
                   1351: }
                   1352: 
                   1353: 
1.145     brouard  1354: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1355: {
1.187     brouard  1356:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1357:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1358:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1359:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1360:   */
1.160     brouard  1361:   char *s, *t;
1.145     brouard  1362:   t=in;s=in;
                   1363:   while ((*in != occ) && (*in != '\0')){
                   1364:     *alocc++ = *in++;
                   1365:   }
                   1366:   if( *in == occ){
                   1367:     *(alocc)='\0';
                   1368:     s=++in;
                   1369:   }
                   1370:  
                   1371:   if (s == t) {/* occ not found */
                   1372:     *(alocc-(in-s))='\0';
                   1373:     in=s;
                   1374:   }
                   1375:   while ( *in != '\0'){
                   1376:     *blocc++ = *in++;
                   1377:   }
                   1378: 
                   1379:   *blocc='\0';
                   1380:   return t;
                   1381: }
1.137     brouard  1382: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1383: {
1.187     brouard  1384:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1385:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1386:      gives blocc="abcdef2ghi" and alocc="j".
                   1387:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1388:   */
                   1389:   char *s, *t;
                   1390:   t=in;s=in;
                   1391:   while (*in != '\0'){
                   1392:     while( *in == occ){
                   1393:       *blocc++ = *in++;
                   1394:       s=in;
                   1395:     }
                   1396:     *blocc++ = *in++;
                   1397:   }
                   1398:   if (s == t) /* occ not found */
                   1399:     *(blocc-(in-s))='\0';
                   1400:   else
                   1401:     *(blocc-(in-s)-1)='\0';
                   1402:   in=s;
                   1403:   while ( *in != '\0'){
                   1404:     *alocc++ = *in++;
                   1405:   }
                   1406: 
                   1407:   *alocc='\0';
                   1408:   return s;
                   1409: }
                   1410: 
1.126     brouard  1411: int nbocc(char *s, char occ)
                   1412: {
                   1413:   int i,j=0;
                   1414:   int lg=20;
                   1415:   i=0;
                   1416:   lg=strlen(s);
                   1417:   for(i=0; i<= lg; i++) {
1.234     brouard  1418:     if  (s[i] == occ ) j++;
1.126     brouard  1419:   }
                   1420:   return j;
                   1421: }
                   1422: 
1.137     brouard  1423: /* void cutv(char *u,char *v, char*t, char occ) */
                   1424: /* { */
                   1425: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1426: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1427: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1428: /*   int i,lg,j,p=0; */
                   1429: /*   i=0; */
                   1430: /*   lg=strlen(t); */
                   1431: /*   for(j=0; j<=lg-1; j++) { */
                   1432: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1433: /*   } */
1.126     brouard  1434: 
1.137     brouard  1435: /*   for(j=0; j<p; j++) { */
                   1436: /*     (u[j] = t[j]); */
                   1437: /*   } */
                   1438: /*      u[p]='\0'; */
1.126     brouard  1439: 
1.137     brouard  1440: /*    for(j=0; j<= lg; j++) { */
                   1441: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1442: /*   } */
                   1443: /* } */
1.126     brouard  1444: 
1.160     brouard  1445: #ifdef _WIN32
                   1446: char * strsep(char **pp, const char *delim)
                   1447: {
                   1448:   char *p, *q;
                   1449:          
                   1450:   if ((p = *pp) == NULL)
                   1451:     return 0;
                   1452:   if ((q = strpbrk (p, delim)) != NULL)
                   1453:   {
                   1454:     *pp = q + 1;
                   1455:     *q = '\0';
                   1456:   }
                   1457:   else
                   1458:     *pp = 0;
                   1459:   return p;
                   1460: }
                   1461: #endif
                   1462: 
1.126     brouard  1463: /********************** nrerror ********************/
                   1464: 
                   1465: void nrerror(char error_text[])
                   1466: {
                   1467:   fprintf(stderr,"ERREUR ...\n");
                   1468:   fprintf(stderr,"%s\n",error_text);
                   1469:   exit(EXIT_FAILURE);
                   1470: }
                   1471: /*********************** vector *******************/
                   1472: double *vector(int nl, int nh)
                   1473: {
                   1474:   double *v;
                   1475:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1476:   if (!v) nrerror("allocation failure in vector");
                   1477:   return v-nl+NR_END;
                   1478: }
                   1479: 
                   1480: /************************ free vector ******************/
                   1481: void free_vector(double*v, int nl, int nh)
                   1482: {
                   1483:   free((FREE_ARG)(v+nl-NR_END));
                   1484: }
                   1485: 
                   1486: /************************ivector *******************************/
                   1487: int *ivector(long nl,long nh)
                   1488: {
                   1489:   int *v;
                   1490:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1491:   if (!v) nrerror("allocation failure in ivector");
                   1492:   return v-nl+NR_END;
                   1493: }
                   1494: 
                   1495: /******************free ivector **************************/
                   1496: void free_ivector(int *v, long nl, long nh)
                   1497: {
                   1498:   free((FREE_ARG)(v+nl-NR_END));
                   1499: }
                   1500: 
                   1501: /************************lvector *******************************/
                   1502: long *lvector(long nl,long nh)
                   1503: {
                   1504:   long *v;
                   1505:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1506:   if (!v) nrerror("allocation failure in ivector");
                   1507:   return v-nl+NR_END;
                   1508: }
                   1509: 
                   1510: /******************free lvector **************************/
                   1511: void free_lvector(long *v, long nl, long nh)
                   1512: {
                   1513:   free((FREE_ARG)(v+nl-NR_END));
                   1514: }
                   1515: 
                   1516: /******************* imatrix *******************************/
                   1517: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1518:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1519: { 
                   1520:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1521:   int **m; 
                   1522:   
                   1523:   /* allocate pointers to rows */ 
                   1524:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1525:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1526:   m += NR_END; 
                   1527:   m -= nrl; 
                   1528:   
                   1529:   
                   1530:   /* allocate rows and set pointers to them */ 
                   1531:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1532:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1533:   m[nrl] += NR_END; 
                   1534:   m[nrl] -= ncl; 
                   1535:   
                   1536:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1537:   
                   1538:   /* return pointer to array of pointers to rows */ 
                   1539:   return m; 
                   1540: } 
                   1541: 
                   1542: /****************** free_imatrix *************************/
                   1543: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1544:       int **m;
                   1545:       long nch,ncl,nrh,nrl; 
                   1546:      /* free an int matrix allocated by imatrix() */ 
                   1547: { 
                   1548:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1549:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1550: } 
                   1551: 
                   1552: /******************* matrix *******************************/
                   1553: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1554: {
                   1555:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1556:   double **m;
                   1557: 
                   1558:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1559:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1560:   m += NR_END;
                   1561:   m -= nrl;
                   1562: 
                   1563:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1564:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1565:   m[nrl] += NR_END;
                   1566:   m[nrl] -= ncl;
                   1567: 
                   1568:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1569:   return m;
1.145     brouard  1570:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1571: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1572: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1573:    */
                   1574: }
                   1575: 
                   1576: /*************************free matrix ************************/
                   1577: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1578: {
                   1579:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1580:   free((FREE_ARG)(m+nrl-NR_END));
                   1581: }
                   1582: 
                   1583: /******************* ma3x *******************************/
                   1584: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1585: {
                   1586:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1587:   double ***m;
                   1588: 
                   1589:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1590:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1591:   m += NR_END;
                   1592:   m -= nrl;
                   1593: 
                   1594:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1595:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1596:   m[nrl] += NR_END;
                   1597:   m[nrl] -= ncl;
                   1598: 
                   1599:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1600: 
                   1601:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1602:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1603:   m[nrl][ncl] += NR_END;
                   1604:   m[nrl][ncl] -= nll;
                   1605:   for (j=ncl+1; j<=nch; j++) 
                   1606:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1607:   
                   1608:   for (i=nrl+1; i<=nrh; i++) {
                   1609:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1610:     for (j=ncl+1; j<=nch; j++) 
                   1611:       m[i][j]=m[i][j-1]+nlay;
                   1612:   }
                   1613:   return m; 
                   1614:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1615:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1616:   */
                   1617: }
                   1618: 
                   1619: /*************************free ma3x ************************/
                   1620: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1621: {
                   1622:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1623:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1624:   free((FREE_ARG)(m+nrl-NR_END));
                   1625: }
                   1626: 
                   1627: /*************** function subdirf ***********/
                   1628: char *subdirf(char fileres[])
                   1629: {
                   1630:   /* Caution optionfilefiname is hidden */
                   1631:   strcpy(tmpout,optionfilefiname);
                   1632:   strcat(tmpout,"/"); /* Add to the right */
                   1633:   strcat(tmpout,fileres);
                   1634:   return tmpout;
                   1635: }
                   1636: 
                   1637: /*************** function subdirf2 ***********/
                   1638: char *subdirf2(char fileres[], char *preop)
                   1639: {
                   1640:   
                   1641:   /* Caution optionfilefiname is hidden */
                   1642:   strcpy(tmpout,optionfilefiname);
                   1643:   strcat(tmpout,"/");
                   1644:   strcat(tmpout,preop);
                   1645:   strcat(tmpout,fileres);
                   1646:   return tmpout;
                   1647: }
                   1648: 
                   1649: /*************** function subdirf3 ***********/
                   1650: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1651: {
                   1652:   
                   1653:   /* Caution optionfilefiname is hidden */
                   1654:   strcpy(tmpout,optionfilefiname);
                   1655:   strcat(tmpout,"/");
                   1656:   strcat(tmpout,preop);
                   1657:   strcat(tmpout,preop2);
                   1658:   strcat(tmpout,fileres);
                   1659:   return tmpout;
                   1660: }
1.213     brouard  1661:  
                   1662: /*************** function subdirfext ***********/
                   1663: char *subdirfext(char fileres[], char *preop, char *postop)
                   1664: {
                   1665:   
                   1666:   strcpy(tmpout,preop);
                   1667:   strcat(tmpout,fileres);
                   1668:   strcat(tmpout,postop);
                   1669:   return tmpout;
                   1670: }
1.126     brouard  1671: 
1.213     brouard  1672: /*************** function subdirfext3 ***********/
                   1673: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1674: {
                   1675:   
                   1676:   /* Caution optionfilefiname is hidden */
                   1677:   strcpy(tmpout,optionfilefiname);
                   1678:   strcat(tmpout,"/");
                   1679:   strcat(tmpout,preop);
                   1680:   strcat(tmpout,fileres);
                   1681:   strcat(tmpout,postop);
                   1682:   return tmpout;
                   1683: }
                   1684:  
1.162     brouard  1685: char *asc_diff_time(long time_sec, char ascdiff[])
                   1686: {
                   1687:   long sec_left, days, hours, minutes;
                   1688:   days = (time_sec) / (60*60*24);
                   1689:   sec_left = (time_sec) % (60*60*24);
                   1690:   hours = (sec_left) / (60*60) ;
                   1691:   sec_left = (sec_left) %(60*60);
                   1692:   minutes = (sec_left) /60;
                   1693:   sec_left = (sec_left) % (60);
                   1694:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1695:   return ascdiff;
                   1696: }
                   1697: 
1.126     brouard  1698: /***************** f1dim *************************/
                   1699: extern int ncom; 
                   1700: extern double *pcom,*xicom;
                   1701: extern double (*nrfunc)(double []); 
                   1702:  
                   1703: double f1dim(double x) 
                   1704: { 
                   1705:   int j; 
                   1706:   double f;
                   1707:   double *xt; 
                   1708:  
                   1709:   xt=vector(1,ncom); 
                   1710:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1711:   f=(*nrfunc)(xt); 
                   1712:   free_vector(xt,1,ncom); 
                   1713:   return f; 
                   1714: } 
                   1715: 
                   1716: /*****************brent *************************/
                   1717: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1718: {
                   1719:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1720:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1721:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1722:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1723:    * returned function value. 
                   1724:   */
1.126     brouard  1725:   int iter; 
                   1726:   double a,b,d,etemp;
1.159     brouard  1727:   double fu=0,fv,fw,fx;
1.164     brouard  1728:   double ftemp=0.;
1.126     brouard  1729:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1730:   double e=0.0; 
                   1731:  
                   1732:   a=(ax < cx ? ax : cx); 
                   1733:   b=(ax > cx ? ax : cx); 
                   1734:   x=w=v=bx; 
                   1735:   fw=fv=fx=(*f)(x); 
                   1736:   for (iter=1;iter<=ITMAX;iter++) { 
                   1737:     xm=0.5*(a+b); 
                   1738:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1739:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1740:     printf(".");fflush(stdout);
                   1741:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1742: #ifdef DEBUGBRENT
1.126     brouard  1743:     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);
                   1744:     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);
                   1745:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1746: #endif
                   1747:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1748:       *xmin=x; 
                   1749:       return fx; 
                   1750:     } 
                   1751:     ftemp=fu;
                   1752:     if (fabs(e) > tol1) { 
                   1753:       r=(x-w)*(fx-fv); 
                   1754:       q=(x-v)*(fx-fw); 
                   1755:       p=(x-v)*q-(x-w)*r; 
                   1756:       q=2.0*(q-r); 
                   1757:       if (q > 0.0) p = -p; 
                   1758:       q=fabs(q); 
                   1759:       etemp=e; 
                   1760:       e=d; 
                   1761:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1762:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1763:       else { 
1.224     brouard  1764:                                d=p/q; 
                   1765:                                u=x+d; 
                   1766:                                if (u-a < tol2 || b-u < tol2) 
                   1767:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1768:       } 
                   1769:     } else { 
                   1770:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1771:     } 
                   1772:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1773:     fu=(*f)(u); 
                   1774:     if (fu <= fx) { 
                   1775:       if (u >= x) a=x; else b=x; 
                   1776:       SHFT(v,w,x,u) 
1.183     brouard  1777:       SHFT(fv,fw,fx,fu) 
                   1778:     } else { 
                   1779:       if (u < x) a=u; else b=u; 
                   1780:       if (fu <= fw || w == x) { 
1.224     brouard  1781:                                v=w; 
                   1782:                                w=u; 
                   1783:                                fv=fw; 
                   1784:                                fw=fu; 
1.183     brouard  1785:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1786:                                v=u; 
                   1787:                                fv=fu; 
1.183     brouard  1788:       } 
                   1789:     } 
1.126     brouard  1790:   } 
                   1791:   nrerror("Too many iterations in brent"); 
                   1792:   *xmin=x; 
                   1793:   return fx; 
                   1794: } 
                   1795: 
                   1796: /****************** mnbrak ***********************/
                   1797: 
                   1798: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1799:            double (*func)(double)) 
1.183     brouard  1800: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1801: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1802: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1803: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1804:    */
1.126     brouard  1805:   double ulim,u,r,q, dum;
                   1806:   double fu; 
1.187     brouard  1807: 
                   1808:   double scale=10.;
                   1809:   int iterscale=0;
                   1810: 
                   1811:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1812:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1813: 
                   1814: 
                   1815:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1816:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1817:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1818:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1819:   /* } */
                   1820: 
1.126     brouard  1821:   if (*fb > *fa) { 
                   1822:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1823:     SHFT(dum,*fb,*fa,dum) 
                   1824:   } 
1.126     brouard  1825:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1826:   *fc=(*func)(*cx); 
1.183     brouard  1827: #ifdef DEBUG
1.224     brouard  1828:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1829:   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  1830: #endif
1.224     brouard  1831:   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  1832:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1833:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1834:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1835:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1836:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1837:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1838:       fu=(*func)(u); 
1.163     brouard  1839: #ifdef DEBUG
                   1840:       /* f(x)=A(x-u)**2+f(u) */
                   1841:       double A, fparabu; 
                   1842:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1843:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1844:       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);
                   1845:       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  1846:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1847:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1848:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1849:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1850: #endif 
1.184     brouard  1851: #ifdef MNBRAKORIGINAL
1.183     brouard  1852: #else
1.191     brouard  1853: /*       if (fu > *fc) { */
                   1854: /* #ifdef DEBUG */
                   1855: /*       printf("mnbrak4  fu > fc \n"); */
                   1856: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1857: /* #endif */
                   1858: /*     /\* 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 *\\/  *\/ */
                   1859: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1860: /*     dum=u; /\* Shifting c and u *\/ */
                   1861: /*     u = *cx; */
                   1862: /*     *cx = dum; */
                   1863: /*     dum = fu; */
                   1864: /*     fu = *fc; */
                   1865: /*     *fc =dum; */
                   1866: /*       } else { /\* end *\/ */
                   1867: /* #ifdef DEBUG */
                   1868: /*       printf("mnbrak3  fu < fc \n"); */
                   1869: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1870: /* #endif */
                   1871: /*     dum=u; /\* Shifting c and u *\/ */
                   1872: /*     u = *cx; */
                   1873: /*     *cx = dum; */
                   1874: /*     dum = fu; */
                   1875: /*     fu = *fc; */
                   1876: /*     *fc =dum; */
                   1877: /*       } */
1.224     brouard  1878: #ifdef DEBUGMNBRAK
                   1879:                 double A, fparabu; 
                   1880:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1881:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1882:      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);
                   1883:      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  1884: #endif
1.191     brouard  1885:       dum=u; /* Shifting c and u */
                   1886:       u = *cx;
                   1887:       *cx = dum;
                   1888:       dum = fu;
                   1889:       fu = *fc;
                   1890:       *fc =dum;
1.183     brouard  1891: #endif
1.162     brouard  1892:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1893: #ifdef DEBUG
1.224     brouard  1894:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1895:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1896: #endif
1.126     brouard  1897:       fu=(*func)(u); 
                   1898:       if (fu < *fc) { 
1.183     brouard  1899: #ifdef DEBUG
1.224     brouard  1900:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1901:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1902: #endif
                   1903:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1904:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1905: #ifdef DEBUG
                   1906:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1907: #endif
                   1908:       } 
1.162     brouard  1909:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1910: #ifdef DEBUG
1.224     brouard  1911:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1912:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1913: #endif
1.126     brouard  1914:       u=ulim; 
                   1915:       fu=(*func)(u); 
1.183     brouard  1916:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1917: #ifdef DEBUG
1.224     brouard  1918:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1919:       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  1920: #endif
1.126     brouard  1921:       u=(*cx)+GOLD*(*cx-*bx); 
                   1922:       fu=(*func)(u); 
1.224     brouard  1923: #ifdef DEBUG
                   1924:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1925:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1926: #endif
1.183     brouard  1927:     } /* end tests */
1.126     brouard  1928:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1929:     SHFT(*fa,*fb,*fc,fu) 
                   1930: #ifdef DEBUG
1.224     brouard  1931:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1932:       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  1933: #endif
                   1934:   } /* 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  1935: } 
                   1936: 
                   1937: /*************** linmin ************************/
1.162     brouard  1938: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1939: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1940: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1941: the value of func at the returned location p . This is actually all accomplished by calling the
                   1942: routines mnbrak and brent .*/
1.126     brouard  1943: int ncom; 
                   1944: double *pcom,*xicom;
                   1945: double (*nrfunc)(double []); 
                   1946:  
1.224     brouard  1947: #ifdef LINMINORIGINAL
1.126     brouard  1948: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1949: #else
                   1950: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1951: #endif
1.126     brouard  1952: { 
                   1953:   double brent(double ax, double bx, double cx, 
                   1954:               double (*f)(double), double tol, double *xmin); 
                   1955:   double f1dim(double x); 
                   1956:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1957:              double *fc, double (*func)(double)); 
                   1958:   int j; 
                   1959:   double xx,xmin,bx,ax; 
                   1960:   double fx,fb,fa;
1.187     brouard  1961: 
1.203     brouard  1962: #ifdef LINMINORIGINAL
                   1963: #else
                   1964:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1965: #endif
                   1966:   
1.126     brouard  1967:   ncom=n; 
                   1968:   pcom=vector(1,n); 
                   1969:   xicom=vector(1,n); 
                   1970:   nrfunc=func; 
                   1971:   for (j=1;j<=n;j++) { 
                   1972:     pcom[j]=p[j]; 
1.202     brouard  1973:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1974:   } 
1.187     brouard  1975: 
1.203     brouard  1976: #ifdef LINMINORIGINAL
                   1977:   xx=1.;
                   1978: #else
                   1979:   axs=0.0;
                   1980:   xxs=1.;
                   1981:   do{
                   1982:     xx= xxs;
                   1983: #endif
1.187     brouard  1984:     ax=0.;
                   1985:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1986:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1987:     /* 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))   */
                   1988:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1989:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1990:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1991:     /* 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  1992: #ifdef LINMINORIGINAL
                   1993: #else
                   1994:     if (fx != fx){
1.224     brouard  1995:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1996:                        printf("|");
                   1997:                        fprintf(ficlog,"|");
1.203     brouard  1998: #ifdef DEBUGLINMIN
1.224     brouard  1999:                        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  2000: #endif
                   2001:     }
1.224     brouard  2002:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2003: #endif
                   2004:   
1.191     brouard  2005: #ifdef DEBUGLINMIN
                   2006:   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  2007:   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  2008: #endif
1.224     brouard  2009: #ifdef LINMINORIGINAL
                   2010: #else
                   2011:        if(fb == fx){ /* Flat function in the direction */
                   2012:                xmin=xx;
                   2013:     *flat=1;
                   2014:        }else{
                   2015:     *flat=0;
                   2016: #endif
                   2017:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2018:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2019:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2020:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2021:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2022:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2023: #ifdef DEBUG
1.224     brouard  2024:   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);
                   2025:   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);
                   2026: #endif
                   2027: #ifdef LINMINORIGINAL
                   2028: #else
                   2029:                        }
1.126     brouard  2030: #endif
1.191     brouard  2031: #ifdef DEBUGLINMIN
                   2032:   printf("linmin end ");
1.202     brouard  2033:   fprintf(ficlog,"linmin end ");
1.191     brouard  2034: #endif
1.126     brouard  2035:   for (j=1;j<=n;j++) { 
1.203     brouard  2036: #ifdef LINMINORIGINAL
                   2037:     xi[j] *= xmin; 
                   2038: #else
                   2039: #ifdef DEBUGLINMIN
                   2040:     if(xxs <1.0)
                   2041:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2042: #endif
                   2043:     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) */
                   2044: #ifdef DEBUGLINMIN
                   2045:     if(xxs <1.0)
                   2046:       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 );
                   2047: #endif
                   2048: #endif
1.187     brouard  2049:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2050:   } 
1.191     brouard  2051: #ifdef DEBUGLINMIN
1.203     brouard  2052:   printf("\n");
1.191     brouard  2053:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2054:   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  2055:   for (j=1;j<=n;j++) { 
1.202     brouard  2056:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2057:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2058:     if(j % ncovmodel == 0){
1.191     brouard  2059:       printf("\n");
1.202     brouard  2060:       fprintf(ficlog,"\n");
                   2061:     }
1.191     brouard  2062:   }
1.203     brouard  2063: #else
1.191     brouard  2064: #endif
1.126     brouard  2065:   free_vector(xicom,1,n); 
                   2066:   free_vector(pcom,1,n); 
                   2067: } 
                   2068: 
                   2069: 
                   2070: /*************** powell ************************/
1.162     brouard  2071: /*
                   2072: Minimization of a function func of n variables. Input consists of an initial starting point
                   2073: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2074: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2075: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2076: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2077: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2078:  */
1.224     brouard  2079: #ifdef LINMINORIGINAL
                   2080: #else
                   2081:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2082:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2083: #endif
1.126     brouard  2084: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2085:            double (*func)(double [])) 
                   2086: { 
1.224     brouard  2087: #ifdef LINMINORIGINAL
                   2088:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2089:              double (*func)(double [])); 
1.224     brouard  2090: #else 
1.241     brouard  2091:  void linmin(double p[], double xi[], int n, double *fret,
                   2092:             double (*func)(double []),int *flat); 
1.224     brouard  2093: #endif
1.239     brouard  2094:  int i,ibig,j,jk,k; 
1.126     brouard  2095:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2096:   double directest;
1.126     brouard  2097:   double fp,fptt;
                   2098:   double *xits;
                   2099:   int niterf, itmp;
1.224     brouard  2100: #ifdef LINMINORIGINAL
                   2101: #else
                   2102: 
                   2103:   flatdir=ivector(1,n); 
                   2104:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2105: #endif
1.126     brouard  2106: 
                   2107:   pt=vector(1,n); 
                   2108:   ptt=vector(1,n); 
                   2109:   xit=vector(1,n); 
                   2110:   xits=vector(1,n); 
                   2111:   *fret=(*func)(p); 
                   2112:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2113:   rcurr_time = time(NULL);  
1.126     brouard  2114:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2115:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2116:     ibig=0; 
                   2117:     del=0.0; 
1.157     brouard  2118:     rlast_time=rcurr_time;
                   2119:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2120:     rcurr_time = time(NULL);  
                   2121:     curr_time = *localtime(&rcurr_time);
                   2122:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2123:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2124: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2125:     for (i=1;i<=n;i++) {
1.126     brouard  2126:       fprintf(ficrespow," %.12lf", p[i]);
                   2127:     }
1.239     brouard  2128:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2129:     printf("\n#model=  1      +     age ");
                   2130:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2131:     if(nagesqr==1){
1.241     brouard  2132:        printf("  + age*age  ");
                   2133:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2134:     }
                   2135:     for(j=1;j <=ncovmodel-2;j++){
                   2136:       if(Typevar[j]==0) {
                   2137:        printf("  +      V%d  ",Tvar[j]);
                   2138:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2139:       }else if(Typevar[j]==1) {
                   2140:        printf("  +    V%d*age ",Tvar[j]);
                   2141:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2142:       }else if(Typevar[j]==2) {
                   2143:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2144:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2145:       }
                   2146:     }
1.126     brouard  2147:     printf("\n");
1.239     brouard  2148: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2149: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2150:     fprintf(ficlog,"\n");
1.239     brouard  2151:     for(i=1,jk=1; i <=nlstate; i++){
                   2152:       for(k=1; k <=(nlstate+ndeath); k++){
                   2153:        if (k != i) {
                   2154:          printf("%d%d ",i,k);
                   2155:          fprintf(ficlog,"%d%d ",i,k);
                   2156:          for(j=1; j <=ncovmodel; j++){
                   2157:            printf("%12.7f ",p[jk]);
                   2158:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2159:            jk++; 
                   2160:          }
                   2161:          printf("\n");
                   2162:          fprintf(ficlog,"\n");
                   2163:        }
                   2164:       }
                   2165:     }
1.241     brouard  2166:     if(*iter <=3 && *iter >1){
1.157     brouard  2167:       tml = *localtime(&rcurr_time);
                   2168:       strcpy(strcurr,asctime(&tml));
                   2169:       rforecast_time=rcurr_time; 
1.126     brouard  2170:       itmp = strlen(strcurr);
                   2171:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2172:        strcurr[itmp-1]='\0';
1.162     brouard  2173:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2174:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2175:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2176:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2177:        forecast_time = *localtime(&rforecast_time);
                   2178:        strcpy(strfor,asctime(&forecast_time));
                   2179:        itmp = strlen(strfor);
                   2180:        if(strfor[itmp-1]=='\n')
                   2181:          strfor[itmp-1]='\0';
                   2182:        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);
                   2183:        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  2184:       }
                   2185:     }
1.187     brouard  2186:     for (i=1;i<=n;i++) { /* For each direction i */
                   2187:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2188:       fptt=(*fret); 
                   2189: #ifdef DEBUG
1.203     brouard  2190:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2191:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2192: #endif
1.203     brouard  2193:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2194:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2195: #ifdef LINMINORIGINAL
1.188     brouard  2196:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2197: #else
                   2198:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2199:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2200: #endif
                   2201:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2202:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2203:                                /* because that direction will be replaced unless the gain del is small */
                   2204:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2205:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2206:                                /* with the new direction. */
                   2207:                                del=fabs(fptt-(*fret)); 
                   2208:                                ibig=i; 
1.126     brouard  2209:       } 
                   2210: #ifdef DEBUG
                   2211:       printf("%d %.12e",i,(*fret));
                   2212:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2213:       for (j=1;j<=n;j++) {
1.224     brouard  2214:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2215:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2216:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2217:       }
                   2218:       for(j=1;j<=n;j++) {
1.225     brouard  2219:                                printf(" p(%d)=%.12e",j,p[j]);
                   2220:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2221:       }
                   2222:       printf("\n");
                   2223:       fprintf(ficlog,"\n");
                   2224: #endif
1.187     brouard  2225:     } /* end loop on each direction i */
                   2226:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2227:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2228:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2229:       for(j=1;j<=n;j++) {
1.225     brouard  2230:                                if(flatdir[j] >0){
                   2231:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2232:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2233:                                }
                   2234:                                /* printf("\n"); */
                   2235:                                /* fprintf(ficlog,"\n"); */
                   2236:                        }
1.243     brouard  2237:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2238:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2239:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2240:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2241:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2242:       /* decreased of more than 3.84  */
                   2243:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2244:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2245:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2246:                        
1.188     brouard  2247:       /* Starting the program with initial values given by a former maximization will simply change */
                   2248:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2249:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2250:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2251: #ifdef DEBUG
                   2252:       int k[2],l;
                   2253:       k[0]=1;
                   2254:       k[1]=-1;
                   2255:       printf("Max: %.12e",(*func)(p));
                   2256:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2257:       for (j=1;j<=n;j++) {
                   2258:        printf(" %.12e",p[j]);
                   2259:        fprintf(ficlog," %.12e",p[j]);
                   2260:       }
                   2261:       printf("\n");
                   2262:       fprintf(ficlog,"\n");
                   2263:       for(l=0;l<=1;l++) {
                   2264:        for (j=1;j<=n;j++) {
                   2265:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2266:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2267:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2268:        }
                   2269:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2270:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2271:       }
                   2272: #endif
                   2273: 
1.224     brouard  2274: #ifdef LINMINORIGINAL
                   2275: #else
                   2276:       free_ivector(flatdir,1,n); 
                   2277: #endif
1.126     brouard  2278:       free_vector(xit,1,n); 
                   2279:       free_vector(xits,1,n); 
                   2280:       free_vector(ptt,1,n); 
                   2281:       free_vector(pt,1,n); 
                   2282:       return; 
1.192     brouard  2283:     } /* enough precision */ 
1.240     brouard  2284:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2285:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2286:       ptt[j]=2.0*p[j]-pt[j]; 
                   2287:       xit[j]=p[j]-pt[j]; 
                   2288:       pt[j]=p[j]; 
                   2289:     } 
1.181     brouard  2290:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2291: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2292:                if (*iter <=4) {
1.225     brouard  2293: #else
                   2294: #endif
1.224     brouard  2295: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2296: #else
1.161     brouard  2297:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2298: #endif
1.162     brouard  2299:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2300:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2301:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2302:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2303:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2304:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2305:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2306:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2307:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2308:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2309:       /* mu² and del² are equal when f3=f1 */
                   2310:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2311:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2312:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2313:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2314: #ifdef NRCORIGINAL
                   2315:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2316: #else
                   2317:       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  2318:       t= t- del*SQR(fp-fptt);
1.183     brouard  2319: #endif
1.202     brouard  2320:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2321: #ifdef DEBUG
1.181     brouard  2322:       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);
                   2323:       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  2324:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2325:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2326:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2327:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2328:       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);
                   2329:       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);
                   2330: #endif
1.183     brouard  2331: #ifdef POWELLORIGINAL
                   2332:       if (t < 0.0) { /* Then we use it for new direction */
                   2333: #else
1.182     brouard  2334:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2335:                                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  2336:         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  2337:         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  2338:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2339:       } 
1.181     brouard  2340:       if (directest < 0.0) { /* Then we use it for new direction */
                   2341: #endif
1.191     brouard  2342: #ifdef DEBUGLINMIN
1.234     brouard  2343:        printf("Before linmin in direction P%d-P0\n",n);
                   2344:        for (j=1;j<=n;j++) {
                   2345:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2346:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2347:          if(j % ncovmodel == 0){
                   2348:            printf("\n");
                   2349:            fprintf(ficlog,"\n");
                   2350:          }
                   2351:        }
1.224     brouard  2352: #endif
                   2353: #ifdef LINMINORIGINAL
1.234     brouard  2354:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2355: #else
1.234     brouard  2356:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2357:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2358: #endif
1.234     brouard  2359:        
1.191     brouard  2360: #ifdef DEBUGLINMIN
1.234     brouard  2361:        for (j=1;j<=n;j++) { 
                   2362:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2363:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2364:          if(j % ncovmodel == 0){
                   2365:            printf("\n");
                   2366:            fprintf(ficlog,"\n");
                   2367:          }
                   2368:        }
1.224     brouard  2369: #endif
1.234     brouard  2370:        for (j=1;j<=n;j++) { 
                   2371:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2372:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2373:        }
1.224     brouard  2374: #ifdef LINMINORIGINAL
                   2375: #else
1.234     brouard  2376:        for (j=1, flatd=0;j<=n;j++) {
                   2377:          if(flatdir[j]>0)
                   2378:            flatd++;
                   2379:        }
                   2380:        if(flatd >0){
                   2381:          printf("%d flat directions\n",flatd);
                   2382:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2383:          for (j=1;j<=n;j++) { 
                   2384:            if(flatdir[j]>0){
                   2385:              printf("%d ",j);
                   2386:              fprintf(ficlog,"%d ",j);
                   2387:            }
                   2388:          }
                   2389:          printf("\n");
                   2390:          fprintf(ficlog,"\n");
                   2391:        }
1.191     brouard  2392: #endif
1.234     brouard  2393:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2394:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2395:        
1.126     brouard  2396: #ifdef DEBUG
1.234     brouard  2397:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2398:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2399:        for(j=1;j<=n;j++){
                   2400:          printf(" %lf",xit[j]);
                   2401:          fprintf(ficlog," %lf",xit[j]);
                   2402:        }
                   2403:        printf("\n");
                   2404:        fprintf(ficlog,"\n");
1.126     brouard  2405: #endif
1.192     brouard  2406:       } /* end of t or directest negative */
1.224     brouard  2407: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2408: #else
1.234     brouard  2409:       } /* end if (fptt < fp)  */
1.192     brouard  2410: #endif
1.225     brouard  2411: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2412:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2413: #else
1.224     brouard  2414: #endif
1.234     brouard  2415:                } /* loop iteration */ 
1.126     brouard  2416: } 
1.234     brouard  2417:   
1.126     brouard  2418: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2419:   
1.235     brouard  2420:   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  2421:   {
1.235     brouard  2422:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2423:        (and selected quantitative values in nres)
                   2424:        by left multiplying the unit
1.234     brouard  2425:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2426:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2427:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2428:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2429:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2430:   /* Initial matrix pimij */
                   2431:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2432:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2433:   /*  0,                   0                  , 1} */
                   2434:   /*
                   2435:    * and after some iteration: */
                   2436:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2437:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2438:   /*  0,                   0                  , 1} */
                   2439:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2440:   /* {0.51571254859325999, 0.4842874514067399, */
                   2441:   /*  0.51326036147820708, 0.48673963852179264} */
                   2442:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2443:     
1.126     brouard  2444:   int i, ii,j,k;
1.209     brouard  2445:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2446:   /* double **matprod2(); */ /* test */
1.218     brouard  2447:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2448:   double **newm;
1.209     brouard  2449:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2450:   int ncvloop=0;
1.169     brouard  2451:   
1.209     brouard  2452:   min=vector(1,nlstate);
                   2453:   max=vector(1,nlstate);
                   2454:   meandiff=vector(1,nlstate);
                   2455: 
1.218     brouard  2456:        /* Starting with matrix unity */
1.126     brouard  2457:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2458:     for (j=1;j<=nlstate+ndeath;j++){
                   2459:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2460:     }
1.169     brouard  2461:   
                   2462:   cov[1]=1.;
                   2463:   
                   2464:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2465:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2466:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2467:     ncvloop++;
1.126     brouard  2468:     newm=savm;
                   2469:     /* Covariates have to be included here again */
1.138     brouard  2470:     cov[2]=agefin;
1.187     brouard  2471:     if(nagesqr==1)
                   2472:       cov[3]= agefin*agefin;;
1.234     brouard  2473:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2474:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2475:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2476:       /* 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  2477:     }
                   2478:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2479:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2480:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2481:       /* 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  2482:     }
1.237     brouard  2483:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2484:       if(Dummy[Tvar[Tage[k]]]){
                   2485:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2486:       } else{
1.235     brouard  2487:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2488:       }
1.235     brouard  2489:       /* 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  2490:     }
1.237     brouard  2491:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2492:       /* 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  2493:       if(Dummy[Tvard[k][1]==0]){
                   2494:        if(Dummy[Tvard[k][2]==0]){
                   2495:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2496:        }else{
                   2497:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2498:        }
                   2499:       }else{
                   2500:        if(Dummy[Tvard[k][2]==0]){
                   2501:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2502:        }else{
                   2503:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2504:        }
                   2505:       }
1.234     brouard  2506:     }
1.138     brouard  2507:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2508:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2509:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2510:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2511:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2512:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2513:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2514:     
1.126     brouard  2515:     savm=oldm;
                   2516:     oldm=newm;
1.209     brouard  2517: 
                   2518:     for(j=1; j<=nlstate; j++){
                   2519:       max[j]=0.;
                   2520:       min[j]=1.;
                   2521:     }
                   2522:     for(i=1;i<=nlstate;i++){
                   2523:       sumnew=0;
                   2524:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2525:       for(j=1; j<=nlstate; j++){ 
                   2526:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2527:        max[j]=FMAX(max[j],prlim[i][j]);
                   2528:        min[j]=FMIN(min[j],prlim[i][j]);
                   2529:       }
                   2530:     }
                   2531: 
1.126     brouard  2532:     maxmax=0.;
1.209     brouard  2533:     for(j=1; j<=nlstate; j++){
                   2534:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2535:       maxmax=FMAX(maxmax,meandiff[j]);
                   2536:       /* 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  2537:     } /* j loop */
1.203     brouard  2538:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2539:     /* 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  2540:     if(maxmax < ftolpl){
1.209     brouard  2541:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2542:       free_vector(min,1,nlstate);
                   2543:       free_vector(max,1,nlstate);
                   2544:       free_vector(meandiff,1,nlstate);
1.126     brouard  2545:       return prlim;
                   2546:     }
1.169     brouard  2547:   } /* age loop */
1.208     brouard  2548:     /* After some age loop it doesn't converge */
1.209     brouard  2549:   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  2550: 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  2551:   /* 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); */
                   2552:   free_vector(min,1,nlstate);
                   2553:   free_vector(max,1,nlstate);
                   2554:   free_vector(meandiff,1,nlstate);
1.208     brouard  2555:   
1.169     brouard  2556:   return prlim; /* should not reach here */
1.126     brouard  2557: }
                   2558: 
1.217     brouard  2559: 
                   2560:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2561: 
1.218     brouard  2562:  /* 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) */
                   2563:  /* 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  2564:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2565: {
1.218     brouard  2566:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2567:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2568:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2569:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2570:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2571:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2572:   /* Initial matrix pimij */
                   2573:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2574:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2575:   /*  0,                   0                  , 1} */
                   2576:   /*
                   2577:    * and after some iteration: */
                   2578:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2579:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2580:   /*  0,                   0                  , 1} */
                   2581:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2582:   /* {0.51571254859325999, 0.4842874514067399, */
                   2583:   /*  0.51326036147820708, 0.48673963852179264} */
                   2584:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2585: 
                   2586:   int i, ii,j,k;
1.247   ! brouard  2587:   int first=0;
1.217     brouard  2588:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2589:   /* double **matprod2(); */ /* test */
                   2590:   double **out, cov[NCOVMAX+1], **bmij();
                   2591:   double **newm;
1.218     brouard  2592:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2593:   double        **oldm, **savm;  /* for use */
                   2594: 
1.217     brouard  2595:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2596:   int ncvloop=0;
                   2597:   
                   2598:   min=vector(1,nlstate);
                   2599:   max=vector(1,nlstate);
                   2600:   meandiff=vector(1,nlstate);
                   2601: 
1.218     brouard  2602:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2603:        oldm=oldms; savm=savms;
                   2604: 
                   2605:        /* Starting with matrix unity */
                   2606:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2607:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2608:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2609:     }
                   2610:   
                   2611:   cov[1]=1.;
                   2612:   
                   2613:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2614:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2615:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2616:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2617:     ncvloop++;
1.218     brouard  2618:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2619:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2620:     /* Covariates have to be included here again */
                   2621:     cov[2]=agefin;
                   2622:     if(nagesqr==1)
                   2623:       cov[3]= agefin*agefin;;
1.242     brouard  2624:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2625:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2626:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2627:       /* 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)); */
                   2628:     }
                   2629:     /* for (k=1; k<=cptcovn;k++) { */
                   2630:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2631:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2632:     /*   /\* 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])]); *\/ */
                   2633:     /* } */
                   2634:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2635:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2636:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2637:       /* 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]); */
                   2638:     }
                   2639:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2640:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2641:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2642:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2643:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2644:       if(Dummy[Tvar[Tage[k]]]){
                   2645:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2646:       } else{
                   2647:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2648:       }
                   2649:       /* 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]); */
                   2650:     }
                   2651:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2652:       /* 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]); */
                   2653:       if(Dummy[Tvard[k][1]==0]){
                   2654:        if(Dummy[Tvard[k][2]==0]){
                   2655:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2656:        }else{
                   2657:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2658:        }
                   2659:       }else{
                   2660:        if(Dummy[Tvard[k][2]==0]){
                   2661:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2662:        }else{
                   2663:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2664:        }
                   2665:       }
1.217     brouard  2666:     }
                   2667:     
                   2668:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2669:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2670:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2671:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2672:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2673:                /* ij should be linked to the correct index of cov */
                   2674:                /* age and covariate values ij are in 'cov', but we need to pass
                   2675:                 * ij for the observed prevalence at age and status and covariate
                   2676:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2677:                 */
                   2678:     /* 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 *\/ */
                   2679:     /* 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 *\/ */
                   2680:     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  2681:     savm=oldm;
                   2682:     oldm=newm;
                   2683:     for(j=1; j<=nlstate; j++){
                   2684:       max[j]=0.;
                   2685:       min[j]=1.;
                   2686:     }
                   2687:     for(j=1; j<=nlstate; j++){ 
                   2688:       for(i=1;i<=nlstate;i++){
1.234     brouard  2689:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2690:        bprlim[i][j]= newm[i][j];
                   2691:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2692:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2693:       }
                   2694:     }
1.218     brouard  2695:                
1.217     brouard  2696:     maxmax=0.;
                   2697:     for(i=1; i<=nlstate; i++){
                   2698:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2699:       maxmax=FMAX(maxmax,meandiff[i]);
                   2700:       /* 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); */
                   2701:     } /* j loop */
                   2702:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2703:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2704:     if(maxmax < ftolpl){
1.220     brouard  2705:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2706:       free_vector(min,1,nlstate);
                   2707:       free_vector(max,1,nlstate);
                   2708:       free_vector(meandiff,1,nlstate);
                   2709:       return bprlim;
                   2710:     }
                   2711:   } /* age loop */
                   2712:     /* After some age loop it doesn't converge */
1.247   ! brouard  2713:   if(first){
        !          2714:     first=1;
        !          2715:     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\
        !          2716: 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);
        !          2717:   }
        !          2718:   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  2719: 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);
                   2720:   /* 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); */
                   2721:   free_vector(min,1,nlstate);
                   2722:   free_vector(max,1,nlstate);
                   2723:   free_vector(meandiff,1,nlstate);
                   2724:   
                   2725:   return bprlim; /* should not reach here */
                   2726: }
                   2727: 
1.126     brouard  2728: /*************** transition probabilities ***************/ 
                   2729: 
                   2730: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2731: {
1.138     brouard  2732:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2733:      computes the probability to be observed in state j being in state i by appying the
                   2734:      model to the ncovmodel covariates (including constant and age).
                   2735:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2736:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2737:      ncth covariate in the global vector x is given by the formula:
                   2738:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2739:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2740:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2741:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2742:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2743:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2744:   */
                   2745:   double s1, lnpijopii;
1.126     brouard  2746:   /*double t34;*/
1.164     brouard  2747:   int i,j, nc, ii, jj;
1.126     brouard  2748: 
1.223     brouard  2749:   for(i=1; i<= nlstate; i++){
                   2750:     for(j=1; j<i;j++){
                   2751:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2752:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2753:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2754:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2755:       }
                   2756:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2757:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2758:     }
                   2759:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2760:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2761:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2762:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2763:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2764:       }
                   2765:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2766:     }
                   2767:   }
1.218     brouard  2768:   
1.223     brouard  2769:   for(i=1; i<= nlstate; i++){
                   2770:     s1=0;
                   2771:     for(j=1; j<i; j++){
                   2772:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2773:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2774:     }
                   2775:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2776:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2777:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2778:     }
                   2779:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2780:     ps[i][i]=1./(s1+1.);
                   2781:     /* Computing other pijs */
                   2782:     for(j=1; j<i; j++)
                   2783:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2784:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2785:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2786:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2787:   } /* end i */
1.218     brouard  2788:   
1.223     brouard  2789:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2790:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2791:       ps[ii][jj]=0;
                   2792:       ps[ii][ii]=1;
                   2793:     }
                   2794:   }
1.218     brouard  2795:   
                   2796:   
1.223     brouard  2797:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2798:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2799:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2800:   /*   } */
                   2801:   /*   printf("\n "); */
                   2802:   /* } */
                   2803:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2804:   /*
                   2805:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2806:                goto end;*/
1.223     brouard  2807:   return ps;
1.126     brouard  2808: }
                   2809: 
1.218     brouard  2810: /*************** backward transition probabilities ***************/ 
                   2811: 
                   2812:  /* 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 ) */
                   2813: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2814:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2815: {
1.222     brouard  2816:   /* Computes the backward probability at age agefin and covariate ij
                   2817:    * and returns in **ps as well as **bmij.
                   2818:    */
1.218     brouard  2819:   int i, ii, j,k;
1.222     brouard  2820:   
                   2821:   double **out, **pmij();
                   2822:   double sumnew=0.;
1.218     brouard  2823:   double agefin;
1.222     brouard  2824:   
                   2825:   double **dnewm, **dsavm, **doldm;
                   2826:   double **bbmij;
                   2827:   
1.218     brouard  2828:   doldm=ddoldms; /* global pointers */
1.222     brouard  2829:   dnewm=ddnewms;
                   2830:   dsavm=ddsavms;
                   2831:   
                   2832:   agefin=cov[2];
                   2833:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2834:      the observed prevalence (with this covariate ij) */
                   2835:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2836:   /* We do have the matrix Px in savm  and we need pij */
                   2837:   for (j=1;j<=nlstate+ndeath;j++){
                   2838:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2839:     for (ii=1;ii<=nlstate;ii++){
                   2840:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2841:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2842:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2843:       if(sumnew >= 1.e-10){
                   2844:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2845:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2846:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2847:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2848:        /* }else */
                   2849:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2850:       }else{
1.242     brouard  2851:        ;
                   2852:        /* 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  2853:       }
                   2854:     } /*End ii */
                   2855:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2856:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2857:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2858:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2859:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2860:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2861:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2862:   for (j=1;j<=nlstate+ndeath;j++){
                   2863:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2864:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2865:     }
                   2866:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2867:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2868:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2869:   /* end bmij */
                   2870:   return ps; 
1.218     brouard  2871: }
1.217     brouard  2872: /*************** transition probabilities ***************/ 
                   2873: 
1.218     brouard  2874: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2875: {
                   2876:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2877:      computes the probability to be observed in state j being in state i by appying the
                   2878:      model to the ncovmodel covariates (including constant and age).
                   2879:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2880:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2881:      ncth covariate in the global vector x is given by the formula:
                   2882:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2883:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2884:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2885:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2886:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2887:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2888:   */
                   2889:   double s1, lnpijopii;
                   2890:   /*double t34;*/
                   2891:   int i,j, nc, ii, jj;
                   2892: 
1.234     brouard  2893:   for(i=1; i<= nlstate; i++){
                   2894:     for(j=1; j<i;j++){
                   2895:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2896:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2897:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2898:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2899:       }
                   2900:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2901:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2902:     }
                   2903:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2904:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2905:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2906:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2907:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2908:       }
                   2909:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2910:     }
                   2911:   }
                   2912:   
                   2913:   for(i=1; i<= nlstate; i++){
                   2914:     s1=0;
                   2915:     for(j=1; j<i; j++){
                   2916:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2917:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2918:     }
                   2919:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2920:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2921:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2922:     }
                   2923:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2924:     ps[i][i]=1./(s1+1.);
                   2925:     /* Computing other pijs */
                   2926:     for(j=1; j<i; j++)
                   2927:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2928:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2929:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2930:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2931:   } /* end i */
                   2932:   
                   2933:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2934:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2935:       ps[ii][jj]=0;
                   2936:       ps[ii][ii]=1;
                   2937:     }
                   2938:   }
                   2939:   /* Added for backcast */ /* Transposed matrix too */
                   2940:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2941:     s1=0.;
                   2942:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2943:       s1+=ps[ii][jj];
                   2944:     }
                   2945:     for(ii=1; ii<= nlstate; ii++){
                   2946:       ps[ii][jj]=ps[ii][jj]/s1;
                   2947:     }
                   2948:   }
                   2949:   /* Transposition */
                   2950:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2951:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2952:       s1=ps[ii][jj];
                   2953:       ps[ii][jj]=ps[jj][ii];
                   2954:       ps[jj][ii]=s1;
                   2955:     }
                   2956:   }
                   2957:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2958:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2959:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2960:   /*   } */
                   2961:   /*   printf("\n "); */
                   2962:   /* } */
                   2963:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2964:   /*
                   2965:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2966:     goto end;*/
                   2967:   return ps;
1.217     brouard  2968: }
                   2969: 
                   2970: 
1.126     brouard  2971: /**************** Product of 2 matrices ******************/
                   2972: 
1.145     brouard  2973: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2974: {
                   2975:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2976:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2977:   /* in, b, out are matrice of pointers which should have been initialized 
                   2978:      before: only the contents of out is modified. The function returns
                   2979:      a pointer to pointers identical to out */
1.145     brouard  2980:   int i, j, k;
1.126     brouard  2981:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2982:     for(k=ncolol; k<=ncoloh; k++){
                   2983:       out[i][k]=0.;
                   2984:       for(j=ncl; j<=nch; j++)
                   2985:        out[i][k] +=in[i][j]*b[j][k];
                   2986:     }
1.126     brouard  2987:   return out;
                   2988: }
                   2989: 
                   2990: 
                   2991: /************* Higher Matrix Product ***************/
                   2992: 
1.235     brouard  2993: 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  2994: {
1.218     brouard  2995:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2996:      'nhstepm*hstepm*stepm' months (i.e. until
                   2997:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2998:      nhstepm*hstepm matrices. 
                   2999:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3000:      (typically every 2 years instead of every month which is too big 
                   3001:      for the memory).
                   3002:      Model is determined by parameters x and covariates have to be 
                   3003:      included manually here. 
                   3004: 
                   3005:      */
                   3006: 
                   3007:   int i, j, d, h, k;
1.131     brouard  3008:   double **out, cov[NCOVMAX+1];
1.126     brouard  3009:   double **newm;
1.187     brouard  3010:   double agexact;
1.214     brouard  3011:   double agebegin, ageend;
1.126     brouard  3012: 
                   3013:   /* Hstepm could be zero and should return the unit matrix */
                   3014:   for (i=1;i<=nlstate+ndeath;i++)
                   3015:     for (j=1;j<=nlstate+ndeath;j++){
                   3016:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3017:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3018:     }
                   3019:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3020:   for(h=1; h <=nhstepm; h++){
                   3021:     for(d=1; d <=hstepm; d++){
                   3022:       newm=savm;
                   3023:       /* Covariates have to be included here again */
                   3024:       cov[1]=1.;
1.214     brouard  3025:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3026:       cov[2]=agexact;
                   3027:       if(nagesqr==1)
1.227     brouard  3028:        cov[3]= agexact*agexact;
1.235     brouard  3029:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3030:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3031:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3032:        /* 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)); */
                   3033:       }
                   3034:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3035:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3036:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3037:        /* 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]); */
                   3038:       }
                   3039:       for (k=1; k<=cptcovage;k++){
                   3040:        if(Dummy[Tvar[Tage[k]]]){
                   3041:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3042:        } else{
                   3043:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3044:        }
                   3045:        /* 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]); */
                   3046:       }
                   3047:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3048:        /* 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]); */
                   3049:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3050:       }
                   3051:       /* for (k=1; k<=cptcovn;k++)  */
                   3052:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3053:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3054:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3055:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3056:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3057:       
                   3058:       
1.126     brouard  3059:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3060:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3061:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3062:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3063:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3064:       /* if((int)age == 70){ */
                   3065:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3066:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3067:       /*         printf("%d pmmij ",i); */
                   3068:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3069:       /*           printf("%f ",pmmij[i][j]); */
                   3070:       /*         } */
                   3071:       /*         printf(" oldm "); */
                   3072:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3073:       /*           printf("%f ",oldm[i][j]); */
                   3074:       /*         } */
                   3075:       /*         printf("\n"); */
                   3076:       /*       } */
                   3077:       /* } */
1.126     brouard  3078:       savm=oldm;
                   3079:       oldm=newm;
                   3080:     }
                   3081:     for(i=1; i<=nlstate+ndeath; i++)
                   3082:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3083:                                po[i][j][h]=newm[i][j];
                   3084:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3085:       }
1.128     brouard  3086:     /*printf("h=%d ",h);*/
1.126     brouard  3087:   } /* end h */
1.218     brouard  3088:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3089:   return po;
                   3090: }
                   3091: 
1.217     brouard  3092: /************* Higher Back Matrix Product ***************/
1.218     brouard  3093: /* 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  3094: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3095: {
1.218     brouard  3096:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3097:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3098:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3099:      nhstepm*hstepm matrices.
                   3100:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3101:      (typically every 2 years instead of every month which is too big
1.217     brouard  3102:      for the memory).
1.218     brouard  3103:      Model is determined by parameters x and covariates have to be
                   3104:      included manually here.
1.217     brouard  3105: 
1.222     brouard  3106:   */
1.217     brouard  3107: 
                   3108:   int i, j, d, h, k;
                   3109:   double **out, cov[NCOVMAX+1];
                   3110:   double **newm;
                   3111:   double agexact;
                   3112:   double agebegin, ageend;
1.222     brouard  3113:   double **oldm, **savm;
1.217     brouard  3114: 
1.222     brouard  3115:   oldm=oldms;savm=savms;
1.217     brouard  3116:   /* Hstepm could be zero and should return the unit matrix */
                   3117:   for (i=1;i<=nlstate+ndeath;i++)
                   3118:     for (j=1;j<=nlstate+ndeath;j++){
                   3119:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3120:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3121:     }
                   3122:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3123:   for(h=1; h <=nhstepm; h++){
                   3124:     for(d=1; d <=hstepm; d++){
                   3125:       newm=savm;
                   3126:       /* Covariates have to be included here again */
                   3127:       cov[1]=1.;
                   3128:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3129:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3130:       cov[2]=agexact;
                   3131:       if(nagesqr==1)
1.222     brouard  3132:        cov[3]= agexact*agexact;
1.218     brouard  3133:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3134:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3135:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3136:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3137:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3138:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3139:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3140:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3141:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3142:       /* 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  3143:                        
                   3144:                        
1.217     brouard  3145:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3146:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3147:       /* Careful transposed matrix */
1.222     brouard  3148:       /* age is in cov[2] */
1.218     brouard  3149:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3150:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3151:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3152:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3153:       /* if((int)age == 70){ */
                   3154:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3155:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3156:       /*         printf("%d pmmij ",i); */
                   3157:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3158:       /*           printf("%f ",pmmij[i][j]); */
                   3159:       /*         } */
                   3160:       /*         printf(" oldm "); */
                   3161:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3162:       /*           printf("%f ",oldm[i][j]); */
                   3163:       /*         } */
                   3164:       /*         printf("\n"); */
                   3165:       /*       } */
                   3166:       /* } */
                   3167:       savm=oldm;
                   3168:       oldm=newm;
                   3169:     }
                   3170:     for(i=1; i<=nlstate+ndeath; i++)
                   3171:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3172:        po[i][j][h]=newm[i][j];
                   3173:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3174:       }
                   3175:     /*printf("h=%d ",h);*/
                   3176:   } /* end h */
1.222     brouard  3177:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3178:   return po;
                   3179: }
                   3180: 
                   3181: 
1.162     brouard  3182: #ifdef NLOPT
                   3183:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3184:   double fret;
                   3185:   double *xt;
                   3186:   int j;
                   3187:   myfunc_data *d2 = (myfunc_data *) pd;
                   3188: /* xt = (p1-1); */
                   3189:   xt=vector(1,n); 
                   3190:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3191: 
                   3192:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3193:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3194:   printf("Function = %.12lf ",fret);
                   3195:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3196:   printf("\n");
                   3197:  free_vector(xt,1,n);
                   3198:   return fret;
                   3199: }
                   3200: #endif
1.126     brouard  3201: 
                   3202: /*************** log-likelihood *************/
                   3203: double func( double *x)
                   3204: {
1.226     brouard  3205:   int i, ii, j, k, mi, d, kk;
                   3206:   int ioffset=0;
                   3207:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3208:   double **out;
                   3209:   double lli; /* Individual log likelihood */
                   3210:   int s1, s2;
1.228     brouard  3211:   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  3212:   double bbh, survp;
                   3213:   long ipmx;
                   3214:   double agexact;
                   3215:   /*extern weight */
                   3216:   /* We are differentiating ll according to initial status */
                   3217:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3218:   /*for(i=1;i<imx;i++) 
                   3219:     printf(" %d\n",s[4][i]);
                   3220:   */
1.162     brouard  3221: 
1.226     brouard  3222:   ++countcallfunc;
1.162     brouard  3223: 
1.226     brouard  3224:   cov[1]=1.;
1.126     brouard  3225: 
1.226     brouard  3226:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3227:   ioffset=0;
1.226     brouard  3228:   if(mle==1){
                   3229:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3230:       /* Computes the values of the ncovmodel covariates of the model
                   3231:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3232:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3233:         to be observed in j being in i according to the model.
                   3234:       */
1.243     brouard  3235:       ioffset=2+nagesqr ;
1.233     brouard  3236:    /* Fixed */
1.234     brouard  3237:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3238:        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)*/
                   3239:       }
1.226     brouard  3240:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3241:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3242:         has been calculated etc */
                   3243:       /* For an individual i, wav[i] gives the number of effective waves */
                   3244:       /* We compute the contribution to Likelihood of each effective transition
                   3245:         mw[mi][i] is real wave of the mi th effectve wave */
                   3246:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3247:         s2=s[mw[mi+1][i]][i];
                   3248:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3249:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3250:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3251:       */
                   3252:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3253:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3254:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3255:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3256:        }
                   3257:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3258:          for (j=1;j<=nlstate+ndeath;j++){
                   3259:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3260:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3261:          }
                   3262:        for(d=0; d<dh[mi][i]; d++){
                   3263:          newm=savm;
                   3264:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3265:          cov[2]=agexact;
                   3266:          if(nagesqr==1)
                   3267:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3268:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3269:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3270:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3271:          else
                   3272:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3273:          }
                   3274:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3275:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3276:          savm=oldm;
                   3277:          oldm=newm;
                   3278:        } /* end mult */
                   3279:        
                   3280:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3281:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3282:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3283:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3284:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3285:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3286:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3287:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3288:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3289:                                 * -stepm/2 to stepm/2 .
                   3290:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3291:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3292:                                 */
1.234     brouard  3293:        s1=s[mw[mi][i]][i];
                   3294:        s2=s[mw[mi+1][i]][i];
                   3295:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3296:        /* bias bh is positive if real duration
                   3297:         * is higher than the multiple of stepm and negative otherwise.
                   3298:         */
                   3299:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3300:        if( s2 > nlstate){ 
                   3301:          /* i.e. if s2 is a death state and if the date of death is known 
                   3302:             then the contribution to the likelihood is the probability to 
                   3303:             die between last step unit time and current  step unit time, 
                   3304:             which is also equal to probability to die before dh 
                   3305:             minus probability to die before dh-stepm . 
                   3306:             In version up to 0.92 likelihood was computed
                   3307:             as if date of death was unknown. Death was treated as any other
                   3308:             health state: the date of the interview describes the actual state
                   3309:             and not the date of a change in health state. The former idea was
                   3310:             to consider that at each interview the state was recorded
                   3311:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3312:             introduced the exact date of death then we should have modified
                   3313:             the contribution of an exact death to the likelihood. This new
                   3314:             contribution is smaller and very dependent of the step unit
                   3315:             stepm. It is no more the probability to die between last interview
                   3316:             and month of death but the probability to survive from last
                   3317:             interview up to one month before death multiplied by the
                   3318:             probability to die within a month. Thanks to Chris
                   3319:             Jackson for correcting this bug.  Former versions increased
                   3320:             mortality artificially. The bad side is that we add another loop
                   3321:             which slows down the processing. The difference can be up to 10%
                   3322:             lower mortality.
                   3323:          */
                   3324:          /* If, at the beginning of the maximization mostly, the
                   3325:             cumulative probability or probability to be dead is
                   3326:             constant (ie = 1) over time d, the difference is equal to
                   3327:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3328:             s1 at precedent wave, to be dead a month before current
                   3329:             wave is equal to probability, being at state s1 at
                   3330:             precedent wave, to be dead at mont of the current
                   3331:             wave. Then the observed probability (that this person died)
                   3332:             is null according to current estimated parameter. In fact,
                   3333:             it should be very low but not zero otherwise the log go to
                   3334:             infinity.
                   3335:          */
1.183     brouard  3336: /* #ifdef INFINITYORIGINAL */
                   3337: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3338: /* #else */
                   3339: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3340: /*         lli=log(mytinydouble); */
                   3341: /*       else */
                   3342: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3343: /* #endif */
1.226     brouard  3344:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3345:          
1.226     brouard  3346:        } else if  ( s2==-1 ) { /* alive */
                   3347:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3348:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3349:          /*survp += out[s1][j]; */
                   3350:          lli= log(survp);
                   3351:        }
                   3352:        else if  (s2==-4) { 
                   3353:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3354:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3355:          lli= log(survp); 
                   3356:        } 
                   3357:        else if  (s2==-5) { 
                   3358:          for (j=1,survp=0. ; j<=2; j++)  
                   3359:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3360:          lli= log(survp); 
                   3361:        } 
                   3362:        else{
                   3363:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3364:          /*  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 */
                   3365:        } 
                   3366:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3367:        /*if(lli ==000.0)*/
                   3368:        /*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); */
                   3369:        ipmx +=1;
                   3370:        sw += weight[i];
                   3371:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3372:        /* if (lli < log(mytinydouble)){ */
                   3373:        /*   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); */
                   3374:        /*   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]); */
                   3375:        /* } */
                   3376:       } /* end of wave */
                   3377:     } /* end of individual */
                   3378:   }  else if(mle==2){
                   3379:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3380:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3381:       for(mi=1; mi<= wav[i]-1; mi++){
                   3382:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3383:          for (j=1;j<=nlstate+ndeath;j++){
                   3384:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3385:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3386:          }
                   3387:        for(d=0; d<=dh[mi][i]; d++){
                   3388:          newm=savm;
                   3389:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3390:          cov[2]=agexact;
                   3391:          if(nagesqr==1)
                   3392:            cov[3]= agexact*agexact;
                   3393:          for (kk=1; kk<=cptcovage;kk++) {
                   3394:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3395:          }
                   3396:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3397:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3398:          savm=oldm;
                   3399:          oldm=newm;
                   3400:        } /* end mult */
                   3401:       
                   3402:        s1=s[mw[mi][i]][i];
                   3403:        s2=s[mw[mi+1][i]][i];
                   3404:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3405:        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 */
                   3406:        ipmx +=1;
                   3407:        sw += weight[i];
                   3408:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3409:       } /* end of wave */
                   3410:     } /* end of individual */
                   3411:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3412:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3413:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3414:       for(mi=1; mi<= wav[i]-1; mi++){
                   3415:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3416:          for (j=1;j<=nlstate+ndeath;j++){
                   3417:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3418:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3419:          }
                   3420:        for(d=0; d<dh[mi][i]; d++){
                   3421:          newm=savm;
                   3422:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3423:          cov[2]=agexact;
                   3424:          if(nagesqr==1)
                   3425:            cov[3]= agexact*agexact;
                   3426:          for (kk=1; kk<=cptcovage;kk++) {
                   3427:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3428:          }
                   3429:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3430:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3431:          savm=oldm;
                   3432:          oldm=newm;
                   3433:        } /* end mult */
                   3434:       
                   3435:        s1=s[mw[mi][i]][i];
                   3436:        s2=s[mw[mi+1][i]][i];
                   3437:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3438:        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 */
                   3439:        ipmx +=1;
                   3440:        sw += weight[i];
                   3441:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3442:       } /* end of wave */
                   3443:     } /* end of individual */
                   3444:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3445:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3446:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3447:       for(mi=1; mi<= wav[i]-1; mi++){
                   3448:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3449:          for (j=1;j<=nlstate+ndeath;j++){
                   3450:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3451:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3452:          }
                   3453:        for(d=0; d<dh[mi][i]; d++){
                   3454:          newm=savm;
                   3455:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3456:          cov[2]=agexact;
                   3457:          if(nagesqr==1)
                   3458:            cov[3]= agexact*agexact;
                   3459:          for (kk=1; kk<=cptcovage;kk++) {
                   3460:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3461:          }
1.126     brouard  3462:        
1.226     brouard  3463:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3464:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3465:          savm=oldm;
                   3466:          oldm=newm;
                   3467:        } /* end mult */
                   3468:       
                   3469:        s1=s[mw[mi][i]][i];
                   3470:        s2=s[mw[mi+1][i]][i];
                   3471:        if( s2 > nlstate){ 
                   3472:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3473:        } else if  ( s2==-1 ) { /* alive */
                   3474:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3475:            survp += out[s1][j];
                   3476:          lli= log(survp);
                   3477:        }else{
                   3478:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3479:        }
                   3480:        ipmx +=1;
                   3481:        sw += weight[i];
                   3482:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3483: /*     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  3484:       } /* end of wave */
                   3485:     } /* end of individual */
                   3486:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3487:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3488:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3489:       for(mi=1; mi<= wav[i]-1; mi++){
                   3490:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3491:          for (j=1;j<=nlstate+ndeath;j++){
                   3492:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3493:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3494:          }
                   3495:        for(d=0; d<dh[mi][i]; d++){
                   3496:          newm=savm;
                   3497:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3498:          cov[2]=agexact;
                   3499:          if(nagesqr==1)
                   3500:            cov[3]= agexact*agexact;
                   3501:          for (kk=1; kk<=cptcovage;kk++) {
                   3502:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3503:          }
1.126     brouard  3504:        
1.226     brouard  3505:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3506:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3507:          savm=oldm;
                   3508:          oldm=newm;
                   3509:        } /* end mult */
                   3510:       
                   3511:        s1=s[mw[mi][i]][i];
                   3512:        s2=s[mw[mi+1][i]][i];
                   3513:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3514:        ipmx +=1;
                   3515:        sw += weight[i];
                   3516:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3517:        /*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]);*/
                   3518:       } /* end of wave */
                   3519:     } /* end of individual */
                   3520:   } /* End of if */
                   3521:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3522:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3523:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3524:   return -l;
1.126     brouard  3525: }
                   3526: 
                   3527: /*************** log-likelihood *************/
                   3528: double funcone( double *x)
                   3529: {
1.228     brouard  3530:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3531:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3532:   int ioffset=0;
1.131     brouard  3533:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3534:   double **out;
                   3535:   double lli; /* Individual log likelihood */
                   3536:   double llt;
                   3537:   int s1, s2;
1.228     brouard  3538:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3539: 
1.126     brouard  3540:   double bbh, survp;
1.187     brouard  3541:   double agexact;
1.214     brouard  3542:   double agebegin, ageend;
1.126     brouard  3543:   /*extern weight */
                   3544:   /* We are differentiating ll according to initial status */
                   3545:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3546:   /*for(i=1;i<imx;i++) 
                   3547:     printf(" %d\n",s[4][i]);
                   3548:   */
                   3549:   cov[1]=1.;
                   3550: 
                   3551:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3552:   ioffset=0;
                   3553:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3554:     /* ioffset=2+nagesqr+cptcovage; */
                   3555:     ioffset=2+nagesqr;
1.232     brouard  3556:     /* Fixed */
1.224     brouard  3557:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3558:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3559:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3560:       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)*/
                   3561: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3562: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3563: /*    cov[2+6]=covar[2][i]; V2  */
                   3564: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3565: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3566: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3567: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3568: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3569: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3570:     }
1.232     brouard  3571:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3572:     /*   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?)*\/ */
                   3573:     /* } */
1.231     brouard  3574:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3575:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3576:     /* } */
1.225     brouard  3577:     
1.233     brouard  3578: 
                   3579:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3580:     /* Wave varying (but not age varying) */
                   3581:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3582:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3583:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3584:       }
1.232     brouard  3585:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3586:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3587:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3588:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3589:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3590:       /* 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  3591:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3592:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3593:       /*       /\* 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]); *\/ */
                   3594:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3595:       /* } */
1.126     brouard  3596:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3597:        for (j=1;j<=nlstate+ndeath;j++){
                   3598:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3599:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3600:        }
1.214     brouard  3601:       
                   3602:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3603:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3604:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247   ! brouard  3605:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3606:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3607:          and mw[mi+1][i]. dh depends on stepm.*/
                   3608:        newm=savm;
1.247   ! brouard  3609:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3610:        cov[2]=agexact;
                   3611:        if(nagesqr==1)
                   3612:          cov[3]= agexact*agexact;
                   3613:        for (kk=1; kk<=cptcovage;kk++) {
                   3614:          if(!FixedV[Tvar[Tage[kk]]])
                   3615:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3616:          else
                   3617:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3618:        }
                   3619:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3620:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3621:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3622:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3623:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3624:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3625:        savm=oldm;
                   3626:        oldm=newm;
1.126     brouard  3627:       } /* end mult */
                   3628:       
                   3629:       s1=s[mw[mi][i]][i];
                   3630:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3631:       /* if(s2==-1){ */
                   3632:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3633:       /*       /\* exit(1); *\/ */
                   3634:       /* } */
1.126     brouard  3635:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3636:       /* bias is positive if real duration
                   3637:        * is higher than the multiple of stepm and negative otherwise.
                   3638:        */
                   3639:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3640:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3641:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3642:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3643:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3644:        lli= log(survp);
1.126     brouard  3645:       }else if (mle==1){
1.242     brouard  3646:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3647:       } else if(mle==2){
1.242     brouard  3648:        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  3649:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3650:        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  3651:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3652:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3653:       } else{  /* mle=0 back to 1 */
1.242     brouard  3654:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3655:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3656:       } /* End of if */
                   3657:       ipmx +=1;
                   3658:       sw += weight[i];
                   3659:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3660:       /*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  3661:       if(globpr){
1.246     brouard  3662:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3663:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3664:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3665:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3666:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3667:          llt +=ll[k]*gipmx/gsw;
                   3668:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3669:        }
                   3670:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3671:       }
1.232     brouard  3672:        } /* end of wave */
                   3673: } /* end of individual */
                   3674: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3675: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3676: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3677: if(globpr==0){ /* First time we count the contributions and weights */
                   3678:        gipmx=ipmx;
                   3679:        gsw=sw;
                   3680: }
                   3681: return -l;
1.126     brouard  3682: }
                   3683: 
                   3684: 
                   3685: /*************** function likelione ***********/
                   3686: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3687: {
                   3688:   /* This routine should help understanding what is done with 
                   3689:      the selection of individuals/waves and
                   3690:      to check the exact contribution to the likelihood.
                   3691:      Plotting could be done.
                   3692:    */
                   3693:   int k;
                   3694: 
                   3695:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3696:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3697:     strcat(fileresilk,fileresu);
1.126     brouard  3698:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3699:       printf("Problem with resultfile: %s\n", fileresilk);
                   3700:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3701:     }
1.214     brouard  3702:     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");
                   3703:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3704:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3705:     for(k=1; k<=nlstate; k++) 
                   3706:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3707:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3708:   }
                   3709: 
                   3710:   *fretone=(*funcone)(p);
                   3711:   if(*globpri !=0){
                   3712:     fclose(ficresilk);
1.205     brouard  3713:     if (mle ==0)
                   3714:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3715:     else if(mle >=1)
                   3716:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3717:     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  3718:     
1.208     brouard  3719:       
                   3720:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3721:       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  3722: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3723:     }
1.207     brouard  3724:     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  3725: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3726:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3727: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3728:     fflush(fichtm);
1.205     brouard  3729:   }
1.126     brouard  3730:   return;
                   3731: }
                   3732: 
                   3733: 
                   3734: /*********** Maximum Likelihood Estimation ***************/
                   3735: 
                   3736: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3737: {
1.165     brouard  3738:   int i,j, iter=0;
1.126     brouard  3739:   double **xi;
                   3740:   double fret;
                   3741:   double fretone; /* Only one call to likelihood */
                   3742:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3743: 
                   3744: #ifdef NLOPT
                   3745:   int creturn;
                   3746:   nlopt_opt opt;
                   3747:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3748:   double *lb;
                   3749:   double minf; /* the minimum objective value, upon return */
                   3750:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3751:   myfunc_data dinst, *d = &dinst;
                   3752: #endif
                   3753: 
                   3754: 
1.126     brouard  3755:   xi=matrix(1,npar,1,npar);
                   3756:   for (i=1;i<=npar;i++)
                   3757:     for (j=1;j<=npar;j++)
                   3758:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3759:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3760:   strcpy(filerespow,"POW_"); 
1.126     brouard  3761:   strcat(filerespow,fileres);
                   3762:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3763:     printf("Problem with resultfile: %s\n", filerespow);
                   3764:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3765:   }
                   3766:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3767:   for (i=1;i<=nlstate;i++)
                   3768:     for(j=1;j<=nlstate+ndeath;j++)
                   3769:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3770:   fprintf(ficrespow,"\n");
1.162     brouard  3771: #ifdef POWELL
1.126     brouard  3772:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3773: #endif
1.126     brouard  3774: 
1.162     brouard  3775: #ifdef NLOPT
                   3776: #ifdef NEWUOA
                   3777:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3778: #else
                   3779:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3780: #endif
                   3781:   lb=vector(0,npar-1);
                   3782:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3783:   nlopt_set_lower_bounds(opt, lb);
                   3784:   nlopt_set_initial_step1(opt, 0.1);
                   3785:   
                   3786:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3787:   d->function = func;
                   3788:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3789:   nlopt_set_min_objective(opt, myfunc, d);
                   3790:   nlopt_set_xtol_rel(opt, ftol);
                   3791:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3792:     printf("nlopt failed! %d\n",creturn); 
                   3793:   }
                   3794:   else {
                   3795:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3796:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3797:     iter=1; /* not equal */
                   3798:   }
                   3799:   nlopt_destroy(opt);
                   3800: #endif
1.126     brouard  3801:   free_matrix(xi,1,npar,1,npar);
                   3802:   fclose(ficrespow);
1.203     brouard  3803:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3804:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3805:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3806: 
                   3807: }
                   3808: 
                   3809: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3810: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3811: {
                   3812:   double  **a,**y,*x,pd;
1.203     brouard  3813:   /* double **hess; */
1.164     brouard  3814:   int i, j;
1.126     brouard  3815:   int *indx;
                   3816: 
                   3817:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3818:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3819:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3820:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3821:   double gompertz(double p[]);
1.203     brouard  3822:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3823: 
                   3824:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3825:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3826:   for (i=1;i<=npar;i++){
1.203     brouard  3827:     printf("%d-",i);fflush(stdout);
                   3828:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3829:    
                   3830:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3831:     
                   3832:     /*  printf(" %f ",p[i]);
                   3833:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3834:   }
                   3835:   
                   3836:   for (i=1;i<=npar;i++) {
                   3837:     for (j=1;j<=npar;j++)  {
                   3838:       if (j>i) { 
1.203     brouard  3839:        printf(".%d-%d",i,j);fflush(stdout);
                   3840:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3841:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3842:        
                   3843:        hess[j][i]=hess[i][j];    
                   3844:        /*printf(" %lf ",hess[i][j]);*/
                   3845:       }
                   3846:     }
                   3847:   }
                   3848:   printf("\n");
                   3849:   fprintf(ficlog,"\n");
                   3850: 
                   3851:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3852:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3853:   
                   3854:   a=matrix(1,npar,1,npar);
                   3855:   y=matrix(1,npar,1,npar);
                   3856:   x=vector(1,npar);
                   3857:   indx=ivector(1,npar);
                   3858:   for (i=1;i<=npar;i++)
                   3859:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3860:   ludcmp(a,npar,indx,&pd);
                   3861: 
                   3862:   for (j=1;j<=npar;j++) {
                   3863:     for (i=1;i<=npar;i++) x[i]=0;
                   3864:     x[j]=1;
                   3865:     lubksb(a,npar,indx,x);
                   3866:     for (i=1;i<=npar;i++){ 
                   3867:       matcov[i][j]=x[i];
                   3868:     }
                   3869:   }
                   3870: 
                   3871:   printf("\n#Hessian matrix#\n");
                   3872:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3873:   for (i=1;i<=npar;i++) { 
                   3874:     for (j=1;j<=npar;j++) { 
1.203     brouard  3875:       printf("%.6e ",hess[i][j]);
                   3876:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3877:     }
                   3878:     printf("\n");
                   3879:     fprintf(ficlog,"\n");
                   3880:   }
                   3881: 
1.203     brouard  3882:   /* printf("\n#Covariance matrix#\n"); */
                   3883:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3884:   /* for (i=1;i<=npar;i++) {  */
                   3885:   /*   for (j=1;j<=npar;j++) {  */
                   3886:   /*     printf("%.6e ",matcov[i][j]); */
                   3887:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3888:   /*   } */
                   3889:   /*   printf("\n"); */
                   3890:   /*   fprintf(ficlog,"\n"); */
                   3891:   /* } */
                   3892: 
1.126     brouard  3893:   /* Recompute Inverse */
1.203     brouard  3894:   /* for (i=1;i<=npar;i++) */
                   3895:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3896:   /* ludcmp(a,npar,indx,&pd); */
                   3897: 
                   3898:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3899: 
                   3900:   /* for (j=1;j<=npar;j++) { */
                   3901:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3902:   /*   x[j]=1; */
                   3903:   /*   lubksb(a,npar,indx,x); */
                   3904:   /*   for (i=1;i<=npar;i++){  */
                   3905:   /*     y[i][j]=x[i]; */
                   3906:   /*     printf("%.3e ",y[i][j]); */
                   3907:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3908:   /*   } */
                   3909:   /*   printf("\n"); */
                   3910:   /*   fprintf(ficlog,"\n"); */
                   3911:   /* } */
                   3912: 
                   3913:   /* Verifying the inverse matrix */
                   3914: #ifdef DEBUGHESS
                   3915:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3916: 
1.203     brouard  3917:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3918:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3919: 
                   3920:   for (j=1;j<=npar;j++) {
                   3921:     for (i=1;i<=npar;i++){ 
1.203     brouard  3922:       printf("%.2f ",y[i][j]);
                   3923:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3924:     }
                   3925:     printf("\n");
                   3926:     fprintf(ficlog,"\n");
                   3927:   }
1.203     brouard  3928: #endif
1.126     brouard  3929: 
                   3930:   free_matrix(a,1,npar,1,npar);
                   3931:   free_matrix(y,1,npar,1,npar);
                   3932:   free_vector(x,1,npar);
                   3933:   free_ivector(indx,1,npar);
1.203     brouard  3934:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3935: 
                   3936: 
                   3937: }
                   3938: 
                   3939: /*************** hessian matrix ****************/
                   3940: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3941: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3942:   int i;
                   3943:   int l=1, lmax=20;
1.203     brouard  3944:   double k1,k2, res, fx;
1.132     brouard  3945:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3946:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3947:   int k=0,kmax=10;
                   3948:   double l1;
                   3949: 
                   3950:   fx=func(x);
                   3951:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3952:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3953:     l1=pow(10,l);
                   3954:     delts=delt;
                   3955:     for(k=1 ; k <kmax; k=k+1){
                   3956:       delt = delta*(l1*k);
                   3957:       p2[theta]=x[theta] +delt;
1.145     brouard  3958:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3959:       p2[theta]=x[theta]-delt;
                   3960:       k2=func(p2)-fx;
                   3961:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3962:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3963:       
1.203     brouard  3964: #ifdef DEBUGHESSII
1.126     brouard  3965:       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);
                   3966:       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);
                   3967: #endif
                   3968:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3969:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3970:        k=kmax;
                   3971:       }
                   3972:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3973:        k=kmax; l=lmax*10;
1.126     brouard  3974:       }
                   3975:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3976:        delts=delt;
                   3977:       }
1.203     brouard  3978:     } /* End loop k */
1.126     brouard  3979:   }
                   3980:   delti[theta]=delts;
                   3981:   return res; 
                   3982:   
                   3983: }
                   3984: 
1.203     brouard  3985: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3986: {
                   3987:   int i;
1.164     brouard  3988:   int l=1, lmax=20;
1.126     brouard  3989:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3990:   double p2[MAXPARM+1];
1.203     brouard  3991:   int k, kmax=1;
                   3992:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3993: 
                   3994:   int firstime=0;
1.203     brouard  3995:   
1.126     brouard  3996:   fx=func(x);
1.203     brouard  3997:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3998:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3999:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4000:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4001:     k1=func(p2)-fx;
                   4002:   
1.203     brouard  4003:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4004:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4005:     k2=func(p2)-fx;
                   4006:   
1.203     brouard  4007:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4008:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4009:     k3=func(p2)-fx;
                   4010:   
1.203     brouard  4011:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4012:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4013:     k4=func(p2)-fx;
1.203     brouard  4014:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4015:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4016:       firstime=1;
1.203     brouard  4017:       kmax=kmax+10;
1.208     brouard  4018:     }
                   4019:     if(kmax >=10 || firstime ==1){
1.246     brouard  4020:       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);
                   4021:       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  4022:       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);
                   4023:       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);
                   4024:     }
                   4025: #ifdef DEBUGHESSIJ
                   4026:     v1=hess[thetai][thetai];
                   4027:     v2=hess[thetaj][thetaj];
                   4028:     cv12=res;
                   4029:     /* Computing eigen value of Hessian matrix */
                   4030:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4031:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4032:     if ((lc2 <0) || (lc1 <0) ){
                   4033:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4034:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4035:       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);
                   4036:       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);
                   4037:     }
1.126     brouard  4038: #endif
                   4039:   }
                   4040:   return res;
                   4041: }
                   4042: 
1.203     brouard  4043:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4044: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4045: /* { */
                   4046: /*   int i; */
                   4047: /*   int l=1, lmax=20; */
                   4048: /*   double k1,k2,k3,k4,res,fx; */
                   4049: /*   double p2[MAXPARM+1]; */
                   4050: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4051: /*   int k=0,kmax=10; */
                   4052: /*   double l1; */
                   4053:   
                   4054: /*   fx=func(x); */
                   4055: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4056: /*     l1=pow(10,l); */
                   4057: /*     delts=delt; */
                   4058: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4059: /*       delt = delti*(l1*k); */
                   4060: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4061: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4062: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4063: /*       k1=func(p2)-fx; */
                   4064:       
                   4065: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4066: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4067: /*       k2=func(p2)-fx; */
                   4068:       
                   4069: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4070: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4071: /*       k3=func(p2)-fx; */
                   4072:       
                   4073: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4074: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4075: /*       k4=func(p2)-fx; */
                   4076: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4077: /* #ifdef DEBUGHESSIJ */
                   4078: /*       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); */
                   4079: /*       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); */
                   4080: /* #endif */
                   4081: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4082: /*     k=kmax; */
                   4083: /*       } */
                   4084: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4085: /*     k=kmax; l=lmax*10; */
                   4086: /*       } */
                   4087: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4088: /*     delts=delt; */
                   4089: /*       } */
                   4090: /*     } /\* End loop k *\/ */
                   4091: /*   } */
                   4092: /*   delti[theta]=delts; */
                   4093: /*   return res;  */
                   4094: /* } */
                   4095: 
                   4096: 
1.126     brouard  4097: /************** Inverse of matrix **************/
                   4098: void ludcmp(double **a, int n, int *indx, double *d) 
                   4099: { 
                   4100:   int i,imax,j,k; 
                   4101:   double big,dum,sum,temp; 
                   4102:   double *vv; 
                   4103:  
                   4104:   vv=vector(1,n); 
                   4105:   *d=1.0; 
                   4106:   for (i=1;i<=n;i++) { 
                   4107:     big=0.0; 
                   4108:     for (j=1;j<=n;j++) 
                   4109:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   4110:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   4111:     vv[i]=1.0/big; 
                   4112:   } 
                   4113:   for (j=1;j<=n;j++) { 
                   4114:     for (i=1;i<j;i++) { 
                   4115:       sum=a[i][j]; 
                   4116:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4117:       a[i][j]=sum; 
                   4118:     } 
                   4119:     big=0.0; 
                   4120:     for (i=j;i<=n;i++) { 
                   4121:       sum=a[i][j]; 
                   4122:       for (k=1;k<j;k++) 
                   4123:        sum -= a[i][k]*a[k][j]; 
                   4124:       a[i][j]=sum; 
                   4125:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4126:        big=dum; 
                   4127:        imax=i; 
                   4128:       } 
                   4129:     } 
                   4130:     if (j != imax) { 
                   4131:       for (k=1;k<=n;k++) { 
                   4132:        dum=a[imax][k]; 
                   4133:        a[imax][k]=a[j][k]; 
                   4134:        a[j][k]=dum; 
                   4135:       } 
                   4136:       *d = -(*d); 
                   4137:       vv[imax]=vv[j]; 
                   4138:     } 
                   4139:     indx[j]=imax; 
                   4140:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4141:     if (j != n) { 
                   4142:       dum=1.0/(a[j][j]); 
                   4143:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4144:     } 
                   4145:   } 
                   4146:   free_vector(vv,1,n);  /* Doesn't work */
                   4147: ;
                   4148: } 
                   4149: 
                   4150: void lubksb(double **a, int n, int *indx, double b[]) 
                   4151: { 
                   4152:   int i,ii=0,ip,j; 
                   4153:   double sum; 
                   4154:  
                   4155:   for (i=1;i<=n;i++) { 
                   4156:     ip=indx[i]; 
                   4157:     sum=b[ip]; 
                   4158:     b[ip]=b[i]; 
                   4159:     if (ii) 
                   4160:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4161:     else if (sum) ii=i; 
                   4162:     b[i]=sum; 
                   4163:   } 
                   4164:   for (i=n;i>=1;i--) { 
                   4165:     sum=b[i]; 
                   4166:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4167:     b[i]=sum/a[i][i]; 
                   4168:   } 
                   4169: } 
                   4170: 
                   4171: void pstamp(FILE *fichier)
                   4172: {
1.196     brouard  4173:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4174: }
                   4175: 
                   4176: /************ Frequencies ********************/
1.226     brouard  4177: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4178:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4179:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4180: {  /* Some frequencies */
                   4181:   
1.227     brouard  4182:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4183:   int iind=0, iage=0;
                   4184:   int mi; /* Effective wave */
                   4185:   int first;
                   4186:   double ***freq; /* Frequencies */
                   4187:   double *meanq;
                   4188:   double **meanqt;
                   4189:   double *pp, **prop, *posprop, *pospropt;
                   4190:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4191:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4192:   double agebegin, ageend;
                   4193:     
                   4194:   pp=vector(1,nlstate);
                   4195:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4196:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4197:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4198:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4199:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4200:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4201:   strcpy(fileresp,"P_");
                   4202:   strcat(fileresp,fileresu);
                   4203:   /*strcat(fileresphtm,fileresu);*/
                   4204:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4205:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4206:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4207:     exit(0);
                   4208:   }
1.240     brouard  4209:   
1.226     brouard  4210:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4211:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4212:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4213:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4214:     fflush(ficlog);
                   4215:     exit(70); 
                   4216:   }
                   4217:   else{
                   4218:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4219: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4220: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4221:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4222:   }
1.237     brouard  4223:   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  4224:   
1.226     brouard  4225:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4226:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4227:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4228:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4229:     fflush(ficlog);
                   4230:     exit(70); 
1.240     brouard  4231:   } else{
1.226     brouard  4232:     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  4233: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4234: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4235:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4236:   }
1.240     brouard  4237:   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);
                   4238:   
1.226     brouard  4239:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4240:   j1=0;
1.126     brouard  4241:   
1.227     brouard  4242:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4243:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4244:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4245:   
1.226     brouard  4246:   first=1;
1.240     brouard  4247:   
1.226     brouard  4248:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4249:      reference=low_education V1=0,V2=0
                   4250:      med_educ                V1=1 V2=0, 
                   4251:      high_educ               V1=0 V2=1
                   4252:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4253:   */
1.240     brouard  4254:   
1.227     brouard  4255:   for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
1.226     brouard  4256:     posproptt=0.;
                   4257:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4258:       scanf("%d", i);*/
                   4259:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4260:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.240     brouard  4261:        for(m=iagemin; m <= iagemax+3; m++)
                   4262:          freq[i][jk][m]=0;
                   4263:     
1.226     brouard  4264:     for (i=1; i<=nlstate; i++)  {
                   4265:       for(m=iagemin; m <= iagemax+3; m++)
1.240     brouard  4266:        prop[i][m]=0;
1.226     brouard  4267:       posprop[i]=0;
                   4268:       pospropt[i]=0;
                   4269:     }
1.227     brouard  4270:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4271:     /*   meanq[z1]+=0.; */
                   4272:     /*   for(m=1;m<=lastpass;m++){ */
                   4273:     /*         meanqt[m][z1]=0.; */
                   4274:     /*   } */
                   4275:     /* } */
1.240     brouard  4276:     
1.226     brouard  4277:     dateintsum=0;
                   4278:     k2cpt=0;
1.227     brouard  4279:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4280:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4281:       bool=1;
1.227     brouard  4282:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4283:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4284:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4285:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4286:          /* } */
1.234     brouard  4287:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4288:            /* if(Tvaraff[z1] ==-20){ */
                   4289:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4290:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4291:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4292:            /* }else  */
                   4293:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4294:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4295:              bool=0;
                   4296:              /* 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", 
                   4297:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4298:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4299:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4300:            } /* Onlyf fixed */
                   4301:          } /* end z1 */
                   4302:        } /* cptcovn > 0 */
1.227     brouard  4303:       } /* end any */
                   4304:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4305:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4306:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4307:          m=mw[mi][iind];
                   4308:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4309:            for (z1=1; z1<=cptcoveff; z1++) {
                   4310:              if( Fixed[Tmodelind[z1]]==1){
                   4311:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4312:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4313:                  bool=0;
                   4314:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4315:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4316:                  bool=0;
                   4317:                }
                   4318:              }
                   4319:            }
                   4320:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4321:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4322:          if(bool==1){
                   4323:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4324:               and mw[mi+1][iind]. dh depends on stepm. */
                   4325:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4326:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4327:            if(m >=firstpass && m <=lastpass){
                   4328:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4329:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4330:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4331:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4332:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4333:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4334:              if (m<lastpass) {
                   4335:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4336:                /*   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]); */
                   4337:                if(s[m][iind]==-1)
                   4338:                  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.));
                   4339:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4340:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4341:                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 */
                   4342:              }
                   4343:            } /* end if between passes */  
                   4344:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4345:              dateintsum=dateintsum+k2;
                   4346:              k2cpt++;
                   4347:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4348:            }
                   4349:          } /* end bool 2 */
                   4350:        } /* end m */
1.226     brouard  4351:       } /* end bool */
                   4352:     } /* end iind = 1 to imx */
                   4353:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4354:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.240     brouard  4355:     
                   4356:     
1.226     brouard  4357:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4358:     pstamp(ficresp);
1.240     brouard  4359:     if  (cptcoveff>0){
1.226     brouard  4360:       fprintf(ficresp, "\n#********** Variable "); 
                   4361:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4362:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.240     brouard  4363:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4364:       for (z1=1; z1<=cptcoveff; z1++){
1.240     brouard  4365:        if(DummyV[z1]){
                   4366:          fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4367:          fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4368:          fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4369:          fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4370:        }else{
                   4371:          fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4372:          fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4373:          fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4374:          fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4375:        }
1.226     brouard  4376:       }
                   4377:       fprintf(ficresp, "**********\n#");
                   4378:       fprintf(ficresphtm, "**********</h3>\n");
                   4379:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4380:       fprintf(ficlog, "**********\n");
                   4381:     }
                   4382:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4383:     for(i=1; i<=nlstate;i++) {
1.240     brouard  4384:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
1.226     brouard  4385:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4386:     }
                   4387:     fprintf(ficresp, "\n");
                   4388:     fprintf(ficresphtm, "\n");
1.240     brouard  4389:     
1.226     brouard  4390:     /* Header of frequency table by age */
                   4391:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4392:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4393:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4394:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4395:        if(jk!=0 && m!=0)
                   4396:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4397:       }
                   4398:     }
                   4399:     fprintf(ficresphtmfr, "\n");
1.240     brouard  4400:     
1.226     brouard  4401:     /* For each age */
                   4402:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4403:       fprintf(ficresphtm,"<tr>");
                   4404:       if(iage==iagemax+1){
1.240     brouard  4405:        fprintf(ficlog,"1");
                   4406:        fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4407:       }else if(iage==iagemax+2){
1.240     brouard  4408:        fprintf(ficlog,"0");
                   4409:        fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4410:       }else if(iage==iagemax+3){
1.240     brouard  4411:        fprintf(ficlog,"Total");
                   4412:        fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4413:       }else{
1.240     brouard  4414:        if(first==1){
                   4415:          first=0;
                   4416:          printf("See log file for details...\n");
                   4417:        }
                   4418:        fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4419:        fprintf(ficlog,"Age %d", iage);
1.226     brouard  4420:       }
                   4421:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4422:        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4423:          pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4424:       }
                   4425:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4426:        for(m=-1, pos=0; m <=0 ; m++)
                   4427:          pos += freq[jk][m][iage];
                   4428:        if(pp[jk]>=1.e-10){
                   4429:          if(first==1){
                   4430:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4431:          }
                   4432:          fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4433:        }else{
                   4434:          if(first==1)
                   4435:            printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4436:          fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4437:        }
1.226     brouard  4438:       }
1.240     brouard  4439:       
1.226     brouard  4440:       for(jk=1; jk <=nlstate ; jk++){ 
1.240     brouard  4441:        /* posprop[jk]=0; */
                   4442:        for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4443:          pp[jk] += freq[jk][m][iage];
1.226     brouard  4444:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.240     brouard  4445:       
1.226     brouard  4446:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.240     brouard  4447:        pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4448:        posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4449:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4450:        pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4451:                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4452:       }
                   4453:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4454:        if(pos>=1.e-5){
                   4455:          if(first==1)
                   4456:            printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4457:          fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4458:        }else{
                   4459:          if(first==1)
                   4460:            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4461:          fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4462:        }
                   4463:        if( iage <= iagemax){
                   4464:          if(pos>=1.e-5){
                   4465:            fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4466:            fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4467:            /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4468:            /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4469:          }
                   4470:          else{
                   4471:            fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4472:            fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4473:          }
                   4474:        }
                   4475:        pospropt[jk] +=posprop[jk];
1.226     brouard  4476:       } /* end loop jk */
                   4477:       /* pospropt=0.; */
                   4478:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.240     brouard  4479:        for(m=-1; m <=nlstate+ndeath; m++){
                   4480:          if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4481:            if(first==1){
                   4482:              printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4483:            }
                   4484:            fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4485:          }
                   4486:          if(jk!=0 && m!=0)
                   4487:            fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4488:        }
1.226     brouard  4489:       } /* end loop jk */
                   4490:       posproptt=0.; 
                   4491:       for(jk=1; jk <=nlstate; jk++){
1.240     brouard  4492:        posproptt += pospropt[jk];
1.226     brouard  4493:       }
                   4494:       fprintf(ficresphtmfr,"</tr>\n ");
                   4495:       if(iage <= iagemax){
1.240     brouard  4496:        fprintf(ficresp,"\n");
                   4497:        fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4498:       }
                   4499:       if(first==1)
1.240     brouard  4500:        printf("Others in log...\n");
1.226     brouard  4501:       fprintf(ficlog,"\n");
                   4502:     } /* end loop age iage */
                   4503:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4504:     for(jk=1; jk <=nlstate ; jk++){
                   4505:       if(posproptt < 1.e-5){
1.240     brouard  4506:        fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4507:       }else{
1.240     brouard  4508:        fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4509:       }
                   4510:     }
                   4511:     fprintf(ficresphtm,"</tr>\n");
                   4512:     fprintf(ficresphtm,"</table>\n");
                   4513:     fprintf(ficresphtmfr,"</table>\n");
                   4514:     if(posproptt < 1.e-5){
                   4515:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4516:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4517:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4518:       invalidvarcomb[j1]=1;
                   4519:     }else{
                   4520:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4521:       invalidvarcomb[j1]=0;
                   4522:     }
                   4523:     fprintf(ficresphtmfr,"</table>\n");
                   4524:   } /* end selected combination of covariate j1 */
                   4525:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4526:   
1.226     brouard  4527:   fclose(ficresp);
                   4528:   fclose(ficresphtm);
                   4529:   fclose(ficresphtmfr);
                   4530:   free_vector(meanq,1,nqfveff);
                   4531:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4532:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4533:   free_vector(pospropt,1,nlstate);
                   4534:   free_vector(posprop,1,nlstate);
                   4535:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4536:   free_vector(pp,1,nlstate);
                   4537:   /* End of freqsummary */
                   4538: }
1.126     brouard  4539: 
                   4540: /************ Prevalence ********************/
1.227     brouard  4541: 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)
                   4542: {  
                   4543:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4544:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4545:      We still use firstpass and lastpass as another selection.
                   4546:   */
1.126     brouard  4547:  
1.227     brouard  4548:   int i, m, jk, j1, bool, z1,j, iv;
                   4549:   int mi; /* Effective wave */
                   4550:   int iage;
                   4551:   double agebegin, ageend;
                   4552: 
                   4553:   double **prop;
                   4554:   double posprop; 
                   4555:   double  y2; /* in fractional years */
                   4556:   int iagemin, iagemax;
                   4557:   int first; /** to stop verbosity which is redirected to log file */
                   4558: 
                   4559:   iagemin= (int) agemin;
                   4560:   iagemax= (int) agemax;
                   4561:   /*pp=vector(1,nlstate);*/
                   4562:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4563:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4564:   j1=0;
1.222     brouard  4565:   
1.227     brouard  4566:   /*j=cptcoveff;*/
                   4567:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4568:   
1.227     brouard  4569:   first=1;
                   4570:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4571:     for (i=1; i<=nlstate; i++)  
                   4572:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4573:        prop[i][iage]=0.0;
                   4574:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4575:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4576:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4577:     
                   4578:     for (i=1; i<=imx; i++) { /* Each individual */
                   4579:       bool=1;
                   4580:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4581:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4582:        m=mw[mi][i];
                   4583:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4584:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4585:        for (z1=1; z1<=cptcoveff; z1++){
                   4586:          if( Fixed[Tmodelind[z1]]==1){
                   4587:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4588:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4589:              bool=0;
                   4590:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4591:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4592:              bool=0;
                   4593:            }
                   4594:        }
                   4595:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4596:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4597:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4598:          if(m >=firstpass && m <=lastpass){
                   4599:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4600:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4601:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4602:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4603:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4604:                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); 
                   4605:                exit(1);
                   4606:              }
                   4607:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4608:                /*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]]);*/
                   4609:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4610:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4611:              } /* end valid statuses */ 
                   4612:            } /* end selection of dates */
                   4613:          } /* end selection of waves */
                   4614:        } /* end bool */
                   4615:       } /* end wave */
                   4616:     } /* end individual */
                   4617:     for(i=iagemin; i <= iagemax+3; i++){  
                   4618:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4619:        posprop += prop[jk][i]; 
                   4620:       } 
                   4621:       
                   4622:       for(jk=1; jk <=nlstate ; jk++){      
                   4623:        if( i <=  iagemax){ 
                   4624:          if(posprop>=1.e-5){ 
                   4625:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4626:          } else{
                   4627:            if(first==1){
                   4628:              first=0;
                   4629:              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]);
                   4630:            }
                   4631:          }
                   4632:        } 
                   4633:       }/* end jk */ 
                   4634:     }/* end i */ 
1.222     brouard  4635:      /*} *//* end i1 */
1.227     brouard  4636:   } /* end j1 */
1.222     brouard  4637:   
1.227     brouard  4638:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4639:   /*free_vector(pp,1,nlstate);*/
                   4640:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4641: }  /* End of prevalence */
1.126     brouard  4642: 
                   4643: /************* Waves Concatenation ***************/
                   4644: 
                   4645: 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)
                   4646: {
                   4647:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4648:      Death is a valid wave (if date is known).
                   4649:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4650:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4651:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4652:   */
1.126     brouard  4653: 
1.224     brouard  4654:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4655:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4656:      double sum=0., jmean=0.;*/
1.224     brouard  4657:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4658:   int j, k=0,jk, ju, jl;
                   4659:   double sum=0.;
                   4660:   first=0;
1.214     brouard  4661:   firstwo=0;
1.217     brouard  4662:   firsthree=0;
1.218     brouard  4663:   firstfour=0;
1.164     brouard  4664:   jmin=100000;
1.126     brouard  4665:   jmax=-1;
                   4666:   jmean=0.;
1.224     brouard  4667: 
                   4668: /* Treating live states */
1.214     brouard  4669:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4670:     mi=0;  /* First valid wave */
1.227     brouard  4671:     mli=0; /* Last valid wave */
1.126     brouard  4672:     m=firstpass;
1.214     brouard  4673:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4674:       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 */
                   4675:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4676:       }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 */
                   4677:        mw[++mi][i]=m;
                   4678:        mli=m;
1.224     brouard  4679:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4680:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4681:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4682:       }
1.227     brouard  4683:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4684: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4685:        break;
1.224     brouard  4686: #else
1.227     brouard  4687:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4688:          if(firsthree == 0){
                   4689:            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);
                   4690:            firsthree=1;
                   4691:          }
                   4692:          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);
                   4693:          mw[++mi][i]=m;
                   4694:          mli=m;
                   4695:        }
                   4696:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4697:          nbwarn++;
                   4698:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4699:            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);
                   4700:            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);
                   4701:          }
                   4702:          break;
                   4703:        }
                   4704:        break;
1.224     brouard  4705: #endif
1.227     brouard  4706:       }/* End m >= lastpass */
1.126     brouard  4707:     }/* end while */
1.224     brouard  4708: 
1.227     brouard  4709:     /* 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  4710:     /* After last pass */
1.224     brouard  4711: /* Treating death states */
1.214     brouard  4712:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4713:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4714:       /* } */
1.126     brouard  4715:       mi++;    /* Death is another wave */
                   4716:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4717:       /* Only death is a correct wave */
1.126     brouard  4718:       mw[mi][i]=m;
1.224     brouard  4719:     }
                   4720: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4721:     else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
1.216     brouard  4722:       /* m++; */
                   4723:       /* mi++; */
                   4724:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4725:       /* mw[mi][i]=m; */
1.218     brouard  4726:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4727:        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 */
                   4728:          nbwarn++;
                   4729:          if(firstfiv==0){
                   4730:            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 );
                   4731:            firstfiv=1;
                   4732:          }else{
                   4733:            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 );
                   4734:          }
                   4735:        }else{ /* Death occured afer last wave potential bias */
                   4736:          nberr++;
                   4737:          if(firstwo==0){
                   4738:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4739:            firstwo=1;
                   4740:          }
                   4741:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4742:        }
1.218     brouard  4743:       }else{ /* end date of interview is known */
1.227     brouard  4744:        /* death is known but not confirmed by death status at any wave */
                   4745:        if(firstfour==0){
                   4746:          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 );
                   4747:          firstfour=1;
                   4748:        }
                   4749:        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  4750:       }
1.224     brouard  4751:     } /* end if date of death is known */
                   4752: #endif
                   4753:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4754:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4755:     if(mi==0){
                   4756:       nbwarn++;
                   4757:       if(first==0){
1.227     brouard  4758:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4759:        first=1;
1.126     brouard  4760:       }
                   4761:       if(first==1){
1.227     brouard  4762:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4763:       }
                   4764:     } /* end mi==0 */
                   4765:   } /* End individuals */
1.214     brouard  4766:   /* wav and mw are no more changed */
1.223     brouard  4767:        
1.214     brouard  4768:   
1.126     brouard  4769:   for(i=1; i<=imx; i++){
                   4770:     for(mi=1; mi<wav[i];mi++){
                   4771:       if (stepm <=0)
1.227     brouard  4772:        dh[mi][i]=1;
1.126     brouard  4773:       else{
1.227     brouard  4774:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4775:          if (agedc[i] < 2*AGESUP) {
                   4776:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4777:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4778:            else if(j<0){
                   4779:              nberr++;
                   4780:              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]);
                   4781:              j=1; /* Temporary Dangerous patch */
                   4782:              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);
                   4783:              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]);
                   4784:              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);
                   4785:            }
                   4786:            k=k+1;
                   4787:            if (j >= jmax){
                   4788:              jmax=j;
                   4789:              ijmax=i;
                   4790:            }
                   4791:            if (j <= jmin){
                   4792:              jmin=j;
                   4793:              ijmin=i;
                   4794:            }
                   4795:            sum=sum+j;
                   4796:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4797:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4798:          }
                   4799:        }
                   4800:        else{
                   4801:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4802: /*       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  4803:                                        
1.227     brouard  4804:          k=k+1;
                   4805:          if (j >= jmax) {
                   4806:            jmax=j;
                   4807:            ijmax=i;
                   4808:          }
                   4809:          else if (j <= jmin){
                   4810:            jmin=j;
                   4811:            ijmin=i;
                   4812:          }
                   4813:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4814:          /*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]);*/
                   4815:          if(j<0){
                   4816:            nberr++;
                   4817:            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]);
                   4818:            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]);
                   4819:          }
                   4820:          sum=sum+j;
                   4821:        }
                   4822:        jk= j/stepm;
                   4823:        jl= j -jk*stepm;
                   4824:        ju= j -(jk+1)*stepm;
                   4825:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4826:          if(jl==0){
                   4827:            dh[mi][i]=jk;
                   4828:            bh[mi][i]=0;
                   4829:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4830:                  * to avoid the price of an extra matrix product in likelihood */
                   4831:            dh[mi][i]=jk+1;
                   4832:            bh[mi][i]=ju;
                   4833:          }
                   4834:        }else{
                   4835:          if(jl <= -ju){
                   4836:            dh[mi][i]=jk;
                   4837:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4838:                                 * is higher than the multiple of stepm and negative otherwise.
                   4839:                                 */
                   4840:          }
                   4841:          else{
                   4842:            dh[mi][i]=jk+1;
                   4843:            bh[mi][i]=ju;
                   4844:          }
                   4845:          if(dh[mi][i]==0){
                   4846:            dh[mi][i]=1; /* At least one step */
                   4847:            bh[mi][i]=ju; /* At least one step */
                   4848:            /*  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);*/
                   4849:          }
                   4850:        } /* end if mle */
1.126     brouard  4851:       }
                   4852:     } /* end wave */
                   4853:   }
                   4854:   jmean=sum/k;
                   4855:   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  4856:   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  4857: }
1.126     brouard  4858: 
                   4859: /*********** Tricode ****************************/
1.220     brouard  4860:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  4861:  {
                   4862:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4863:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   4864:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   4865:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4866:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   4867:     */
1.130     brouard  4868: 
1.242     brouard  4869:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   4870:    int modmaxcovj=0; /* Modality max of covariates j */
                   4871:    int cptcode=0; /* Modality max of covariates j */
                   4872:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  4873: 
                   4874: 
1.242     brouard  4875:    /* cptcoveff=0;  */
                   4876:    /* *cptcov=0; */
1.126     brouard  4877:  
1.242     brouard  4878:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4879: 
1.242     brouard  4880:    /* Loop on covariates without age and products and no quantitative variable */
                   4881:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
                   4882:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4883:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4884:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4885:        switch(Fixed[k]) {
                   4886:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   4887:         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*/
                   4888:           ij=(int)(covar[Tvar[k]][i]);
                   4889:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4890:            * If product of Vn*Vm, still boolean *:
                   4891:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4892:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4893:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4894:              modality of the nth covariate of individual i. */
                   4895:           if (ij > modmaxcovj)
                   4896:             modmaxcovj=ij; 
                   4897:           else if (ij < modmincovj) 
                   4898:             modmincovj=ij; 
                   4899:           if ((ij < -1) && (ij > NCOVMAX)){
                   4900:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4901:             exit(1);
                   4902:           }else
                   4903:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4904:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4905:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4906:           /* getting the maximum value of the modality of the covariate
                   4907:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4908:              female ies 1, then modmaxcovj=1.
                   4909:           */
                   4910:         } /* end for loop on individuals i */
                   4911:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4912:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4913:         cptcode=modmaxcovj;
                   4914:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4915:         /*for (i=0; i<=cptcode; i++) {*/
                   4916:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4917:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4918:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4919:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4920:             if( j != -1){
                   4921:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4922:                                  covariate for which somebody answered excluding 
                   4923:                                  undefined. Usually 2: 0 and 1. */
                   4924:             }
                   4925:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4926:                                     covariate for which somebody answered including 
                   4927:                                     undefined. Usually 3: -1, 0 and 1. */
                   4928:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4929:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4930:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  4931:                        
1.242     brouard  4932:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4933:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4934:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4935:         /* modmincovj=3; modmaxcovj = 7; */
                   4936:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4937:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4938:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   4939:         /* nbcode[Tvar[j]][ij]=k; */
                   4940:         /* nbcode[Tvar[j]][1]=0; */
                   4941:         /* nbcode[Tvar[j]][2]=1; */
                   4942:         /* nbcode[Tvar[j]][3]=2; */
                   4943:         /* To be continued (not working yet). */
                   4944:         ij=0; /* ij is similar to i but can jump over null modalities */
                   4945:         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*/
                   4946:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4947:             break;
                   4948:           }
                   4949:           ij++;
                   4950:           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*/
                   4951:           cptcode = ij; /* New max modality for covar j */
                   4952:         } /* end of loop on modality i=-1 to 1 or more */
                   4953:         break;
                   4954:        case 1: /* Testing on varying covariate, could be simple and
                   4955:                * should look at waves or product of fixed *
                   4956:                * varying. No time to test -1, assuming 0 and 1 only */
                   4957:         ij=0;
                   4958:         for(i=0; i<=1;i++){
                   4959:           nbcode[Tvar[k]][++ij]=i;
                   4960:         }
                   4961:         break;
                   4962:        default:
                   4963:         break;
                   4964:        } /* end switch */
                   4965:      } /* end dummy test */
                   4966:     
                   4967:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4968:      /*        /\*recode from 0 *\/ */
                   4969:      /*                                     k is a modality. If we have model=V1+V1*sex  */
                   4970:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4971:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4972:      /*        } */
                   4973:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4974:      /*        if (ij > ncodemax[j]) { */
                   4975:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4976:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4977:      /*          break; */
                   4978:      /*        } */
                   4979:      /*   }  /\* end of loop on modality k *\/ */
                   4980:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4981:   
                   4982:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   4983:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   4984:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   4985:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4986:      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 */ 
                   4987:      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 */
                   4988:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   4989:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4990:   
                   4991:    ij=0;
                   4992:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4993:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4994:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4995:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4996:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4997:        /* If product not in single variable we don't print results */
                   4998:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4999:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5000:        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*/
                   5001:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5002:        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 */
                   5003:        if(Fixed[k]!=0)
                   5004:         anyvaryingduminmodel=1;
                   5005:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5006:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5007:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5008:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5009:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5010:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5011:      } 
                   5012:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5013:    /* ij--; */
                   5014:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5015:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5016:                * because they can be excluded from the model and real
                   5017:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5018:    for(j=ij+1; j<= cptcovt; j++){
                   5019:      Tvaraff[j]=0;
                   5020:      Tmodelind[j]=0;
                   5021:    }
                   5022:    for(j=ntveff+1; j<= cptcovt; j++){
                   5023:      TmodelInvind[j]=0;
                   5024:    }
                   5025:    /* To be sorted */
                   5026:    ;
                   5027:  }
1.126     brouard  5028: 
1.145     brouard  5029: 
1.126     brouard  5030: /*********** Health Expectancies ****************/
                   5031: 
1.235     brouard  5032:  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  5033: 
                   5034: {
                   5035:   /* Health expectancies, no variances */
1.164     brouard  5036:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5037:   int nhstepma, nstepma; /* Decreasing with age */
                   5038:   double age, agelim, hf;
                   5039:   double ***p3mat;
                   5040:   double eip;
                   5041: 
1.238     brouard  5042:   /* pstamp(ficreseij); */
1.126     brouard  5043:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5044:   fprintf(ficreseij,"# Age");
                   5045:   for(i=1; i<=nlstate;i++){
                   5046:     for(j=1; j<=nlstate;j++){
                   5047:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5048:     }
                   5049:     fprintf(ficreseij," e%1d. ",i);
                   5050:   }
                   5051:   fprintf(ficreseij,"\n");
                   5052: 
                   5053:   
                   5054:   if(estepm < stepm){
                   5055:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5056:   }
                   5057:   else  hstepm=estepm;   
                   5058:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5059:    * This is mainly to measure the difference between two models: for example
                   5060:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5061:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5062:    * progression in between and thus overestimating or underestimating according
                   5063:    * to the curvature of the survival function. If, for the same date, we 
                   5064:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5065:    * to compare the new estimate of Life expectancy with the same linear 
                   5066:    * hypothesis. A more precise result, taking into account a more precise
                   5067:    * curvature will be obtained if estepm is as small as stepm. */
                   5068: 
                   5069:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5070:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5071:      nhstepm is the number of hstepm from age to agelim 
                   5072:      nstepm is the number of stepm from age to agelin. 
                   5073:      Look at hpijx to understand the reason of that which relies in memory size
                   5074:      and note for a fixed period like estepm months */
                   5075:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5076:      survival function given by stepm (the optimization length). Unfortunately it
                   5077:      means that if the survival funtion is printed only each two years of age and if
                   5078:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5079:      results. So we changed our mind and took the option of the best precision.
                   5080:   */
                   5081:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5082: 
                   5083:   agelim=AGESUP;
                   5084:   /* If stepm=6 months */
                   5085:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5086:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5087:     
                   5088: /* nhstepm age range expressed in number of stepm */
                   5089:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5090:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5091:   /* if (stepm >= YEARM) hstepm=1;*/
                   5092:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5093:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5094: 
                   5095:   for (age=bage; age<=fage; age ++){ 
                   5096:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5097:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5098:     /* if (stepm >= YEARM) hstepm=1;*/
                   5099:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5100: 
                   5101:     /* If stepm=6 months */
                   5102:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5103:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5104:     
1.235     brouard  5105:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5106:     
                   5107:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5108:     
                   5109:     printf("%d|",(int)age);fflush(stdout);
                   5110:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5111:     
                   5112:     /* Computing expectancies */
                   5113:     for(i=1; i<=nlstate;i++)
                   5114:       for(j=1; j<=nlstate;j++)
                   5115:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5116:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5117:          
                   5118:          /* 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]);*/
                   5119: 
                   5120:        }
                   5121: 
                   5122:     fprintf(ficreseij,"%3.0f",age );
                   5123:     for(i=1; i<=nlstate;i++){
                   5124:       eip=0;
                   5125:       for(j=1; j<=nlstate;j++){
                   5126:        eip +=eij[i][j][(int)age];
                   5127:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5128:       }
                   5129:       fprintf(ficreseij,"%9.4f", eip );
                   5130:     }
                   5131:     fprintf(ficreseij,"\n");
                   5132:     
                   5133:   }
                   5134:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5135:   printf("\n");
                   5136:   fprintf(ficlog,"\n");
                   5137:   
                   5138: }
                   5139: 
1.235     brouard  5140:  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  5141: 
                   5142: {
                   5143:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5144:      to initial status i, ei. .
1.126     brouard  5145:   */
                   5146:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5147:   int nhstepma, nstepma; /* Decreasing with age */
                   5148:   double age, agelim, hf;
                   5149:   double ***p3matp, ***p3matm, ***varhe;
                   5150:   double **dnewm,**doldm;
                   5151:   double *xp, *xm;
                   5152:   double **gp, **gm;
                   5153:   double ***gradg, ***trgradg;
                   5154:   int theta;
                   5155: 
                   5156:   double eip, vip;
                   5157: 
                   5158:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5159:   xp=vector(1,npar);
                   5160:   xm=vector(1,npar);
                   5161:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5162:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5163:   
                   5164:   pstamp(ficresstdeij);
                   5165:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5166:   fprintf(ficresstdeij,"# Age");
                   5167:   for(i=1; i<=nlstate;i++){
                   5168:     for(j=1; j<=nlstate;j++)
                   5169:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5170:     fprintf(ficresstdeij," e%1d. ",i);
                   5171:   }
                   5172:   fprintf(ficresstdeij,"\n");
                   5173: 
                   5174:   pstamp(ficrescveij);
                   5175:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5176:   fprintf(ficrescveij,"# Age");
                   5177:   for(i=1; i<=nlstate;i++)
                   5178:     for(j=1; j<=nlstate;j++){
                   5179:       cptj= (j-1)*nlstate+i;
                   5180:       for(i2=1; i2<=nlstate;i2++)
                   5181:        for(j2=1; j2<=nlstate;j2++){
                   5182:          cptj2= (j2-1)*nlstate+i2;
                   5183:          if(cptj2 <= cptj)
                   5184:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5185:        }
                   5186:     }
                   5187:   fprintf(ficrescveij,"\n");
                   5188:   
                   5189:   if(estepm < stepm){
                   5190:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5191:   }
                   5192:   else  hstepm=estepm;   
                   5193:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5194:    * This is mainly to measure the difference between two models: for example
                   5195:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5196:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5197:    * progression in between and thus overestimating or underestimating according
                   5198:    * to the curvature of the survival function. If, for the same date, we 
                   5199:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5200:    * to compare the new estimate of Life expectancy with the same linear 
                   5201:    * hypothesis. A more precise result, taking into account a more precise
                   5202:    * curvature will be obtained if estepm is as small as stepm. */
                   5203: 
                   5204:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5205:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5206:      nhstepm is the number of hstepm from age to agelim 
                   5207:      nstepm is the number of stepm from age to agelin. 
                   5208:      Look at hpijx to understand the reason of that which relies in memory size
                   5209:      and note for a fixed period like estepm months */
                   5210:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5211:      survival function given by stepm (the optimization length). Unfortunately it
                   5212:      means that if the survival funtion is printed only each two years of age and if
                   5213:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5214:      results. So we changed our mind and took the option of the best precision.
                   5215:   */
                   5216:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5217: 
                   5218:   /* If stepm=6 months */
                   5219:   /* nhstepm age range expressed in number of stepm */
                   5220:   agelim=AGESUP;
                   5221:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5222:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5223:   /* if (stepm >= YEARM) hstepm=1;*/
                   5224:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5225:   
                   5226:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5227:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5228:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5229:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5230:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5231:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5232: 
                   5233:   for (age=bage; age<=fage; age ++){ 
                   5234:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5235:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5236:     /* if (stepm >= YEARM) hstepm=1;*/
                   5237:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5238:                
1.126     brouard  5239:     /* If stepm=6 months */
                   5240:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5241:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5242:     
                   5243:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5244:                
1.126     brouard  5245:     /* Computing  Variances of health expectancies */
                   5246:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5247:        decrease memory allocation */
                   5248:     for(theta=1; theta <=npar; theta++){
                   5249:       for(i=1; i<=npar; i++){ 
1.222     brouard  5250:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5251:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5252:       }
1.235     brouard  5253:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5254:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5255:                        
1.126     brouard  5256:       for(j=1; j<= nlstate; j++){
1.222     brouard  5257:        for(i=1; i<=nlstate; i++){
                   5258:          for(h=0; h<=nhstepm-1; h++){
                   5259:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5260:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5261:          }
                   5262:        }
1.126     brouard  5263:       }
1.218     brouard  5264:                        
1.126     brouard  5265:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5266:        for(h=0; h<=nhstepm-1; h++){
                   5267:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5268:        }
1.126     brouard  5269:     }/* End theta */
                   5270:     
                   5271:     
                   5272:     for(h=0; h<=nhstepm-1; h++)
                   5273:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5274:        for(theta=1; theta <=npar; theta++)
                   5275:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5276:     
1.218     brouard  5277:                
1.222     brouard  5278:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5279:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5280:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5281:                
1.222     brouard  5282:     printf("%d|",(int)age);fflush(stdout);
                   5283:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5284:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5285:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5286:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5287:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5288:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5289:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5290:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5291:       }
                   5292:     }
1.218     brouard  5293:                
1.126     brouard  5294:     /* Computing expectancies */
1.235     brouard  5295:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5296:     for(i=1; i<=nlstate;i++)
                   5297:       for(j=1; j<=nlstate;j++)
1.222     brouard  5298:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5299:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5300:                                        
1.222     brouard  5301:          /* 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  5302:                                        
1.222     brouard  5303:        }
1.218     brouard  5304:                
1.126     brouard  5305:     fprintf(ficresstdeij,"%3.0f",age );
                   5306:     for(i=1; i<=nlstate;i++){
                   5307:       eip=0.;
                   5308:       vip=0.;
                   5309:       for(j=1; j<=nlstate;j++){
1.222     brouard  5310:        eip += eij[i][j][(int)age];
                   5311:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5312:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5313:        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  5314:       }
                   5315:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5316:     }
                   5317:     fprintf(ficresstdeij,"\n");
1.218     brouard  5318:                
1.126     brouard  5319:     fprintf(ficrescveij,"%3.0f",age );
                   5320:     for(i=1; i<=nlstate;i++)
                   5321:       for(j=1; j<=nlstate;j++){
1.222     brouard  5322:        cptj= (j-1)*nlstate+i;
                   5323:        for(i2=1; i2<=nlstate;i2++)
                   5324:          for(j2=1; j2<=nlstate;j2++){
                   5325:            cptj2= (j2-1)*nlstate+i2;
                   5326:            if(cptj2 <= cptj)
                   5327:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5328:          }
1.126     brouard  5329:       }
                   5330:     fprintf(ficrescveij,"\n");
1.218     brouard  5331:                
1.126     brouard  5332:   }
                   5333:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5334:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5335:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5336:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5337:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5338:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5339:   printf("\n");
                   5340:   fprintf(ficlog,"\n");
1.218     brouard  5341:        
1.126     brouard  5342:   free_vector(xm,1,npar);
                   5343:   free_vector(xp,1,npar);
                   5344:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5345:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5346:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5347: }
1.218     brouard  5348:  
1.126     brouard  5349: /************ Variance ******************/
1.235     brouard  5350:  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  5351:  {
                   5352:    /* Variance of health expectancies */
                   5353:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5354:    /* double **newm;*/
                   5355:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5356:   
                   5357:    /* int movingaverage(); */
                   5358:    double **dnewm,**doldm;
                   5359:    double **dnewmp,**doldmp;
                   5360:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5361:    int k;
                   5362:    double *xp;
                   5363:    double **gp, **gm;  /* for var eij */
                   5364:    double ***gradg, ***trgradg; /*for var eij */
                   5365:    double **gradgp, **trgradgp; /* for var p point j */
                   5366:    double *gpp, *gmp; /* for var p point j */
                   5367:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5368:    double ***p3mat;
                   5369:    double age,agelim, hf;
                   5370:    /* double ***mobaverage; */
                   5371:    int theta;
                   5372:    char digit[4];
                   5373:    char digitp[25];
                   5374: 
                   5375:    char fileresprobmorprev[FILENAMELENGTH];
                   5376: 
                   5377:    if(popbased==1){
                   5378:      if(mobilav!=0)
                   5379:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5380:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5381:    }
                   5382:    else 
                   5383:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5384: 
1.218     brouard  5385:    /* if (mobilav!=0) { */
                   5386:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5387:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5388:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5389:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5390:    /*   } */
                   5391:    /* } */
                   5392: 
                   5393:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5394:    sprintf(digit,"%-d",ij);
                   5395:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5396:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5397:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5398:    strcat(fileresprobmorprev,fileresu);
                   5399:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5400:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5401:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5402:    }
                   5403:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5404:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5405:    pstamp(ficresprobmorprev);
                   5406:    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  5407:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5408:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5409:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5410:    }
                   5411:    for(j=1;j<=cptcoveff;j++) 
                   5412:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5413:    fprintf(ficresprobmorprev,"\n");
                   5414: 
1.218     brouard  5415:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5416:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5417:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5418:      for(i=1; i<=nlstate;i++)
                   5419:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5420:    }  
                   5421:    fprintf(ficresprobmorprev,"\n");
                   5422:   
                   5423:    fprintf(ficgp,"\n# Routine varevsij");
                   5424:    fprintf(ficgp,"\nunset title \n");
                   5425:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5426:    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");
                   5427:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5428:    /*   } */
                   5429:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5430:    pstamp(ficresvij);
                   5431:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5432:    if(popbased==1)
                   5433:      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);
                   5434:    else
                   5435:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5436:    fprintf(ficresvij,"# Age");
                   5437:    for(i=1; i<=nlstate;i++)
                   5438:      for(j=1; j<=nlstate;j++)
                   5439:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5440:    fprintf(ficresvij,"\n");
                   5441: 
                   5442:    xp=vector(1,npar);
                   5443:    dnewm=matrix(1,nlstate,1,npar);
                   5444:    doldm=matrix(1,nlstate,1,nlstate);
                   5445:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5446:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5447: 
                   5448:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5449:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5450:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5451:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5452:   
1.218     brouard  5453:    if(estepm < stepm){
                   5454:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5455:    }
                   5456:    else  hstepm=estepm;   
                   5457:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5458:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5459:       nhstepm is the number of hstepm from age to agelim 
                   5460:       nstepm is the number of stepm from age to agelim. 
                   5461:       Look at function hpijx to understand why because of memory size limitations, 
                   5462:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5463:       survival function given by stepm (the optimization length). Unfortunately it
                   5464:       means that if the survival funtion is printed every two years of age and if
                   5465:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5466:       results. So we changed our mind and took the option of the best precision.
                   5467:    */
                   5468:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5469:    agelim = AGESUP;
                   5470:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5471:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5472:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5473:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5474:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5475:      gp=matrix(0,nhstepm,1,nlstate);
                   5476:      gm=matrix(0,nhstepm,1,nlstate);
                   5477:                
                   5478:                
                   5479:      for(theta=1; theta <=npar; theta++){
                   5480:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5481:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5482:        }
                   5483:                        
1.242     brouard  5484:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5485:                        
                   5486:        if (popbased==1) {
                   5487:         if(mobilav ==0){
                   5488:           for(i=1; i<=nlstate;i++)
                   5489:             prlim[i][i]=probs[(int)age][i][ij];
                   5490:         }else{ /* mobilav */ 
                   5491:           for(i=1; i<=nlstate;i++)
                   5492:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5493:         }
                   5494:        }
                   5495:                        
1.235     brouard  5496:        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  5497:        for(j=1; j<= nlstate; j++){
                   5498:         for(h=0; h<=nhstepm; h++){
                   5499:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5500:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5501:         }
                   5502:        }
                   5503:        /* Next for computing probability of death (h=1 means
                   5504:          computed over hstepm matrices product = hstepm*stepm months) 
                   5505:          as a weighted average of prlim.
                   5506:        */
                   5507:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5508:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5509:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5510:        }    
                   5511:        /* end probability of death */
                   5512:                        
                   5513:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5514:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5515:                        
1.242     brouard  5516:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5517:                        
                   5518:        if (popbased==1) {
                   5519:         if(mobilav ==0){
                   5520:           for(i=1; i<=nlstate;i++)
                   5521:             prlim[i][i]=probs[(int)age][i][ij];
                   5522:         }else{ /* mobilav */ 
                   5523:           for(i=1; i<=nlstate;i++)
                   5524:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5525:         }
                   5526:        }
                   5527:                        
1.235     brouard  5528:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5529:                        
                   5530:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5531:         for(h=0; h<=nhstepm; h++){
                   5532:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5533:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5534:         }
                   5535:        }
                   5536:        /* This for computing probability of death (h=1 means
                   5537:          computed over hstepm matrices product = hstepm*stepm months) 
                   5538:          as a weighted average of prlim.
                   5539:        */
                   5540:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5541:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5542:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5543:        }    
                   5544:        /* end probability of death */
                   5545:                        
                   5546:        for(j=1; j<= nlstate; j++) /* vareij */
                   5547:         for(h=0; h<=nhstepm; h++){
                   5548:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5549:         }
                   5550:                        
                   5551:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5552:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5553:        }
                   5554:                        
                   5555:      } /* End theta */
                   5556:                
                   5557:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5558:                
                   5559:      for(h=0; h<=nhstepm; h++) /* veij */
                   5560:        for(j=1; j<=nlstate;j++)
                   5561:         for(theta=1; theta <=npar; theta++)
                   5562:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5563:                
                   5564:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5565:        for(theta=1; theta <=npar; theta++)
                   5566:         trgradgp[j][theta]=gradgp[theta][j];
                   5567:                
                   5568:                
                   5569:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5570:      for(i=1;i<=nlstate;i++)
                   5571:        for(j=1;j<=nlstate;j++)
                   5572:         vareij[i][j][(int)age] =0.;
                   5573:                
                   5574:      for(h=0;h<=nhstepm;h++){
                   5575:        for(k=0;k<=nhstepm;k++){
                   5576:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5577:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5578:         for(i=1;i<=nlstate;i++)
                   5579:           for(j=1;j<=nlstate;j++)
                   5580:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5581:        }
                   5582:      }
                   5583:                
                   5584:      /* pptj */
                   5585:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5586:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5587:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5588:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5589:         varppt[j][i]=doldmp[j][i];
                   5590:      /* end ppptj */
                   5591:      /*  x centered again */
                   5592:                
1.242     brouard  5593:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5594:                
                   5595:      if (popbased==1) {
                   5596:        if(mobilav ==0){
                   5597:         for(i=1; i<=nlstate;i++)
                   5598:           prlim[i][i]=probs[(int)age][i][ij];
                   5599:        }else{ /* mobilav */ 
                   5600:         for(i=1; i<=nlstate;i++)
                   5601:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5602:        }
                   5603:      }
                   5604:                
                   5605:      /* This for computing probability of death (h=1 means
                   5606:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5607:        as a weighted average of prlim.
                   5608:      */
1.235     brouard  5609:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5610:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5611:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5612:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5613:      }    
                   5614:      /* end probability of death */
                   5615:                
                   5616:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5617:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5618:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5619:        for(i=1; i<=nlstate;i++){
                   5620:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5621:        }
                   5622:      } 
                   5623:      fprintf(ficresprobmorprev,"\n");
                   5624:                
                   5625:      fprintf(ficresvij,"%.0f ",age );
                   5626:      for(i=1; i<=nlstate;i++)
                   5627:        for(j=1; j<=nlstate;j++){
                   5628:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5629:        }
                   5630:      fprintf(ficresvij,"\n");
                   5631:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5632:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5633:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5634:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5635:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5636:    } /* End age */
                   5637:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5638:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5639:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5640:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5641:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5642:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5643:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5644:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5645:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5646:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5647:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5648:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5649:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5650:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5651:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5652:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5653:    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);
                   5654:    /*  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  5655:     */
1.218     brouard  5656:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5657:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5658: 
1.218     brouard  5659:    free_vector(xp,1,npar);
                   5660:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5661:    free_matrix(dnewm,1,nlstate,1,npar);
                   5662:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5663:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5664:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5665:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5666:    fclose(ficresprobmorprev);
                   5667:    fflush(ficgp);
                   5668:    fflush(fichtm); 
                   5669:  }  /* end varevsij */
1.126     brouard  5670: 
                   5671: /************ Variance of prevlim ******************/
1.235     brouard  5672:  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  5673: {
1.205     brouard  5674:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5675:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5676: 
1.126     brouard  5677:   double **dnewm,**doldm;
                   5678:   int i, j, nhstepm, hstepm;
                   5679:   double *xp;
                   5680:   double *gp, *gm;
                   5681:   double **gradg, **trgradg;
1.208     brouard  5682:   double **mgm, **mgp;
1.126     brouard  5683:   double age,agelim;
                   5684:   int theta;
                   5685:   
                   5686:   pstamp(ficresvpl);
                   5687:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5688:   fprintf(ficresvpl,"# Age ");
                   5689:   if(nresult >=1)
                   5690:     fprintf(ficresvpl," Result# ");
1.126     brouard  5691:   for(i=1; i<=nlstate;i++)
                   5692:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5693:   fprintf(ficresvpl,"\n");
                   5694: 
                   5695:   xp=vector(1,npar);
                   5696:   dnewm=matrix(1,nlstate,1,npar);
                   5697:   doldm=matrix(1,nlstate,1,nlstate);
                   5698:   
                   5699:   hstepm=1*YEARM; /* Every year of age */
                   5700:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5701:   agelim = AGESUP;
                   5702:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5703:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5704:     if (stepm >= YEARM) hstepm=1;
                   5705:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5706:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5707:     mgp=matrix(1,npar,1,nlstate);
                   5708:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5709:     gp=vector(1,nlstate);
                   5710:     gm=vector(1,nlstate);
                   5711: 
                   5712:     for(theta=1; theta <=npar; theta++){
                   5713:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5714:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5715:       }
1.209     brouard  5716:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5717:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5718:       else
1.235     brouard  5719:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5720:       for(i=1;i<=nlstate;i++){
1.126     brouard  5721:        gp[i] = prlim[i][i];
1.208     brouard  5722:        mgp[theta][i] = prlim[i][i];
                   5723:       }
1.126     brouard  5724:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5725:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5726:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5727:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5728:       else
1.235     brouard  5729:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5730:       for(i=1;i<=nlstate;i++){
1.126     brouard  5731:        gm[i] = prlim[i][i];
1.208     brouard  5732:        mgm[theta][i] = prlim[i][i];
                   5733:       }
1.126     brouard  5734:       for(i=1;i<=nlstate;i++)
                   5735:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5736:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5737:     } /* End theta */
                   5738: 
                   5739:     trgradg =matrix(1,nlstate,1,npar);
                   5740: 
                   5741:     for(j=1; j<=nlstate;j++)
                   5742:       for(theta=1; theta <=npar; theta++)
                   5743:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5744:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5745:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5746:     /*   for(j=1; j<=nlstate;j++){ */
                   5747:     /*         printf(" %d ",j); */
                   5748:     /*         for(theta=1; theta <=npar; theta++) */
                   5749:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5750:     /*         printf("\n "); */
                   5751:     /*   } */
                   5752:     /* } */
                   5753:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5754:     /*   printf("\n gradg %d ",(int)age); */
                   5755:     /*   for(j=1; j<=nlstate;j++){ */
                   5756:     /*         printf("%d ",j); */
                   5757:     /*         for(theta=1; theta <=npar; theta++) */
                   5758:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5759:     /*         printf("\n "); */
                   5760:     /*   } */
                   5761:     /* } */
1.126     brouard  5762: 
                   5763:     for(i=1;i<=nlstate;i++)
                   5764:       varpl[i][(int)age] =0.;
1.209     brouard  5765:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5766:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5767:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5768:     }else{
1.126     brouard  5769:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5770:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5771:     }
1.126     brouard  5772:     for(i=1;i<=nlstate;i++)
                   5773:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5774: 
                   5775:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  5776:     if(nresult >=1)
                   5777:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  5778:     for(i=1; i<=nlstate;i++)
                   5779:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5780:     fprintf(ficresvpl,"\n");
                   5781:     free_vector(gp,1,nlstate);
                   5782:     free_vector(gm,1,nlstate);
1.208     brouard  5783:     free_matrix(mgm,1,npar,1,nlstate);
                   5784:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5785:     free_matrix(gradg,1,npar,1,nlstate);
                   5786:     free_matrix(trgradg,1,nlstate,1,npar);
                   5787:   } /* End age */
                   5788: 
                   5789:   free_vector(xp,1,npar);
                   5790:   free_matrix(doldm,1,nlstate,1,npar);
                   5791:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5792: 
                   5793: }
                   5794: 
                   5795: /************ Variance of one-step probabilities  ******************/
                   5796: 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  5797:  {
                   5798:    int i, j=0,  k1, l1, tj;
                   5799:    int k2, l2, j1,  z1;
                   5800:    int k=0, l;
                   5801:    int first=1, first1, first2;
                   5802:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5803:    double **dnewm,**doldm;
                   5804:    double *xp;
                   5805:    double *gp, *gm;
                   5806:    double **gradg, **trgradg;
                   5807:    double **mu;
                   5808:    double age, cov[NCOVMAX+1];
                   5809:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5810:    int theta;
                   5811:    char fileresprob[FILENAMELENGTH];
                   5812:    char fileresprobcov[FILENAMELENGTH];
                   5813:    char fileresprobcor[FILENAMELENGTH];
                   5814:    double ***varpij;
                   5815: 
                   5816:    strcpy(fileresprob,"PROB_"); 
                   5817:    strcat(fileresprob,fileres);
                   5818:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5819:      printf("Problem with resultfile: %s\n", fileresprob);
                   5820:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5821:    }
                   5822:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5823:    strcat(fileresprobcov,fileresu);
                   5824:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5825:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5826:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5827:    }
                   5828:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5829:    strcat(fileresprobcor,fileresu);
                   5830:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5831:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5832:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5833:    }
                   5834:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5835:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5836:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5837:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5838:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5839:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5840:    pstamp(ficresprob);
                   5841:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5842:    fprintf(ficresprob,"# Age");
                   5843:    pstamp(ficresprobcov);
                   5844:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5845:    fprintf(ficresprobcov,"# Age");
                   5846:    pstamp(ficresprobcor);
                   5847:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5848:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5849: 
                   5850: 
1.222     brouard  5851:    for(i=1; i<=nlstate;i++)
                   5852:      for(j=1; j<=(nlstate+ndeath);j++){
                   5853:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5854:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5855:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5856:      }  
                   5857:    /* fprintf(ficresprob,"\n");
                   5858:       fprintf(ficresprobcov,"\n");
                   5859:       fprintf(ficresprobcor,"\n");
                   5860:    */
                   5861:    xp=vector(1,npar);
                   5862:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5863:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5864:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5865:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5866:    first=1;
                   5867:    fprintf(ficgp,"\n# Routine varprob");
                   5868:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5869:    fprintf(fichtm,"\n");
                   5870: 
                   5871:    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);
                   5872:    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);
                   5873:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5874: and drawn. It helps understanding how is the covariance between two incidences.\
                   5875:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5876:    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  5877: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5878: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5879: standard deviations wide on each axis. <br>\
                   5880:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5881:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5882: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5883: 
1.222     brouard  5884:    cov[1]=1;
                   5885:    /* tj=cptcoveff; */
1.225     brouard  5886:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5887:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5888:    j1=0;
1.224     brouard  5889:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5890:      if  (cptcovn>0) {
                   5891:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5892:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5893:        fprintf(ficresprob, "**********\n#\n");
                   5894:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5895:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5896:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5897:                        
1.222     brouard  5898:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5899:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5900:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5901:                        
                   5902:                        
1.222     brouard  5903:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5904:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5905:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5906:                        
1.222     brouard  5907:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5908:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5909:        fprintf(ficresprobcor, "**********\n#");    
                   5910:        if(invalidvarcomb[j1]){
                   5911:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5912:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5913:         continue;
                   5914:        }
                   5915:      }
                   5916:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5917:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5918:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5919:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5920:      for (age=bage; age<=fage; age ++){ 
                   5921:        cov[2]=age;
                   5922:        if(nagesqr==1)
                   5923:         cov[3]= age*age;
                   5924:        for (k=1; k<=cptcovn;k++) {
                   5925:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5926:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5927:                                                                    * 1  1 1 1 1
                   5928:                                                                    * 2  2 1 1 1
                   5929:                                                                    * 3  1 2 1 1
                   5930:                                                                    */
                   5931:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5932:        }
                   5933:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5934:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5935:        for (k=1; k<=cptcovprod;k++)
                   5936:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5937:                        
                   5938:                        
1.222     brouard  5939:        for(theta=1; theta <=npar; theta++){
                   5940:         for(i=1; i<=npar; i++)
                   5941:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5942:                                
1.222     brouard  5943:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5944:                                
1.222     brouard  5945:         k=0;
                   5946:         for(i=1; i<= (nlstate); i++){
                   5947:           for(j=1; j<=(nlstate+ndeath);j++){
                   5948:             k=k+1;
                   5949:             gp[k]=pmmij[i][j];
                   5950:           }
                   5951:         }
1.220     brouard  5952:                                
1.222     brouard  5953:         for(i=1; i<=npar; i++)
                   5954:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5955:                                
1.222     brouard  5956:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5957:         k=0;
                   5958:         for(i=1; i<=(nlstate); i++){
                   5959:           for(j=1; j<=(nlstate+ndeath);j++){
                   5960:             k=k+1;
                   5961:             gm[k]=pmmij[i][j];
                   5962:           }
                   5963:         }
1.220     brouard  5964:                                
1.222     brouard  5965:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5966:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5967:        }
1.126     brouard  5968: 
1.222     brouard  5969:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5970:         for(theta=1; theta <=npar; theta++)
                   5971:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5972:                        
1.222     brouard  5973:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5974:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5975:                        
1.222     brouard  5976:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5977:                        
1.222     brouard  5978:        k=0;
                   5979:        for(i=1; i<=(nlstate); i++){
                   5980:         for(j=1; j<=(nlstate+ndeath);j++){
                   5981:           k=k+1;
                   5982:           mu[k][(int) age]=pmmij[i][j];
                   5983:         }
                   5984:        }
                   5985:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5986:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5987:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5988:                        
1.222     brouard  5989:        /*printf("\n%d ",(int)age);
                   5990:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5991:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5992:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5993:         }*/
1.220     brouard  5994:                        
1.222     brouard  5995:        fprintf(ficresprob,"\n%d ",(int)age);
                   5996:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5997:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5998:                        
1.222     brouard  5999:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6000:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6001:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6002:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6003:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6004:        }
                   6005:        i=0;
                   6006:        for (k=1; k<=(nlstate);k++){
                   6007:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6008:           i++;
                   6009:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6010:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6011:           for (j=1; j<=i;j++){
                   6012:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6013:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6014:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6015:           }
                   6016:         }
                   6017:        }/* end of loop for state */
                   6018:      } /* end of loop for age */
                   6019:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6020:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6021:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6022:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6023:     
                   6024:      /* Confidence intervalle of pij  */
                   6025:      /*
                   6026:        fprintf(ficgp,"\nunset parametric;unset label");
                   6027:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6028:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6029:        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);
                   6030:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6031:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6032:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6033:      */
                   6034:                
                   6035:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6036:      first1=1;first2=2;
                   6037:      for (k2=1; k2<=(nlstate);k2++){
                   6038:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6039:         if(l2==k2) continue;
                   6040:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6041:         for (k1=1; k1<=(nlstate);k1++){
                   6042:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6043:             if(l1==k1) continue;
                   6044:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6045:             if(i<=j) continue;
                   6046:             for (age=bage; age<=fage; age ++){ 
                   6047:               if ((int)age %5==0){
                   6048:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6049:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6050:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6051:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6052:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6053:                 c12=cv12/sqrt(v1*v2);
                   6054:                 /* Computing eigen value of matrix of covariance */
                   6055:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6056:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6057:                 if ((lc2 <0) || (lc1 <0) ){
                   6058:                   if(first2==1){
                   6059:                     first1=0;
                   6060:                     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);
                   6061:                   }
                   6062:                   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);
                   6063:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6064:                   /* lc2=fabs(lc2); */
                   6065:                 }
1.220     brouard  6066:                                                                
1.222     brouard  6067:                 /* Eigen vectors */
                   6068:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6069:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6070:                 v21=(lc1-v1)/cv12*v11;
                   6071:                 v12=-v21;
                   6072:                 v22=v11;
                   6073:                 tnalp=v21/v11;
                   6074:                 if(first1==1){
                   6075:                   first1=0;
                   6076:                   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);
                   6077:                 }
                   6078:                 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);
                   6079:                 /*printf(fignu*/
                   6080:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6081:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6082:                 if(first==1){
                   6083:                   first=0;
                   6084:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6085:                   fprintf(ficgp,"\nset parametric;unset label");
                   6086:                   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);
                   6087:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6088:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6089:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6090: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6091:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6092:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6093:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6094:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6095:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6096:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6097:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6098:                   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",      \
                   6099:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6100:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6101:                 }else{
                   6102:                   first=0;
                   6103:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6104:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6105:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6106:                   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", \
                   6107:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6108:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6109:                 }/* if first */
                   6110:               } /* age mod 5 */
                   6111:             } /* end loop age */
                   6112:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6113:             first=1;
                   6114:           } /*l12 */
                   6115:         } /* k12 */
                   6116:        } /*l1 */
                   6117:      }/* k1 */
                   6118:    }  /* loop on combination of covariates j1 */
                   6119:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6120:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6121:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6122:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6123:    free_vector(xp,1,npar);
                   6124:    fclose(ficresprob);
                   6125:    fclose(ficresprobcov);
                   6126:    fclose(ficresprobcor);
                   6127:    fflush(ficgp);
                   6128:    fflush(fichtmcov);
                   6129:  }
1.126     brouard  6130: 
                   6131: 
                   6132: /******************* Printing html file ***********/
1.201     brouard  6133: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6134:                  int lastpass, int stepm, int weightopt, char model[],\
                   6135:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6136:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6137:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6138:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6139:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6140: 
                   6141:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6142:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6143: </ul>");
1.237     brouard  6144:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6145: </ul>", model);
1.214     brouard  6146:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6147:    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",
                   6148:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6149:    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  6150:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6151:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6152:    fprintf(fichtm,"\
                   6153:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6154:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6155:    fprintf(fichtm,"\
1.217     brouard  6156:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6157:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6158:    fprintf(fichtm,"\
1.126     brouard  6159:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6160:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6161:    fprintf(fichtm,"\
1.217     brouard  6162:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6163:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6164:    fprintf(fichtm,"\
1.211     brouard  6165:  - (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  6166:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6167:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6168:    if(prevfcast==1){
                   6169:      fprintf(fichtm,"\
                   6170:  - Prevalence projections by age and states:                           \
1.201     brouard  6171:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6172:    }
1.126     brouard  6173: 
1.222     brouard  6174:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6175: 
1.225     brouard  6176:    m=pow(2,cptcoveff);
1.222     brouard  6177:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6178: 
1.222     brouard  6179:    jj1=0;
1.237     brouard  6180: 
                   6181:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6182:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.237     brouard  6183:      if(TKresult[nres]!= k1)
                   6184:        continue;
1.220     brouard  6185: 
1.222     brouard  6186:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6187:      jj1++;
                   6188:      if (cptcovn > 0) {
                   6189:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6190:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6191:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6192:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6193:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6194:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6195:        }
1.237     brouard  6196:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6197:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6198:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6199:       }
                   6200:        
1.230     brouard  6201:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6202:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6203:        if(invalidvarcomb[k1]){
                   6204:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6205:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6206:         continue;
                   6207:        }
                   6208:      }
                   6209:      /* aij, bij */
1.241     brouard  6210:      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> \
                   6211: <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  6212:      /* Pij */
1.241     brouard  6213:      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> \
                   6214: <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  6215:      /* Quasi-incidences */
                   6216:      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  6217:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6218:  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  6219: 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> \
                   6220: <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  6221:      /* Survival functions (period) in state j */
                   6222:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6223:        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> \
                   6224: <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  6225:      }
                   6226:      /* State specific survival functions (period) */
                   6227:      for(cpt=1; cpt<=nlstate;cpt++){
                   6228:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6229:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6230:  <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  6231:      }
                   6232:      /* Period (stable) prevalence in each health state */
                   6233:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6234:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6235: <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  6236:      }
                   6237:      if(backcast==1){
                   6238:        /* Period (stable) back prevalence in each health state */
                   6239:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6240:         fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6241: <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  6242:        }
1.217     brouard  6243:      }
1.222     brouard  6244:      if(prevfcast==1){
                   6245:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6246:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6247:         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> \
                   6248: <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  6249:        }
                   6250:      }
1.220     brouard  6251:         
1.222     brouard  6252:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6253:        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> \
                   6254: <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  6255:      }
                   6256:      /* } /\* end i1 *\/ */
                   6257:    }/* End k1 */
                   6258:    fprintf(fichtm,"</ul>");
1.126     brouard  6259: 
1.222     brouard  6260:    fprintf(fichtm,"\
1.126     brouard  6261: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6262:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6263:  - 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  6264: But because parameters are usually highly correlated (a higher incidence of disability \
                   6265: and a higher incidence of recovery can give very close observed transition) it might \
                   6266: be very useful to look not only at linear confidence intervals estimated from the \
                   6267: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6268: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6269: covariance matrix of the one-step probabilities. \
                   6270: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6271: 
1.222     brouard  6272:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6273:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6274:    fprintf(fichtm,"\
1.126     brouard  6275:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6276:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6277: 
1.222     brouard  6278:    fprintf(fichtm,"\
1.126     brouard  6279:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6280:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6281:    fprintf(fichtm,"\
1.126     brouard  6282:  - 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): \
                   6283:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6284:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6285:    fprintf(fichtm,"\
1.126     brouard  6286:  - (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): \
                   6287:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6288:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6289:    fprintf(fichtm,"\
1.128     brouard  6290:  - 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  6291:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6292:    fprintf(fichtm,"\
1.128     brouard  6293:  - 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  6294:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6295:    fprintf(fichtm,"\
1.126     brouard  6296:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6297:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6298: 
                   6299: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6300: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6301: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6302: /*     <br>",fileres,fileres,fileres,fileres); */
                   6303: /*  else  */
                   6304: /*    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  6305:    fflush(fichtm);
                   6306:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6307: 
1.225     brouard  6308:    m=pow(2,cptcoveff);
1.222     brouard  6309:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6310: 
1.222     brouard  6311:    jj1=0;
1.237     brouard  6312: 
1.241     brouard  6313:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6314:    for(k1=1; k1<=m;k1++){
1.237     brouard  6315:      if(TKresult[nres]!= k1)
                   6316:        continue;
1.222     brouard  6317:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6318:      jj1++;
1.126     brouard  6319:      if (cptcovn > 0) {
                   6320:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6321:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6322:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6323:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6324:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6325:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6326:       }
                   6327: 
1.126     brouard  6328:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6329: 
1.222     brouard  6330:        if(invalidvarcomb[k1]){
                   6331:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6332:         continue;
                   6333:        }
1.126     brouard  6334:      }
                   6335:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6336:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
1.241     brouard  6337: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
                   6338: <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  6339:      }
                   6340:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6341: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6342: true period expectancies (those weighted with period prevalences are also\
                   6343:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6344:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6345: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6346:      /* } /\* end i1 *\/ */
                   6347:    }/* End k1 */
1.241     brouard  6348:   }/* End nres */
1.222     brouard  6349:    fprintf(fichtm,"</ul>");
                   6350:    fflush(fichtm);
1.126     brouard  6351: }
                   6352: 
                   6353: /******************* Gnuplot file **************/
1.223     brouard  6354: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6355: 
                   6356:   char dirfileres[132],optfileres[132];
1.223     brouard  6357:   char gplotcondition[132];
1.237     brouard  6358:   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  6359:   int lv=0, vlv=0, kl=0;
1.130     brouard  6360:   int ng=0;
1.201     brouard  6361:   int vpopbased;
1.223     brouard  6362:   int ioffset; /* variable offset for columns */
1.235     brouard  6363:   int nres=0; /* Index of resultline */
1.219     brouard  6364: 
1.126     brouard  6365: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6366: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6367: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6368: /*   } */
                   6369: 
                   6370:   /*#ifdef windows */
                   6371:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6372:   /*#endif */
1.225     brouard  6373:   m=pow(2,cptcoveff);
1.126     brouard  6374: 
1.202     brouard  6375:   /* Contribution to likelihood */
                   6376:   /* Plot the probability implied in the likelihood */
1.223     brouard  6377:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6378:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6379:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6380:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6381: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6382:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6383: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6384:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6385:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6386:   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));
                   6387:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6388:   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));
                   6389:   for (i=1; i<= nlstate ; i ++) {
                   6390:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6391:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6392:     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);
                   6393:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6394:       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);
                   6395:     }
                   6396:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6397:   }
                   6398:   /* 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 */               
                   6399:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6400:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6401:   fprintf(ficgp,"\nset out;unset log\n");
                   6402:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6403: 
1.126     brouard  6404:   strcpy(dirfileres,optionfilefiname);
                   6405:   strcpy(optfileres,"vpl");
1.223     brouard  6406:   /* 1eme*/
1.238     brouard  6407:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6408:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6409:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6410:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6411:        if(TKresult[nres]!= k1)
                   6412:          continue;
                   6413:        /* We are interested in selected combination by the resultline */
1.246     brouard  6414:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.238     brouard  6415:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6416:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6417:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6418:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6419:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6420:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6421:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6422:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  6423:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  6424:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6425:        }
                   6426:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  6427:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  6428:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6429:        }       
1.246     brouard  6430:        /* printf("\n#\n"); */
1.238     brouard  6431:        fprintf(ficgp,"\n#\n");
                   6432:        if(invalidvarcomb[k1]){
                   6433:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6434:          continue;
                   6435:        }
1.235     brouard  6436:       
1.241     brouard  6437:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6438:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   6439:        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  6440:       
1.238     brouard  6441:        for (i=1; i<= nlstate ; i ++) {
                   6442:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6443:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6444:        }
1.242     brouard  6445:        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  6446:        for (i=1; i<= nlstate ; i ++) {
                   6447:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6448:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6449:        } 
1.242     brouard  6450:        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  6451:        for (i=1; i<= nlstate ; i ++) {
                   6452:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6453:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6454:        }  
                   6455:        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));
                   6456:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6457:          /* 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  6458:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6459:          if(cptcoveff ==0){
1.245     brouard  6460:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  6461:          }else{
                   6462:            kl=0;
                   6463:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6464:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6465:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6466:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6467:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6468:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6469:              kl++;
1.238     brouard  6470:              /* 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 *\/ */
                   6471:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6472:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6473:              /* ''  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*/
                   6474:              if(k==cptcoveff){
1.245     brouard  6475:                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  6476:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6477:              }else{
                   6478:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6479:                kl++;
                   6480:              }
                   6481:            } /* end covariate */
                   6482:          } /* end if no covariate */
                   6483:        } /* end if backcast */
                   6484:        fprintf(ficgp,"\nset out \n");
                   6485:       } /* nres */
1.201     brouard  6486:     } /* k1 */
                   6487:   } /* cpt */
1.235     brouard  6488: 
                   6489:   
1.126     brouard  6490:   /*2 eme*/
1.238     brouard  6491:   for (k1=1; k1<= m ; k1 ++){  
                   6492:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6493:       if(TKresult[nres]!= k1)
                   6494:        continue;
                   6495:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6496:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6497:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6498:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6499:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6500:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6501:        vlv= nbcode[Tvaraff[k]][lv];
                   6502:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6503:       }
1.237     brouard  6504:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6505:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6506:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6507:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6508:       }
1.211     brouard  6509:       fprintf(ficgp,"\n#\n");
1.223     brouard  6510:       if(invalidvarcomb[k1]){
                   6511:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6512:        continue;
                   6513:       }
1.219     brouard  6514:                        
1.241     brouard  6515:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6516:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6517:        if(vpopbased==0)
                   6518:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6519:        else
                   6520:          fprintf(ficgp,"\nreplot ");
                   6521:        for (i=1; i<= nlstate+1 ; i ++) {
                   6522:          k=2*i;
                   6523:          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);
                   6524:          for (j=1; j<= nlstate+1 ; j ++) {
                   6525:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6526:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6527:          }   
                   6528:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6529:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6530:          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);
                   6531:          for (j=1; j<= nlstate+1 ; j ++) {
                   6532:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6533:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6534:          }   
                   6535:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6536:          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);
                   6537:          for (j=1; j<= nlstate+1 ; j ++) {
                   6538:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6539:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6540:          }   
                   6541:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6542:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6543:        } /* state */
                   6544:       } /* vpopbased */
1.244     brouard  6545:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  6546:     } /* end nres */
                   6547:   } /* k1 end 2 eme*/
                   6548:        
                   6549:        
                   6550:   /*3eme*/
                   6551:   for (k1=1; k1<= m ; k1 ++){
                   6552:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.240     brouard  6553:       if(TKresult[nres]!= k1)
1.238     brouard  6554:        continue;
                   6555: 
                   6556:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6557:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6558:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6559:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6560:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6561:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6562:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6563:          vlv= nbcode[Tvaraff[k]][lv];
                   6564:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6565:        }
                   6566:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6567:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6568:        }       
                   6569:        fprintf(ficgp,"\n#\n");
                   6570:        if(invalidvarcomb[k1]){
                   6571:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6572:          continue;
                   6573:        }
                   6574:                        
                   6575:        /*       k=2+nlstate*(2*cpt-2); */
                   6576:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6577:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6578:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6579: 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  6580:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6581:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6582:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6583:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6584:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6585:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6586:                                
1.238     brouard  6587:        */
                   6588:        for (i=1; i< nlstate ; i ++) {
                   6589:          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);
                   6590:          /*    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  6591:                                
1.238     brouard  6592:        } 
                   6593:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6594:       }
                   6595:     } /* end nres */
                   6596:   } /* end kl 3eme */
1.126     brouard  6597:   
1.223     brouard  6598:   /* 4eme */
1.201     brouard  6599:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6600:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6601:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6602:       if(TKresult[nres]!= k1)
1.223     brouard  6603:        continue;
1.238     brouard  6604:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6605:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6606:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6607:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6608:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6609:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6610:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6611:          vlv= nbcode[Tvaraff[k]][lv];
                   6612:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6613:        }
                   6614:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6615:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6616:        }       
                   6617:        fprintf(ficgp,"\n#\n");
                   6618:        if(invalidvarcomb[k1]){
                   6619:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6620:          continue;
1.223     brouard  6621:        }
1.238     brouard  6622:       
1.241     brouard  6623:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6624:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6625: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6626:        k=3;
                   6627:        for (i=1; i<= nlstate ; i ++){
                   6628:          if(i==1){
                   6629:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6630:          }else{
                   6631:            fprintf(ficgp,", '' ");
                   6632:          }
                   6633:          l=(nlstate+ndeath)*(i-1)+1;
                   6634:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6635:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6636:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6637:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6638:        } /* nlstate */
                   6639:        fprintf(ficgp,"\nset out\n");
                   6640:       } /* end cpt state*/ 
                   6641:     } /* end nres */
                   6642:   } /* end covariate k1 */  
                   6643: 
1.220     brouard  6644: /* 5eme */
1.201     brouard  6645:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6646:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6647:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6648:       if(TKresult[nres]!= k1)
1.227     brouard  6649:        continue;
1.238     brouard  6650:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6651:        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);
                   6652:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6653:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6654:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6655:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6656:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6657:          vlv= nbcode[Tvaraff[k]][lv];
                   6658:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6659:        }
                   6660:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6661:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6662:        }       
                   6663:        fprintf(ficgp,"\n#\n");
                   6664:        if(invalidvarcomb[k1]){
                   6665:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6666:          continue;
                   6667:        }
1.227     brouard  6668:       
1.241     brouard  6669:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6670:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6671: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6672:        k=3;
                   6673:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6674:          if(j==1)
                   6675:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6676:          else
                   6677:            fprintf(ficgp,", '' ");
                   6678:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6679:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6680:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6681:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6682:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6683:        } /* nlstate */
                   6684:        fprintf(ficgp,", '' ");
                   6685:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6686:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6687:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6688:          if(j < nlstate)
                   6689:            fprintf(ficgp,"$%d +",k+l);
                   6690:          else
                   6691:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6692:        }
                   6693:        fprintf(ficgp,"\nset out\n");
                   6694:       } /* end cpt state*/ 
                   6695:     } /* end covariate */  
                   6696:   } /* end nres */
1.227     brouard  6697:   
1.220     brouard  6698: /* 6eme */
1.202     brouard  6699:   /* CV preval stable (period) for each covariate */
1.237     brouard  6700:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6701:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6702:     if(TKresult[nres]!= k1)
                   6703:       continue;
1.153     brouard  6704:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6705:       
1.211     brouard  6706:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6707:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6708:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6709:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6710:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6711:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6712:        vlv= nbcode[Tvaraff[k]][lv];
                   6713:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6714:       }
1.237     brouard  6715:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6716:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6717:       }        
1.211     brouard  6718:       fprintf(ficgp,"\n#\n");
1.223     brouard  6719:       if(invalidvarcomb[k1]){
1.227     brouard  6720:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6721:        continue;
1.223     brouard  6722:       }
1.227     brouard  6723:       
1.241     brouard  6724:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6725:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6726: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6727:       k=3; /* Offset */
1.153     brouard  6728:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6729:        if(i==1)
                   6730:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6731:        else
                   6732:          fprintf(ficgp,", '' ");
                   6733:        l=(nlstate+ndeath)*(i-1)+1;
                   6734:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6735:        for (j=2; j<= nlstate ; j ++)
                   6736:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6737:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6738:       } /* nlstate */
1.201     brouard  6739:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6740:     } /* end cpt state*/ 
                   6741:   } /* end covariate */  
1.227     brouard  6742:   
                   6743:   
1.220     brouard  6744: /* 7eme */
1.218     brouard  6745:   if(backcast == 1){
1.217     brouard  6746:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6747:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6748:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6749:       if(TKresult[nres]!= k1)
                   6750:        continue;
1.218     brouard  6751:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6752:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6753:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6754:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6755:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6756:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6757:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6758:          vlv= nbcode[Tvaraff[k]][lv];
                   6759:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6760:        }
1.237     brouard  6761:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6762:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6763:        }       
1.227     brouard  6764:        fprintf(ficgp,"\n#\n");
                   6765:        if(invalidvarcomb[k1]){
                   6766:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6767:          continue;
                   6768:        }
                   6769:        
1.241     brouard  6770:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  6771:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6772: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6773:        k=3; /* Offset */
                   6774:        for (i=1; i<= nlstate ; i ++){
                   6775:          if(i==1)
                   6776:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6777:          else
                   6778:            fprintf(ficgp,", '' ");
                   6779:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6780:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6781:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6782:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6783:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6784:          /* for (j=2; j<= nlstate ; j ++) */
                   6785:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6786:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6787:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6788:        } /* nlstate */
                   6789:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6790:       } /* end cpt state*/ 
                   6791:     } /* end covariate */  
                   6792:   } /* End if backcast */
                   6793:   
1.223     brouard  6794:   /* 8eme */
1.218     brouard  6795:   if(prevfcast==1){
                   6796:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6797:     
1.237     brouard  6798:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6799:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6800:       if(TKresult[nres]!= k1)
                   6801:        continue;
1.211     brouard  6802:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6803:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6804:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6805:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6806:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6807:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6808:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6809:          vlv= nbcode[Tvaraff[k]][lv];
                   6810:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6811:        }
1.237     brouard  6812:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6813:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6814:        }       
1.227     brouard  6815:        fprintf(ficgp,"\n#\n");
                   6816:        if(invalidvarcomb[k1]){
                   6817:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6818:          continue;
                   6819:        }
                   6820:        
                   6821:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  6822:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  6823:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  6824: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6825:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6826:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6827:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6828:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6829:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6830:          if(i==1){
                   6831:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6832:          }else{
                   6833:            fprintf(ficgp,",\\\n '' ");
                   6834:          }
                   6835:          if(cptcoveff ==0){ /* No covariate */
                   6836:            ioffset=2; /* Age is in 2 */
                   6837:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6838:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6839:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6840:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6841:            fprintf(ficgp," u %d:(", ioffset); 
                   6842:            if(i==nlstate+1)
                   6843:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6844:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6845:            else
                   6846:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6847:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6848:          }else{ /* more than 2 covariates */
                   6849:            if(cptcoveff ==1){
                   6850:              ioffset=4; /* Age is in 4 */
                   6851:            }else{
                   6852:              ioffset=6; /* Age is in 6 */
                   6853:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6854:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6855:            }   
                   6856:            fprintf(ficgp," u %d:(",ioffset); 
                   6857:            kl=0;
                   6858:            strcpy(gplotcondition,"(");
                   6859:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6860:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6861:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6862:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6863:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6864:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6865:              kl++;
                   6866:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6867:              kl++;
                   6868:              if(k <cptcoveff && cptcoveff>1)
                   6869:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6870:            }
                   6871:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6872:            /* 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 *\/ */
                   6873:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6874:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6875:            /* ''  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*/
                   6876:            if(i==nlstate+1){
                   6877:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6878:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6879:            }else{
                   6880:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6881:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6882:            }
                   6883:          } /* end if covariate */
                   6884:        } /* nlstate */
                   6885:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6886:       } /* end cpt state*/
                   6887:     } /* end covariate */
                   6888:   } /* End if prevfcast */
1.227     brouard  6889:   
                   6890:   
1.238     brouard  6891:   /* 9eme writing MLE parameters */
                   6892:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6893:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6894:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6895:     for(k=1; k <=(nlstate+ndeath); k++){
                   6896:       if (k != i) {
1.227     brouard  6897:        fprintf(ficgp,"#   current state %d\n",k);
                   6898:        for(j=1; j <=ncovmodel; j++){
                   6899:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6900:          jk++; 
                   6901:        }
                   6902:        fprintf(ficgp,"\n");
1.126     brouard  6903:       }
                   6904:     }
1.223     brouard  6905:   }
1.187     brouard  6906:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6907:   
1.145     brouard  6908:   /*goto avoid;*/
1.238     brouard  6909:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   6910:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6911:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6912:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6913:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6914:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6915:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6916:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6917:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6918:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6919:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6920:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6921:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6922:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6923:   fprintf(ficgp,"#\n");
1.223     brouard  6924:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  6925:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6926:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  6927:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6928:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6929:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6930:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6931:       if(TKresult[nres]!= jk)
                   6932:        continue;
                   6933:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6934:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6935:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6936:       }        
                   6937:       fprintf(ficgp,"\n#\n");
1.241     brouard  6938:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  6939:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6940:       if (ng==1){
                   6941:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6942:        fprintf(ficgp,"\nunset log y");
                   6943:       }else if (ng==2){
                   6944:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6945:        fprintf(ficgp,"\nset log y");
                   6946:       }else if (ng==3){
                   6947:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6948:        fprintf(ficgp,"\nset log y");
                   6949:       }else
                   6950:        fprintf(ficgp,"\nunset title ");
                   6951:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6952:       i=1;
                   6953:       for(k2=1; k2<=nlstate; k2++) {
                   6954:        k3=i;
                   6955:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6956:          if (k != k2){
                   6957:            switch( ng) {
                   6958:            case 1:
                   6959:              if(nagesqr==0)
                   6960:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6961:              else /* nagesqr =1 */
                   6962:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6963:              break;
                   6964:            case 2: /* ng=2 */
                   6965:              if(nagesqr==0)
                   6966:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6967:              else /* nagesqr =1 */
                   6968:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6969:              break;
                   6970:            case 3:
                   6971:              if(nagesqr==0)
                   6972:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6973:              else /* nagesqr =1 */
                   6974:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6975:              break;
                   6976:            }
                   6977:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  6978:            ijp=1; /* product no age */
                   6979:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   6980:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  6981:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  6982:              if(j==Tage[ij]) { /* Product by age */
                   6983:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  6984:                  if(DummyV[j]==0){
1.237     brouard  6985:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   6986:                  }else{ /* quantitative */
                   6987:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   6988:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6989:                  }
                   6990:                  ij++;
                   6991:                }
                   6992:              }else if(j==Tprod[ijp]) { /* */ 
                   6993:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   6994:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  6995:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   6996:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  6997:                      /* 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)]); */
                   6998:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   6999:                    }else{ /* Vn is dummy and Vm is quanti */
                   7000:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   7001:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7002:                    }
                   7003:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  7004:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  7005:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   7006:                    }else{ /* Both quanti */
                   7007:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7008:                    }
                   7009:                  }
1.238     brouard  7010:                  ijp++;
1.237     brouard  7011:                }
                   7012:              } else{  /* simple covariate */
                   7013:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   7014:                if(Dummy[j]==0){
                   7015:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   7016:                }else{ /* quantitative */
                   7017:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  7018:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7019:                }
1.237     brouard  7020:              } /* end simple */
                   7021:            } /* end j */
1.223     brouard  7022:          }else{
                   7023:            i=i-ncovmodel;
                   7024:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7025:              fprintf(ficgp," (1.");
                   7026:          }
1.227     brouard  7027:          
1.223     brouard  7028:          if(ng != 1){
                   7029:            fprintf(ficgp,")/(1");
1.227     brouard  7030:            
1.223     brouard  7031:            for(k1=1; k1 <=nlstate; k1++){ 
                   7032:              if(nagesqr==0)
                   7033:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7034:              else /* nagesqr =1 */
                   7035:                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  7036:               
1.223     brouard  7037:              ij=1;
                   7038:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7039:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7040:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7041:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7042:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7043:                    ij++;
                   7044:                  }
                   7045:                }
                   7046:                else
1.225     brouard  7047:                  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  7048:              }
                   7049:              fprintf(ficgp,")");
                   7050:            }
                   7051:            fprintf(ficgp,")");
                   7052:            if(ng ==2)
                   7053:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7054:            else /* ng= 3 */
                   7055:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7056:          }else{ /* end ng <> 1 */
                   7057:            if( k !=k2) /* logit p11 is hard to draw */
                   7058:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7059:          }
                   7060:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7061:            fprintf(ficgp,",");
                   7062:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7063:            fprintf(ficgp,",");
                   7064:          i=i+ncovmodel;
                   7065:        } /* end k */
                   7066:       } /* end k2 */
                   7067:       fprintf(ficgp,"\n set out\n");
                   7068:     } /* end jk */
                   7069:   } /* end ng */
                   7070:   /* avoid: */
                   7071:   fflush(ficgp); 
1.126     brouard  7072: }  /* end gnuplot */
                   7073: 
                   7074: 
                   7075: /*************** Moving average **************/
1.219     brouard  7076: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7077:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7078:    
1.222     brouard  7079:    int i, cpt, cptcod;
                   7080:    int modcovmax =1;
                   7081:    int mobilavrange, mob;
                   7082:    int iage=0;
                   7083: 
                   7084:    double sum=0.;
                   7085:    double age;
                   7086:    double *sumnewp, *sumnewm;
                   7087:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7088:   
                   7089:   
1.225     brouard  7090:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7091:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7092: 
                   7093:    sumnewp = vector(1,ncovcombmax);
                   7094:    sumnewm = vector(1,ncovcombmax);
                   7095:    agemingood = vector(1,ncovcombmax); 
                   7096:    agemaxgood = vector(1,ncovcombmax);
                   7097: 
                   7098:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7099:      sumnewm[cptcod]=0.;
                   7100:      sumnewp[cptcod]=0.;
                   7101:      agemingood[cptcod]=0;
                   7102:      agemaxgood[cptcod]=0;
                   7103:    }
                   7104:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7105:   
                   7106:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7107:      if(mobilav==1) mobilavrange=5; /* default */
                   7108:      else mobilavrange=mobilav;
                   7109:      for (age=bage; age<=fage; age++)
                   7110:        for (i=1; i<=nlstate;i++)
                   7111:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7112:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7113:      /* We keep the original values on the extreme ages bage, fage and for 
                   7114:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7115:        we use a 5 terms etc. until the borders are no more concerned. 
                   7116:      */ 
                   7117:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7118:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7119:         for (i=1; i<=nlstate;i++){
                   7120:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7121:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7122:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7123:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7124:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7125:             }
                   7126:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7127:           }
                   7128:         }
                   7129:        }/* end age */
                   7130:      }/* end mob */
                   7131:    }else
                   7132:      return -1;
                   7133:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7134:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7135:      if(invalidvarcomb[cptcod]){
                   7136:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7137:        continue;
                   7138:      }
1.219     brouard  7139: 
1.222     brouard  7140:      agemingood[cptcod]=fage-(mob-1)/2;
                   7141:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7142:        sumnewm[cptcod]=0.;
                   7143:        for (i=1; i<=nlstate;i++){
                   7144:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7145:        }
                   7146:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7147:         agemingood[cptcod]=age;
                   7148:        }else{ /* bad */
                   7149:         for (i=1; i<=nlstate;i++){
                   7150:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7151:         } /* i */
                   7152:        } /* end bad */
                   7153:      }/* age */
                   7154:      sum=0.;
                   7155:      for (i=1; i<=nlstate;i++){
                   7156:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7157:      }
                   7158:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7159:        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);
                   7160:        /* for (i=1; i<=nlstate;i++){ */
                   7161:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7162:        /* } /\* i *\/ */
                   7163:      } /* end bad */
                   7164:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7165:      /* From youngest, finding the oldest wrong */
                   7166:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7167:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7168:        sumnewm[cptcod]=0.;
                   7169:        for (i=1; i<=nlstate;i++){
                   7170:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7171:        }
                   7172:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7173:         agemaxgood[cptcod]=age;
                   7174:        }else{ /* bad */
                   7175:         for (i=1; i<=nlstate;i++){
                   7176:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7177:         } /* i */
                   7178:        } /* end bad */
                   7179:      }/* age */
                   7180:      sum=0.;
                   7181:      for (i=1; i<=nlstate;i++){
                   7182:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7183:      }
                   7184:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7185:        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);
                   7186:        /* for (i=1; i<=nlstate;i++){ */
                   7187:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7188:        /* } /\* i *\/ */
                   7189:      } /* end bad */
                   7190:                
                   7191:      for (age=bage; age<=fage; age++){
1.235     brouard  7192:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7193:        sumnewp[cptcod]=0.;
                   7194:        sumnewm[cptcod]=0.;
                   7195:        for (i=1; i<=nlstate;i++){
                   7196:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7197:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7198:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7199:        }
                   7200:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7201:      }
                   7202:      /* printf("\n"); */
                   7203:      /* } */
                   7204:      /* brutal averaging */
                   7205:      for (i=1; i<=nlstate;i++){
                   7206:        for (age=1; age<=bage; age++){
                   7207:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7208:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7209:        }       
                   7210:        for (age=fage; age<=AGESUP; age++){
                   7211:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7212:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7213:        }
                   7214:      } /* end i status */
                   7215:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7216:        for (age=1; age<=AGESUP; age++){
                   7217:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7218:         mobaverage[(int)age][i][cptcod]=0.;
                   7219:        }
                   7220:      }
                   7221:    }/* end cptcod */
                   7222:    free_vector(sumnewm,1, ncovcombmax);
                   7223:    free_vector(sumnewp,1, ncovcombmax);
                   7224:    free_vector(agemaxgood,1, ncovcombmax);
                   7225:    free_vector(agemingood,1, ncovcombmax);
                   7226:    return 0;
                   7227:  }/* End movingaverage */
1.218     brouard  7228:  
1.126     brouard  7229: 
                   7230: /************** Forecasting ******************/
1.235     brouard  7231:  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  7232:   /* proj1, year, month, day of starting projection 
                   7233:      agemin, agemax range of age
                   7234:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7235:      anproj2 year of en of projection (same day and month as proj1).
                   7236:   */
1.235     brouard  7237:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7238:   double agec; /* generic age */
                   7239:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7240:   double *popeffectif,*popcount;
                   7241:   double ***p3mat;
1.218     brouard  7242:   /* double ***mobaverage; */
1.126     brouard  7243:   char fileresf[FILENAMELENGTH];
                   7244: 
                   7245:   agelim=AGESUP;
1.211     brouard  7246:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7247:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7248:      We still use firstpass and lastpass as another selection.
                   7249:   */
1.214     brouard  7250:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7251:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7252:  
1.201     brouard  7253:   strcpy(fileresf,"F_"); 
                   7254:   strcat(fileresf,fileresu);
1.126     brouard  7255:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7256:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7257:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7258:   }
1.235     brouard  7259:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7260:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7261: 
1.225     brouard  7262:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7263: 
                   7264: 
                   7265:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7266:   if (stepm<=12) stepsize=1;
                   7267:   if(estepm < stepm){
                   7268:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7269:   }
                   7270:   else  hstepm=estepm;   
                   7271: 
                   7272:   hstepm=hstepm/stepm; 
                   7273:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7274:                                fractional in yp1 */
                   7275:   anprojmean=yp;
                   7276:   yp2=modf((yp1*12),&yp);
                   7277:   mprojmean=yp;
                   7278:   yp1=modf((yp2*30.5),&yp);
                   7279:   jprojmean=yp;
                   7280:   if(jprojmean==0) jprojmean=1;
                   7281:   if(mprojmean==0) jprojmean=1;
                   7282: 
1.227     brouard  7283:   i1=pow(2,cptcoveff);
1.126     brouard  7284:   if (cptcovn < 1){i1=1;}
                   7285:   
                   7286:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7287:   
                   7288:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7289:   
1.126     brouard  7290: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7291:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7292:   for(k=1; k<=i1;k++){
                   7293:     if(TKresult[nres]!= k)
                   7294:       continue;
1.227     brouard  7295:     if(invalidvarcomb[k]){
                   7296:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7297:       continue;
                   7298:     }
                   7299:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7300:     for(j=1;j<=cptcoveff;j++) {
                   7301:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7302:     }
1.235     brouard  7303:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7304:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7305:     }
1.227     brouard  7306:     fprintf(ficresf," yearproj age");
                   7307:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7308:       for(i=1; i<=nlstate;i++)               
                   7309:        fprintf(ficresf," p%d%d",i,j);
                   7310:       fprintf(ficresf," wp.%d",j);
                   7311:     }
                   7312:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7313:       fprintf(ficresf,"\n");
                   7314:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7315:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7316:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7317:        nhstepm = nhstepm/hstepm; 
                   7318:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7319:        oldm=oldms;savm=savms;
1.235     brouard  7320:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7321:        
                   7322:        for (h=0; h<=nhstepm; h++){
                   7323:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7324:            fprintf(ficresf,"\n");
                   7325:            for(j=1;j<=cptcoveff;j++) 
                   7326:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7327:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7328:          } 
                   7329:          for(j=1; j<=nlstate+ndeath;j++) {
                   7330:            ppij=0.;
                   7331:            for(i=1; i<=nlstate;i++) {
                   7332:              if (mobilav==1) 
                   7333:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7334:              else {
                   7335:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7336:              }
                   7337:              if (h*hstepm/YEARM*stepm== yearp) {
                   7338:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7339:              }
                   7340:            } /* end i */
                   7341:            if (h*hstepm/YEARM*stepm==yearp) {
                   7342:              fprintf(ficresf," %.3f", ppij);
                   7343:            }
                   7344:          }/* end j */
                   7345:        } /* end h */
                   7346:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7347:       } /* end agec */
                   7348:     } /* end yearp */
                   7349:   } /* end  k */
1.219     brouard  7350:        
1.126     brouard  7351:   fclose(ficresf);
1.215     brouard  7352:   printf("End of Computing forecasting \n");
                   7353:   fprintf(ficlog,"End of Computing forecasting\n");
                   7354: 
1.126     brouard  7355: }
                   7356: 
1.218     brouard  7357: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7358: /* 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  7359: /*   /\* back1, year, month, day of starting backection  */
                   7360: /*      agemin, agemax range of age */
                   7361: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7362: /*      anback2 year of en of backection (same day and month as back1). */
                   7363: /*   *\/ */
                   7364: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7365: /*   double agec; /\* generic age *\/ */
                   7366: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7367: /*   double *popeffectif,*popcount; */
                   7368: /*   double ***p3mat; */
                   7369: /*   /\* double ***mobaverage; *\/ */
                   7370: /*   char fileresfb[FILENAMELENGTH]; */
                   7371:        
                   7372: /*   agelim=AGESUP; */
                   7373: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7374: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7375: /*      We still use firstpass and lastpass as another selection. */
                   7376: /*   *\/ */
                   7377: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7378: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7379: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7380:        
                   7381: /*   strcpy(fileresfb,"FB_");  */
                   7382: /*   strcat(fileresfb,fileresu); */
                   7383: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7384: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7385: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7386: /*   } */
                   7387: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7388: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7389:        
1.225     brouard  7390: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7391:        
                   7392: /*   /\* if (mobilav!=0) { *\/ */
                   7393: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7394: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7395: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7396: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7397: /*   /\*   } *\/ */
                   7398: /*   /\* } *\/ */
                   7399:        
                   7400: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7401: /*   if (stepm<=12) stepsize=1; */
                   7402: /*   if(estepm < stepm){ */
                   7403: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7404: /*   } */
                   7405: /*   else  hstepm=estepm;    */
                   7406:        
                   7407: /*   hstepm=hstepm/stepm;  */
                   7408: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7409: /*                                fractional in yp1 *\/ */
                   7410: /*   anprojmean=yp; */
                   7411: /*   yp2=modf((yp1*12),&yp); */
                   7412: /*   mprojmean=yp; */
                   7413: /*   yp1=modf((yp2*30.5),&yp); */
                   7414: /*   jprojmean=yp; */
                   7415: /*   if(jprojmean==0) jprojmean=1; */
                   7416: /*   if(mprojmean==0) jprojmean=1; */
                   7417:        
1.225     brouard  7418: /*   i1=cptcoveff; */
1.218     brouard  7419: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7420:   
1.218     brouard  7421: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7422:   
1.218     brouard  7423: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7424:        
                   7425: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7426: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7427: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7428: /*       k=k+1; */
                   7429: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7430: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7431: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7432: /*       } */
                   7433: /*       fprintf(ficresfb," yearbproj age"); */
                   7434: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7435: /*                             for(i=1; i<=nlstate;i++)               */
                   7436: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7437: /*                             fprintf(ficresfb," p.%d",j); */
                   7438: /*       } */
                   7439: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7440: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7441: /*                             fprintf(ficresfb,"\n"); */
                   7442: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7443: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7444: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7445: /*                                     nhstepm = nhstepm/hstepm;  */
                   7446: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7447: /*                                     oldm=oldms;savm=savms; */
                   7448: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7449: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7450: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7451: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7452: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7453: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7454: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7455: /*                                             }  */
                   7456: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7457: /*                                                     ppij=0.; */
                   7458: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7459: /*                                                             if (mobilav==1)  */
                   7460: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7461: /*                                                             else { */
                   7462: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7463: /*                                                             } */
                   7464: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7465: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7466: /*                                                             } */
                   7467: /*                                                     } /\* end i *\/ */
                   7468: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7469: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7470: /*                                                     } */
                   7471: /*                                             }/\* end j *\/ */
                   7472: /*                                     } /\* end h *\/ */
                   7473: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7474: /*                             } /\* end agec *\/ */
                   7475: /*       } /\* end yearp *\/ */
                   7476: /*     } /\* end cptcod *\/ */
                   7477: /*   } /\* end  cptcov *\/ */
                   7478:        
                   7479: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7480:        
                   7481: /*   fclose(ficresfb); */
                   7482: /*   printf("End of Computing Back forecasting \n"); */
                   7483: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7484:        
1.218     brouard  7485: /* } */
1.217     brouard  7486: 
1.126     brouard  7487: /************** Forecasting *****not tested NB*************/
1.227     brouard  7488: /* 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  7489:   
1.227     brouard  7490: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7491: /*   int *popage; */
                   7492: /*   double calagedatem, agelim, kk1, kk2; */
                   7493: /*   double *popeffectif,*popcount; */
                   7494: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7495: /*   /\* double ***mobaverage; *\/ */
                   7496: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7497: 
1.227     brouard  7498: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7499: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7500: /*   agelim=AGESUP; */
                   7501: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7502:   
1.227     brouard  7503: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7504:   
                   7505:   
1.227     brouard  7506: /*   strcpy(filerespop,"POP_");  */
                   7507: /*   strcat(filerespop,fileresu); */
                   7508: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7509: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7510: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7511: /*   } */
                   7512: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7513: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7514: 
1.227     brouard  7515: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7516: 
1.227     brouard  7517: /*   /\* if (mobilav!=0) { *\/ */
                   7518: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7519: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7520: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7521: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7522: /*   /\*   } *\/ */
                   7523: /*   /\* } *\/ */
1.126     brouard  7524: 
1.227     brouard  7525: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7526: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7527:   
1.227     brouard  7528: /*   agelim=AGESUP; */
1.126     brouard  7529:   
1.227     brouard  7530: /*   hstepm=1; */
                   7531: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7532:        
1.227     brouard  7533: /*   if (popforecast==1) { */
                   7534: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7535: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7536: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7537: /*     }  */
                   7538: /*     popage=ivector(0,AGESUP); */
                   7539: /*     popeffectif=vector(0,AGESUP); */
                   7540: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7541:     
1.227     brouard  7542: /*     i=1;    */
                   7543: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7544:     
1.227     brouard  7545: /*     imx=i; */
                   7546: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7547: /*   } */
1.218     brouard  7548:   
1.227     brouard  7549: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7550: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7551: /*       k=k+1; */
                   7552: /*       fprintf(ficrespop,"\n#******"); */
                   7553: /*       for(j=1;j<=cptcoveff;j++) { */
                   7554: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7555: /*       } */
                   7556: /*       fprintf(ficrespop,"******\n"); */
                   7557: /*       fprintf(ficrespop,"# Age"); */
                   7558: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7559: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7560:       
1.227     brouard  7561: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7562: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7563:        
1.227     brouard  7564: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7565: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7566: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7567:          
1.227     brouard  7568: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7569: /*       oldm=oldms;savm=savms; */
                   7570: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7571:          
1.227     brouard  7572: /*       for (h=0; h<=nhstepm; h++){ */
                   7573: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7574: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7575: /*         }  */
                   7576: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7577: /*           kk1=0.;kk2=0; */
                   7578: /*           for(i=1; i<=nlstate;i++) {               */
                   7579: /*             if (mobilav==1)  */
                   7580: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7581: /*             else { */
                   7582: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7583: /*             } */
                   7584: /*           } */
                   7585: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7586: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7587: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7588: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7589: /*           } */
                   7590: /*         } */
                   7591: /*         for(i=1; i<=nlstate;i++){ */
                   7592: /*           kk1=0.; */
                   7593: /*           for(j=1; j<=nlstate;j++){ */
                   7594: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7595: /*           } */
                   7596: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7597: /*         } */
1.218     brouard  7598:            
1.227     brouard  7599: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7600: /*           for(j=1; j<=nlstate;j++)  */
                   7601: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7602: /*       } */
                   7603: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7604: /*     } */
                   7605: /*       } */
1.218     brouard  7606:       
1.227     brouard  7607: /*       /\******\/ */
1.218     brouard  7608:       
1.227     brouard  7609: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7610: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7611: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7612: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7613: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7614:          
1.227     brouard  7615: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7616: /*       oldm=oldms;savm=savms; */
                   7617: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7618: /*       for (h=0; h<=nhstepm; h++){ */
                   7619: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7620: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7621: /*         }  */
                   7622: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7623: /*           kk1=0.;kk2=0; */
                   7624: /*           for(i=1; i<=nlstate;i++) {               */
                   7625: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7626: /*           } */
                   7627: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7628: /*         } */
                   7629: /*       } */
                   7630: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7631: /*     } */
                   7632: /*       } */
                   7633: /*     }  */
                   7634: /*   } */
1.218     brouard  7635:   
1.227     brouard  7636: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7637:   
1.227     brouard  7638: /*   if (popforecast==1) { */
                   7639: /*     free_ivector(popage,0,AGESUP); */
                   7640: /*     free_vector(popeffectif,0,AGESUP); */
                   7641: /*     free_vector(popcount,0,AGESUP); */
                   7642: /*   } */
                   7643: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7644: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7645: /*   fclose(ficrespop); */
                   7646: /* } /\* End of popforecast *\/ */
1.218     brouard  7647:  
1.126     brouard  7648: int fileappend(FILE *fichier, char *optionfich)
                   7649: {
                   7650:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7651:     printf("Problem with file: %s\n", optionfich);
                   7652:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7653:     return (0);
                   7654:   }
                   7655:   fflush(fichier);
                   7656:   return (1);
                   7657: }
                   7658: 
                   7659: 
                   7660: /**************** function prwizard **********************/
                   7661: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7662: {
                   7663: 
                   7664:   /* Wizard to print covariance matrix template */
                   7665: 
1.164     brouard  7666:   char ca[32], cb[32];
                   7667:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7668:   int numlinepar;
                   7669: 
                   7670:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7671:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7672:   for(i=1; i <=nlstate; i++){
                   7673:     jj=0;
                   7674:     for(j=1; j <=nlstate+ndeath; j++){
                   7675:       if(j==i) continue;
                   7676:       jj++;
                   7677:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7678:       printf("%1d%1d",i,j);
                   7679:       fprintf(ficparo,"%1d%1d",i,j);
                   7680:       for(k=1; k<=ncovmodel;k++){
                   7681:        /*        printf(" %lf",param[i][j][k]); */
                   7682:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7683:        printf(" 0.");
                   7684:        fprintf(ficparo," 0.");
                   7685:       }
                   7686:       printf("\n");
                   7687:       fprintf(ficparo,"\n");
                   7688:     }
                   7689:   }
                   7690:   printf("# Scales (for hessian or gradient estimation)\n");
                   7691:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7692:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7693:   for(i=1; i <=nlstate; i++){
                   7694:     jj=0;
                   7695:     for(j=1; j <=nlstate+ndeath; j++){
                   7696:       if(j==i) continue;
                   7697:       jj++;
                   7698:       fprintf(ficparo,"%1d%1d",i,j);
                   7699:       printf("%1d%1d",i,j);
                   7700:       fflush(stdout);
                   7701:       for(k=1; k<=ncovmodel;k++){
                   7702:        /*      printf(" %le",delti3[i][j][k]); */
                   7703:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7704:        printf(" 0.");
                   7705:        fprintf(ficparo," 0.");
                   7706:       }
                   7707:       numlinepar++;
                   7708:       printf("\n");
                   7709:       fprintf(ficparo,"\n");
                   7710:     }
                   7711:   }
                   7712:   printf("# Covariance matrix\n");
                   7713: /* # 121 Var(a12)\n\ */
                   7714: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7715: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7716: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7717: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7718: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7719: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7720: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7721:   fflush(stdout);
                   7722:   fprintf(ficparo,"# Covariance matrix\n");
                   7723:   /* # 121 Var(a12)\n\ */
                   7724:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7725:   /* #   ...\n\ */
                   7726:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7727:   
                   7728:   for(itimes=1;itimes<=2;itimes++){
                   7729:     jj=0;
                   7730:     for(i=1; i <=nlstate; i++){
                   7731:       for(j=1; j <=nlstate+ndeath; j++){
                   7732:        if(j==i) continue;
                   7733:        for(k=1; k<=ncovmodel;k++){
                   7734:          jj++;
                   7735:          ca[0]= k+'a'-1;ca[1]='\0';
                   7736:          if(itimes==1){
                   7737:            printf("#%1d%1d%d",i,j,k);
                   7738:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7739:          }else{
                   7740:            printf("%1d%1d%d",i,j,k);
                   7741:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7742:            /*  printf(" %.5le",matcov[i][j]); */
                   7743:          }
                   7744:          ll=0;
                   7745:          for(li=1;li <=nlstate; li++){
                   7746:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7747:              if(lj==li) continue;
                   7748:              for(lk=1;lk<=ncovmodel;lk++){
                   7749:                ll++;
                   7750:                if(ll<=jj){
                   7751:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7752:                  if(ll<jj){
                   7753:                    if(itimes==1){
                   7754:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7755:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7756:                    }else{
                   7757:                      printf(" 0.");
                   7758:                      fprintf(ficparo," 0.");
                   7759:                    }
                   7760:                  }else{
                   7761:                    if(itimes==1){
                   7762:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7763:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7764:                    }else{
                   7765:                      printf(" 0.");
                   7766:                      fprintf(ficparo," 0.");
                   7767:                    }
                   7768:                  }
                   7769:                }
                   7770:              } /* end lk */
                   7771:            } /* end lj */
                   7772:          } /* end li */
                   7773:          printf("\n");
                   7774:          fprintf(ficparo,"\n");
                   7775:          numlinepar++;
                   7776:        } /* end k*/
                   7777:       } /*end j */
                   7778:     } /* end i */
                   7779:   } /* end itimes */
                   7780: 
                   7781: } /* end of prwizard */
                   7782: /******************* Gompertz Likelihood ******************************/
                   7783: double gompertz(double x[])
                   7784: { 
                   7785:   double A,B,L=0.0,sump=0.,num=0.;
                   7786:   int i,n=0; /* n is the size of the sample */
                   7787: 
1.220     brouard  7788:   for (i=1;i<=imx ; i++) {
1.126     brouard  7789:     sump=sump+weight[i];
                   7790:     /*    sump=sump+1;*/
                   7791:     num=num+1;
                   7792:   }
                   7793:  
                   7794:  
                   7795:   /* for (i=0; i<=imx; i++) 
                   7796:      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]);*/
                   7797: 
                   7798:   for (i=1;i<=imx ; i++)
                   7799:     {
                   7800:       if (cens[i] == 1 && wav[i]>1)
                   7801:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7802:       
                   7803:       if (cens[i] == 0 && wav[i]>1)
                   7804:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7805:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7806:       
                   7807:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7808:       if (wav[i] > 1 ) { /* ??? */
                   7809:        L=L+A*weight[i];
                   7810:        /*      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]);*/
                   7811:       }
                   7812:     }
                   7813: 
                   7814:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7815:  
                   7816:   return -2*L*num/sump;
                   7817: }
                   7818: 
1.136     brouard  7819: #ifdef GSL
                   7820: /******************* Gompertz_f Likelihood ******************************/
                   7821: double gompertz_f(const gsl_vector *v, void *params)
                   7822: { 
                   7823:   double A,B,LL=0.0,sump=0.,num=0.;
                   7824:   double *x= (double *) v->data;
                   7825:   int i,n=0; /* n is the size of the sample */
                   7826: 
                   7827:   for (i=0;i<=imx-1 ; i++) {
                   7828:     sump=sump+weight[i];
                   7829:     /*    sump=sump+1;*/
                   7830:     num=num+1;
                   7831:   }
                   7832:  
                   7833:  
                   7834:   /* for (i=0; i<=imx; i++) 
                   7835:      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]);*/
                   7836:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7837:   for (i=1;i<=imx ; i++)
                   7838:     {
                   7839:       if (cens[i] == 1 && wav[i]>1)
                   7840:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7841:       
                   7842:       if (cens[i] == 0 && wav[i]>1)
                   7843:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7844:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7845:       
                   7846:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7847:       if (wav[i] > 1 ) { /* ??? */
                   7848:        LL=LL+A*weight[i];
                   7849:        /*      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]);*/
                   7850:       }
                   7851:     }
                   7852: 
                   7853:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7854:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7855:  
                   7856:   return -2*LL*num/sump;
                   7857: }
                   7858: #endif
                   7859: 
1.126     brouard  7860: /******************* Printing html file ***********/
1.201     brouard  7861: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7862:                  int lastpass, int stepm, int weightopt, char model[],\
                   7863:                  int imx,  double p[],double **matcov,double agemortsup){
                   7864:   int i,k;
                   7865: 
                   7866:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7867:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7868:   for (i=1;i<=2;i++) 
                   7869:     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  7870:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7871:   fprintf(fichtm,"</ul>");
                   7872: 
                   7873: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7874: 
                   7875:  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>");
                   7876: 
                   7877:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7878:    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]);
                   7879: 
                   7880:  
                   7881:   fflush(fichtm);
                   7882: }
                   7883: 
                   7884: /******************* Gnuplot file **************/
1.201     brouard  7885: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7886: 
                   7887:   char dirfileres[132],optfileres[132];
1.164     brouard  7888: 
1.126     brouard  7889:   int ng;
                   7890: 
                   7891: 
                   7892:   /*#ifdef windows */
                   7893:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7894:     /*#endif */
                   7895: 
                   7896: 
                   7897:   strcpy(dirfileres,optionfilefiname);
                   7898:   strcpy(optfileres,"vpl");
1.199     brouard  7899:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7900:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7901:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7902:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7903:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7904: 
                   7905: } 
                   7906: 
1.136     brouard  7907: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7908: {
1.126     brouard  7909: 
1.136     brouard  7910:   /*-------- data file ----------*/
                   7911:   FILE *fic;
                   7912:   char dummy[]="                         ";
1.240     brouard  7913:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  7914:   int lstra;
1.136     brouard  7915:   int linei, month, year,iout;
                   7916:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7917:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7918:   char *stratrunc;
1.223     brouard  7919: 
1.240     brouard  7920:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   7921:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  7922: 
1.240     brouard  7923:   for(v=1; v <=ncovcol;v++){
                   7924:     DummyV[v]=0;
                   7925:     FixedV[v]=0;
                   7926:   }
                   7927:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   7928:     DummyV[v]=1;
                   7929:     FixedV[v]=0;
                   7930:   }
                   7931:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   7932:     DummyV[v]=0;
                   7933:     FixedV[v]=1;
                   7934:   }
                   7935:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7936:     DummyV[v]=1;
                   7937:     FixedV[v]=1;
                   7938:   }
                   7939:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7940:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   7941:     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]);
                   7942:   }
1.126     brouard  7943: 
1.136     brouard  7944:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7945:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7946:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7947:   }
1.126     brouard  7948: 
1.136     brouard  7949:   i=1;
                   7950:   linei=0;
                   7951:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7952:     linei=linei+1;
                   7953:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7954:       if(line[j] == '\t')
                   7955:        line[j] = ' ';
                   7956:     }
                   7957:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7958:       ;
                   7959:     };
                   7960:     line[j+1]=0;  /* Trims blanks at end of line */
                   7961:     if(line[0]=='#'){
                   7962:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7963:       printf("Comment line\n%s\n",line);
                   7964:       continue;
                   7965:     }
                   7966:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7967:     strcpy(line, linetmp);
1.223     brouard  7968:     
                   7969:     /* Loops on waves */
                   7970:     for (j=maxwav;j>=1;j--){
                   7971:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  7972:        cutv(stra, strb, line, ' '); 
                   7973:        if(strb[0]=='.') { /* Missing value */
                   7974:          lval=-1;
                   7975:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   7976:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   7977:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   7978:            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);
                   7979:            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);
                   7980:            return 1;
                   7981:          }
                   7982:        }else{
                   7983:          errno=0;
                   7984:          /* what_kind_of_number(strb); */
                   7985:          dval=strtod(strb,&endptr); 
                   7986:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7987:          /* if(strb != endptr && *endptr == '\0') */
                   7988:          /*    dval=dlval; */
                   7989:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7990:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7991:            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);
                   7992:            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);
                   7993:            return 1;
                   7994:          }
                   7995:          cotqvar[j][iv][i]=dval; 
                   7996:          cotvar[j][ntv+iv][i]=dval; 
                   7997:        }
                   7998:        strcpy(line,stra);
1.223     brouard  7999:       }/* end loop ntqv */
1.225     brouard  8000:       
1.223     brouard  8001:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  8002:        cutv(stra, strb, line, ' '); 
                   8003:        if(strb[0]=='.') { /* Missing value */
                   8004:          lval=-1;
                   8005:        }else{
                   8006:          errno=0;
                   8007:          lval=strtol(strb,&endptr,10); 
                   8008:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8009:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8010:            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);
                   8011:            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);
                   8012:            return 1;
                   8013:          }
                   8014:        }
                   8015:        if(lval <-1 || lval >1){
                   8016:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8017:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8018:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8019:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8020:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8021:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8022:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8023:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8024:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8025:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8026:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8027:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8028:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8029:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8030:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8031:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8032:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8033:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8034:          return 1;
                   8035:        }
                   8036:        cotvar[j][iv][i]=(double)(lval);
                   8037:        strcpy(line,stra);
1.223     brouard  8038:       }/* end loop ntv */
1.225     brouard  8039:       
1.223     brouard  8040:       /* Statuses  at wave */
1.137     brouard  8041:       cutv(stra, strb, line, ' '); 
1.223     brouard  8042:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8043:        lval=-1;
1.136     brouard  8044:       }else{
1.238     brouard  8045:        errno=0;
                   8046:        lval=strtol(strb,&endptr,10); 
                   8047:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8048:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8049:          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);
                   8050:          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);
                   8051:          return 1;
                   8052:        }
1.136     brouard  8053:       }
1.225     brouard  8054:       
1.136     brouard  8055:       s[j][i]=lval;
1.225     brouard  8056:       
1.223     brouard  8057:       /* Date of Interview */
1.136     brouard  8058:       strcpy(line,stra);
                   8059:       cutv(stra, strb,line,' ');
1.169     brouard  8060:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8061:       }
1.169     brouard  8062:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8063:        month=99;
                   8064:        year=9999;
1.136     brouard  8065:       }else{
1.225     brouard  8066:        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);
                   8067:        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);
                   8068:        return 1;
1.136     brouard  8069:       }
                   8070:       anint[j][i]= (double) year; 
                   8071:       mint[j][i]= (double)month; 
                   8072:       strcpy(line,stra);
1.223     brouard  8073:     } /* End loop on waves */
1.225     brouard  8074:     
1.223     brouard  8075:     /* Date of death */
1.136     brouard  8076:     cutv(stra, strb,line,' '); 
1.169     brouard  8077:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8078:     }
1.169     brouard  8079:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8080:       month=99;
                   8081:       year=9999;
                   8082:     }else{
1.141     brouard  8083:       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  8084:       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);
                   8085:       return 1;
1.136     brouard  8086:     }
                   8087:     andc[i]=(double) year; 
                   8088:     moisdc[i]=(double) month; 
                   8089:     strcpy(line,stra);
                   8090:     
1.223     brouard  8091:     /* Date of birth */
1.136     brouard  8092:     cutv(stra, strb,line,' '); 
1.169     brouard  8093:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8094:     }
1.169     brouard  8095:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8096:       month=99;
                   8097:       year=9999;
                   8098:     }else{
1.141     brouard  8099:       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);
                   8100:       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  8101:       return 1;
1.136     brouard  8102:     }
                   8103:     if (year==9999) {
1.141     brouard  8104:       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);
                   8105:       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  8106:       return 1;
                   8107:       
1.136     brouard  8108:     }
                   8109:     annais[i]=(double)(year);
                   8110:     moisnais[i]=(double)(month); 
                   8111:     strcpy(line,stra);
1.225     brouard  8112:     
1.223     brouard  8113:     /* Sample weight */
1.136     brouard  8114:     cutv(stra, strb,line,' '); 
                   8115:     errno=0;
                   8116:     dval=strtod(strb,&endptr); 
                   8117:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8118:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8119:       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  8120:       fflush(ficlog);
                   8121:       return 1;
                   8122:     }
                   8123:     weight[i]=dval; 
                   8124:     strcpy(line,stra);
1.225     brouard  8125:     
1.223     brouard  8126:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8127:       cutv(stra, strb, line, ' '); 
                   8128:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8129:        lval=-1;
1.223     brouard  8130:       }else{
1.225     brouard  8131:        errno=0;
                   8132:        /* what_kind_of_number(strb); */
                   8133:        dval=strtod(strb,&endptr);
                   8134:        /* if(strb != endptr && *endptr == '\0') */
                   8135:        /*   dval=dlval; */
                   8136:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8137:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8138:          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);
                   8139:          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);
                   8140:          return 1;
                   8141:        }
                   8142:        coqvar[iv][i]=dval; 
1.226     brouard  8143:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8144:       }
                   8145:       strcpy(line,stra);
                   8146:     }/* end loop nqv */
1.136     brouard  8147:     
1.223     brouard  8148:     /* Covariate values */
1.136     brouard  8149:     for (j=ncovcol;j>=1;j--){
                   8150:       cutv(stra, strb,line,' '); 
1.223     brouard  8151:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8152:        lval=-1;
1.136     brouard  8153:       }else{
1.225     brouard  8154:        errno=0;
                   8155:        lval=strtol(strb,&endptr,10); 
                   8156:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8157:          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);
                   8158:          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);
                   8159:          return 1;
                   8160:        }
1.136     brouard  8161:       }
                   8162:       if(lval <-1 || lval >1){
1.225     brouard  8163:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8164:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8165:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8166:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8167:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8168:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8169:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8170:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8171:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8172:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8173:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8174:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8175:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8176:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8177:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8178:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8179:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8180:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8181:        return 1;
1.136     brouard  8182:       }
                   8183:       covar[j][i]=(double)(lval);
                   8184:       strcpy(line,stra);
                   8185:     }  
                   8186:     lstra=strlen(stra);
1.225     brouard  8187:     
1.136     brouard  8188:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8189:       stratrunc = &(stra[lstra-9]);
                   8190:       num[i]=atol(stratrunc);
                   8191:     }
                   8192:     else
                   8193:       num[i]=atol(stra);
                   8194:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8195:       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;}*/
                   8196:     
                   8197:     i=i+1;
                   8198:   } /* End loop reading  data */
1.225     brouard  8199:   
1.136     brouard  8200:   *imax=i-1; /* Number of individuals */
                   8201:   fclose(fic);
1.225     brouard  8202:   
1.136     brouard  8203:   return (0);
1.164     brouard  8204:   /* endread: */
1.225     brouard  8205:   printf("Exiting readdata: ");
                   8206:   fclose(fic);
                   8207:   return (1);
1.223     brouard  8208: }
1.126     brouard  8209: 
1.234     brouard  8210: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8211:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8212:   while (*p2 == ' ')
1.234     brouard  8213:     p2++; 
                   8214:   /* while ((*p1++ = *p2++) !=0) */
                   8215:   /*   ; */
                   8216:   /* do */
                   8217:   /*   while (*p2 == ' ') */
                   8218:   /*     p2++; */
                   8219:   /* while (*p1++ == *p2++); */
                   8220:   *stri=p2; 
1.145     brouard  8221: }
                   8222: 
1.235     brouard  8223: int decoderesult ( char resultline[], int nres)
1.230     brouard  8224: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8225: {
1.235     brouard  8226:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8227:   char resultsav[MAXLINE];
1.234     brouard  8228:   int resultmodel[MAXLINE];
                   8229:   int modelresult[MAXLINE];
1.230     brouard  8230:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8231: 
1.234     brouard  8232:   removefirstspace(&resultline);
1.233     brouard  8233:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8234: 
                   8235:   if (strstr(resultline,"v") !=0){
                   8236:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8237:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8238:     return 1;
                   8239:   }
                   8240:   trimbb(resultsav, resultline);
                   8241:   if (strlen(resultsav) >1){
                   8242:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8243:   }
1.234     brouard  8244:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8245:     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);
                   8246:     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);
                   8247:   }
                   8248:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8249:     if(nbocc(resultsav,'=') >1){
                   8250:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8251:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8252:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8253:     }else
                   8254:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8255:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8256:     
1.230     brouard  8257:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8258:     Tvarsel[k]=atoi(strc);
                   8259:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8260:     /* cptcovsel++;     */
                   8261:     if (nbocc(stra,'=') >0)
                   8262:       strcpy(resultsav,stra); /* and analyzes it */
                   8263:   }
1.235     brouard  8264:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8265:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8266:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8267:       match=0;
1.236     brouard  8268:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8269:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8270:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8271:          match=1;
                   8272:          break;
                   8273:        }
                   8274:       }
                   8275:       if(match == 0){
                   8276:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8277:       }
                   8278:     }
                   8279:   }
1.235     brouard  8280:   /* Checking for missing or useless values in comparison of current model needs */
                   8281:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8282:     match=0;
1.235     brouard  8283:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8284:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8285:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8286:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8287:          ++match;
                   8288:        }
                   8289:       }
                   8290:     }
                   8291:     if(match == 0){
                   8292:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8293:     }else if(match > 1){
                   8294:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8295:     }
                   8296:   }
1.235     brouard  8297:       
1.234     brouard  8298:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8299:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8300:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8301:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8302:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8303:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8304:   /*    1 0 0 0 */
                   8305:   /*    2 1 0 0 */
                   8306:   /*    3 0 1 0 */ 
                   8307:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8308:   /*    5 0 0 1 */
                   8309:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8310:   /*    7 0 1 1 */
                   8311:   /*    8 1 1 1 */
1.237     brouard  8312:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8313:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8314:   /* V5*age V5 known which value for nres?  */
                   8315:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8316:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8317:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8318:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8319:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8320:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8321:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8322:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8323:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8324:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8325:       k4++;;
                   8326:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8327:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8328:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8329:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8330:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8331:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8332:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8333:       k4q++;;
                   8334:     }
                   8335:   }
1.234     brouard  8336:   
1.235     brouard  8337:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8338:   return (0);
                   8339: }
1.235     brouard  8340: 
1.230     brouard  8341: int decodemodel( char model[], int lastobs)
                   8342:  /**< This routine decodes the model and returns:
1.224     brouard  8343:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8344:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8345:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8346:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8347:        * - cptcovage number of covariates with age*products =2
                   8348:        * - cptcovs number of simple covariates
                   8349:        * - 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
                   8350:        *     which is a new column after the 9 (ncovcol) variables. 
                   8351:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8352:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8353:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8354:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8355:        */
1.136     brouard  8356: {
1.238     brouard  8357:   int i, j, k, ks, v;
1.227     brouard  8358:   int  j1, k1, k2, k3, k4;
1.136     brouard  8359:   char modelsav[80];
1.145     brouard  8360:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8361:   char *strpt;
1.136     brouard  8362: 
1.145     brouard  8363:   /*removespace(model);*/
1.136     brouard  8364:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8365:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8366:     if (strstr(model,"AGE") !=0){
1.192     brouard  8367:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8368:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8369:       return 1;
                   8370:     }
1.141     brouard  8371:     if (strstr(model,"v") !=0){
                   8372:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8373:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8374:       return 1;
                   8375:     }
1.187     brouard  8376:     strcpy(modelsav,model); 
                   8377:     if ((strpt=strstr(model,"age*age")) !=0){
                   8378:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8379:       if(strpt != model){
1.234     brouard  8380:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8381:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8382:  corresponding column of parameters.\n",model);
1.234     brouard  8383:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8384:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8385:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8386:        return 1;
1.225     brouard  8387:       }
1.187     brouard  8388:       nagesqr=1;
                   8389:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8390:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8391:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8392:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8393:       else 
1.234     brouard  8394:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8395:     }else
                   8396:       nagesqr=0;
                   8397:     if (strlen(modelsav) >1){
                   8398:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8399:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8400:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8401:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8402:                     * cst, age and age*age 
                   8403:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8404:       /* including age products which are counted in cptcovage.
                   8405:        * but the covariates which are products must be treated 
                   8406:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8407:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8408:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8409:       
                   8410:       
1.187     brouard  8411:       /*   Design
                   8412:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8413:        *  <          ncovcol=8                >
                   8414:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8415:        *   k=  1    2      3       4     5       6      7        8
                   8416:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8417:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8418:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8419:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8420:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8421:        *  Tage[++cptcovage]=k
                   8422:        *       if products, new covar are created after ncovcol with k1
                   8423:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8424:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8425:        *  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
                   8426:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8427:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8428:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8429:        *  <          ncovcol=8                >
                   8430:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8431:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8432:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8433:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8434:        * p Tprod[1]@2={                         6, 5}
                   8435:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8436:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8437:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8438:        *How to reorganize?
                   8439:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8440:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8441:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8442:        * Struct []
                   8443:        */
1.225     brouard  8444:       
1.187     brouard  8445:       /* This loop fills the array Tvar from the string 'model'.*/
                   8446:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8447:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8448:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8449:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8450:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8451:       /*       k=1 Tvar[1]=2 (from V2) */
                   8452:       /*       k=5 Tvar[5] */
                   8453:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8454:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8455:       /*       } */
1.198     brouard  8456:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8457:       /*
                   8458:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8459:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8460:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8461:       }
1.187     brouard  8462:       cptcovage=0;
                   8463:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8464:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8465:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8466:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8467:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8468:        /*scanf("%d",i);*/
                   8469:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8470:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8471:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8472:            /* covar is not filled and then is empty */
                   8473:            cptcovprod--;
                   8474:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8475:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8476:            Typevar[k]=1;  /* 1 for age product */
                   8477:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8478:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8479:            /*printf("stre=%s ", stre);*/
                   8480:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8481:            cptcovprod--;
                   8482:            cutl(stre,strb,strc,'V');
                   8483:            Tvar[k]=atoi(stre);
                   8484:            Typevar[k]=1;  /* 1 for age product */
                   8485:            cptcovage++;
                   8486:            Tage[cptcovage]=k;
                   8487:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8488:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8489:            cptcovn++;
                   8490:            cptcovprodnoage++;k1++;
                   8491:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8492:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8493:                                                because this model-covariate is a construction we invent a new column
                   8494:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8495:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8496:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8497:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8498:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8499:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8500:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8501:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8502:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8503:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8504:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8505:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8506:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8507:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8508:            for (i=1; i<=lastobs;i++){
                   8509:              /* Computes the new covariate which is a product of
                   8510:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8511:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8512:            }
                   8513:          } /* End age is not in the model */
                   8514:        } /* End if model includes a product */
                   8515:        else { /* no more sum */
                   8516:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8517:          /*  scanf("%d",i);*/
                   8518:          cutl(strd,strc,strb,'V');
                   8519:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8520:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8521:          Tvar[k]=atoi(strd);
                   8522:          Typevar[k]=0;  /* 0 for simple covariates */
                   8523:        }
                   8524:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8525:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8526:                                  scanf("%d",i);*/
1.187     brouard  8527:       } /* end of loop + on total covariates */
                   8528:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8529:   } /* end if strlen(model == 0) */
1.136     brouard  8530:   
                   8531:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8532:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8533:   
1.136     brouard  8534:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8535:      printf("cptcovprod=%d ", cptcovprod);
                   8536:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8537:      scanf("%d ",i);*/
                   8538: 
                   8539: 
1.230     brouard  8540: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8541:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8542: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8543:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8544:    k =           1    2   3     4       5       6      7      8        9
                   8545:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8546:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8547:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8548:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8549:          Tmodelind[combination of covar]=k;
1.225     brouard  8550: */  
                   8551: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8552:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8553:   /* 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  8554:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8555:   printf("Model=%s\n\
                   8556: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8557: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8558: 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);
                   8559:   fprintf(ficlog,"Model=%s\n\
                   8560: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8561: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8562: 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  8563:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8564:   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 */
                   8565:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8566:       Fixed[k]= 0;
                   8567:       Dummy[k]= 0;
1.225     brouard  8568:       ncoveff++;
1.232     brouard  8569:       ncovf++;
1.234     brouard  8570:       nsd++;
                   8571:       modell[k].maintype= FTYPE;
                   8572:       TvarsD[nsd]=Tvar[k];
                   8573:       TvarsDind[nsd]=k;
                   8574:       TvarF[ncovf]=Tvar[k];
                   8575:       TvarFind[ncovf]=k;
                   8576:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8577:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8578:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8579:       Fixed[k]= 0;
                   8580:       Dummy[k]= 0;
                   8581:       ncoveff++;
                   8582:       ncovf++;
                   8583:       modell[k].maintype= FTYPE;
                   8584:       TvarF[ncovf]=Tvar[k];
                   8585:       TvarFind[ncovf]=k;
1.230     brouard  8586:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8587:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8588:     }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  8589:       Fixed[k]= 0;
                   8590:       Dummy[k]= 1;
1.230     brouard  8591:       nqfveff++;
1.234     brouard  8592:       modell[k].maintype= FTYPE;
                   8593:       modell[k].subtype= FQ;
                   8594:       nsq++;
                   8595:       TvarsQ[nsq]=Tvar[k];
                   8596:       TvarsQind[nsq]=k;
1.232     brouard  8597:       ncovf++;
1.234     brouard  8598:       TvarF[ncovf]=Tvar[k];
                   8599:       TvarFind[ncovf]=k;
1.231     brouard  8600:       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  8601:       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  8602:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8603:       Fixed[k]= 1;
                   8604:       Dummy[k]= 0;
1.225     brouard  8605:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8606:       modell[k].maintype= VTYPE;
                   8607:       modell[k].subtype= VD;
                   8608:       nsd++;
                   8609:       TvarsD[nsd]=Tvar[k];
                   8610:       TvarsDind[nsd]=k;
                   8611:       ncovv++; /* Only simple time varying variables */
                   8612:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8613:       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  8614:       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 */
                   8615:       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  8616:       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);
                   8617:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8618:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8619:       Fixed[k]= 1;
                   8620:       Dummy[k]= 1;
                   8621:       nqtveff++;
                   8622:       modell[k].maintype= VTYPE;
                   8623:       modell[k].subtype= VQ;
                   8624:       ncovv++; /* Only simple time varying variables */
                   8625:       nsq++;
                   8626:       TvarsQ[nsq]=Tvar[k];
                   8627:       TvarsQind[nsq]=k;
                   8628:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8629:       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  8630:       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 */
                   8631:       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  8632:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8633:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8634:       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  8635:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8636:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8637:       ncova++;
                   8638:       TvarA[ncova]=Tvar[k];
                   8639:       TvarAind[ncova]=k;
1.231     brouard  8640:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8641:        Fixed[k]= 2;
                   8642:        Dummy[k]= 2;
                   8643:        modell[k].maintype= ATYPE;
                   8644:        modell[k].subtype= APFD;
                   8645:        /* ncoveff++; */
1.227     brouard  8646:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8647:        Fixed[k]= 2;
                   8648:        Dummy[k]= 3;
                   8649:        modell[k].maintype= ATYPE;
                   8650:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8651:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8652:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8653:        Fixed[k]= 3;
                   8654:        Dummy[k]= 2;
                   8655:        modell[k].maintype= ATYPE;
                   8656:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8657:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8658:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8659:        Fixed[k]= 3;
                   8660:        Dummy[k]= 3;
                   8661:        modell[k].maintype= ATYPE;
                   8662:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8663:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8664:       }
                   8665:     }else if (Typevar[k] == 2) {  /* product without age */
                   8666:       k1=Tposprod[k];
                   8667:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8668:        if(Tvard[k1][2] <=ncovcol){
                   8669:          Fixed[k]= 1;
                   8670:          Dummy[k]= 0;
                   8671:          modell[k].maintype= FTYPE;
                   8672:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8673:          ncovf++; /* Fixed variables without age */
                   8674:          TvarF[ncovf]=Tvar[k];
                   8675:          TvarFind[ncovf]=k;
                   8676:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8677:          Fixed[k]= 0;  /* or 2 ?*/
                   8678:          Dummy[k]= 1;
                   8679:          modell[k].maintype= FTYPE;
                   8680:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8681:          ncovf++; /* Varying variables without age */
                   8682:          TvarF[ncovf]=Tvar[k];
                   8683:          TvarFind[ncovf]=k;
                   8684:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8685:          Fixed[k]= 1;
                   8686:          Dummy[k]= 0;
                   8687:          modell[k].maintype= VTYPE;
                   8688:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8689:          ncovv++; /* Varying variables without age */
                   8690:          TvarV[ncovv]=Tvar[k];
                   8691:          TvarVind[ncovv]=k;
                   8692:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8693:          Fixed[k]= 1;
                   8694:          Dummy[k]= 1;
                   8695:          modell[k].maintype= VTYPE;
                   8696:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8697:          ncovv++; /* Varying variables without age */
                   8698:          TvarV[ncovv]=Tvar[k];
                   8699:          TvarVind[ncovv]=k;
                   8700:        }
1.227     brouard  8701:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8702:        if(Tvard[k1][2] <=ncovcol){
                   8703:          Fixed[k]= 0;  /* or 2 ?*/
                   8704:          Dummy[k]= 1;
                   8705:          modell[k].maintype= FTYPE;
                   8706:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8707:          ncovf++; /* Fixed variables without age */
                   8708:          TvarF[ncovf]=Tvar[k];
                   8709:          TvarFind[ncovf]=k;
                   8710:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8711:          Fixed[k]= 1;
                   8712:          Dummy[k]= 1;
                   8713:          modell[k].maintype= VTYPE;
                   8714:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8715:          ncovv++; /* Varying variables without age */
                   8716:          TvarV[ncovv]=Tvar[k];
                   8717:          TvarVind[ncovv]=k;
                   8718:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8719:          Fixed[k]= 1;
                   8720:          Dummy[k]= 1;
                   8721:          modell[k].maintype= VTYPE;
                   8722:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8723:          ncovv++; /* Varying variables without age */
                   8724:          TvarV[ncovv]=Tvar[k];
                   8725:          TvarVind[ncovv]=k;
                   8726:          ncovv++; /* Varying variables without age */
                   8727:          TvarV[ncovv]=Tvar[k];
                   8728:          TvarVind[ncovv]=k;
                   8729:        }
1.227     brouard  8730:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8731:        if(Tvard[k1][2] <=ncovcol){
                   8732:          Fixed[k]= 1;
                   8733:          Dummy[k]= 1;
                   8734:          modell[k].maintype= VTYPE;
                   8735:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8736:          ncovv++; /* Varying variables without age */
                   8737:          TvarV[ncovv]=Tvar[k];
                   8738:          TvarVind[ncovv]=k;
                   8739:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8740:          Fixed[k]= 1;
                   8741:          Dummy[k]= 1;
                   8742:          modell[k].maintype= VTYPE;
                   8743:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8744:          ncovv++; /* Varying variables without age */
                   8745:          TvarV[ncovv]=Tvar[k];
                   8746:          TvarVind[ncovv]=k;
                   8747:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8748:          Fixed[k]= 1;
                   8749:          Dummy[k]= 0;
                   8750:          modell[k].maintype= VTYPE;
                   8751:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8752:          ncovv++; /* Varying variables without age */
                   8753:          TvarV[ncovv]=Tvar[k];
                   8754:          TvarVind[ncovv]=k;
                   8755:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8756:          Fixed[k]= 1;
                   8757:          Dummy[k]= 1;
                   8758:          modell[k].maintype= VTYPE;
                   8759:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8760:          ncovv++; /* Varying variables without age */
                   8761:          TvarV[ncovv]=Tvar[k];
                   8762:          TvarVind[ncovv]=k;
                   8763:        }
1.227     brouard  8764:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8765:        if(Tvard[k1][2] <=ncovcol){
                   8766:          Fixed[k]= 1;
                   8767:          Dummy[k]= 1;
                   8768:          modell[k].maintype= VTYPE;
                   8769:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8770:          ncovv++; /* Varying variables without age */
                   8771:          TvarV[ncovv]=Tvar[k];
                   8772:          TvarVind[ncovv]=k;
                   8773:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8774:          Fixed[k]= 1;
                   8775:          Dummy[k]= 1;
                   8776:          modell[k].maintype= VTYPE;
                   8777:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8778:          ncovv++; /* Varying variables without age */
                   8779:          TvarV[ncovv]=Tvar[k];
                   8780:          TvarVind[ncovv]=k;
                   8781:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8782:          Fixed[k]= 1;
                   8783:          Dummy[k]= 1;
                   8784:          modell[k].maintype= VTYPE;
                   8785:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8786:          ncovv++; /* Varying variables without age */
                   8787:          TvarV[ncovv]=Tvar[k];
                   8788:          TvarVind[ncovv]=k;
                   8789:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8790:          Fixed[k]= 1;
                   8791:          Dummy[k]= 1;
                   8792:          modell[k].maintype= VTYPE;
                   8793:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8794:          ncovv++; /* Varying variables without age */
                   8795:          TvarV[ncovv]=Tvar[k];
                   8796:          TvarVind[ncovv]=k;
                   8797:        }
1.227     brouard  8798:       }else{
1.240     brouard  8799:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8800:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8801:       } /*end k1*/
1.225     brouard  8802:     }else{
1.226     brouard  8803:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8804:       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  8805:     }
1.227     brouard  8806:     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  8807:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8808:     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]);
                   8809:   }
                   8810:   /* Searching for doublons in the model */
                   8811:   for(k1=1; k1<= cptcovt;k1++){
                   8812:     for(k2=1; k2 <k1;k2++){
                   8813:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8814:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8815:          if(Tvar[k1]==Tvar[k2]){
                   8816:            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]]);
                   8817:            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);
                   8818:            return(1);
                   8819:          }
                   8820:        }else if (Typevar[k1] ==2){
                   8821:          k3=Tposprod[k1];
                   8822:          k4=Tposprod[k2];
                   8823:          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])) ){
                   8824:            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]]);
                   8825:            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);
                   8826:            return(1);
                   8827:          }
                   8828:        }
1.227     brouard  8829:       }
                   8830:     }
1.225     brouard  8831:   }
                   8832:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8833:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8834:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8835:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8836:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8837:   /*endread:*/
1.225     brouard  8838:   printf("Exiting decodemodel: ");
                   8839:   return (1);
1.136     brouard  8840: }
                   8841: 
1.169     brouard  8842: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8843: {
                   8844:   int i, m;
1.218     brouard  8845:   int firstone=0;
                   8846:   
1.136     brouard  8847:   for (i=1; i<=imx; i++) {
                   8848:     for(m=2; (m<= maxwav); m++) {
                   8849:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8850:        anint[m][i]=9999;
1.216     brouard  8851:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8852:          s[m][i]=-1;
1.136     brouard  8853:       }
                   8854:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8855:        *nberr = *nberr + 1;
1.218     brouard  8856:        if(firstone == 0){
                   8857:          firstone=1;
                   8858:        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);
                   8859:        }
                   8860:        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  8861:        s[m][i]=-1;
                   8862:       }
                   8863:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8864:        (*nberr)++;
1.136     brouard  8865:        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]); 
                   8866:        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]); 
                   8867:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8868:       }
                   8869:     }
                   8870:   }
                   8871: 
                   8872:   for (i=1; i<=imx; i++)  {
                   8873:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8874:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8875:       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  8876:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8877:          if(agedc[i]>0){
                   8878:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8879:              agev[m][i]=agedc[i];
1.214     brouard  8880:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8881:            }else {
1.136     brouard  8882:              if ((int)andc[i]!=9999){
                   8883:                nbwarn++;
                   8884:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8885:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8886:                agev[m][i]=-1;
                   8887:              }
                   8888:            }
1.169     brouard  8889:          } /* agedc > 0 */
1.214     brouard  8890:        } /* end if */
1.136     brouard  8891:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8892:                                 years but with the precision of a month */
                   8893:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8894:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8895:            agev[m][i]=1;
                   8896:          else if(agev[m][i] < *agemin){ 
                   8897:            *agemin=agev[m][i];
                   8898:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8899:          }
                   8900:          else if(agev[m][i] >*agemax){
                   8901:            *agemax=agev[m][i];
1.156     brouard  8902:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8903:          }
                   8904:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8905:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8906:        } /* en if 9*/
1.136     brouard  8907:        else { /* =9 */
1.214     brouard  8908:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8909:          agev[m][i]=1;
                   8910:          s[m][i]=-1;
                   8911:        }
                   8912:       }
1.214     brouard  8913:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8914:        agev[m][i]=1;
1.214     brouard  8915:       else{
                   8916:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8917:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8918:        agev[m][i]=0;
                   8919:       }
                   8920:     } /* End for lastpass */
                   8921:   }
1.136     brouard  8922:     
                   8923:   for (i=1; i<=imx; i++)  {
                   8924:     for(m=firstpass; (m<=lastpass); m++){
                   8925:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8926:        (*nberr)++;
1.136     brouard  8927:        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);     
                   8928:        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);     
                   8929:        return 1;
                   8930:       }
                   8931:     }
                   8932:   }
                   8933: 
                   8934:   /*for (i=1; i<=imx; i++){
                   8935:   for (m=firstpass; (m<lastpass); m++){
                   8936:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8937: }
                   8938: 
                   8939: }*/
                   8940: 
                   8941: 
1.139     brouard  8942:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8943:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8944: 
                   8945:   return (0);
1.164     brouard  8946:  /* endread:*/
1.136     brouard  8947:     printf("Exiting calandcheckages: ");
                   8948:     return (1);
                   8949: }
                   8950: 
1.172     brouard  8951: #if defined(_MSC_VER)
                   8952: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8953: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8954: //#include "stdafx.h"
                   8955: //#include <stdio.h>
                   8956: //#include <tchar.h>
                   8957: //#include <windows.h>
                   8958: //#include <iostream>
                   8959: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8960: 
                   8961: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8962: 
                   8963: BOOL IsWow64()
                   8964: {
                   8965:        BOOL bIsWow64 = FALSE;
                   8966: 
                   8967:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8968:        //  (HANDLE, PBOOL);
                   8969: 
                   8970:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8971: 
                   8972:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8973:        const char funcName[] = "IsWow64Process";
                   8974:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8975:                GetProcAddress(module, funcName);
                   8976: 
                   8977:        if (NULL != fnIsWow64Process)
                   8978:        {
                   8979:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8980:                        &bIsWow64))
                   8981:                        //throw std::exception("Unknown error");
                   8982:                        printf("Unknown error\n");
                   8983:        }
                   8984:        return bIsWow64 != FALSE;
                   8985: }
                   8986: #endif
1.177     brouard  8987: 
1.191     brouard  8988: void syscompilerinfo(int logged)
1.167     brouard  8989:  {
                   8990:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8991:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8992:    /* /GS /W3 /Gy
                   8993:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8994:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8995:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8996:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8997:    */ 
                   8998:    /* 64 bits */
1.185     brouard  8999:    /*
                   9000:      /GS /W3 /Gy
                   9001:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   9002:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   9003:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   9004:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   9005:    /* Optimization are useless and O3 is slower than O2 */
                   9006:    /*
                   9007:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   9008:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   9009:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   9010:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   9011:    */
1.186     brouard  9012:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  9013:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   9014:       /PDB:"visual studio
                   9015:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   9016:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   9017:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   9018:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   9019:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   9020:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   9021:       uiAccess='false'"
                   9022:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   9023:       /NOLOGO /TLBID:1
                   9024:    */
1.177     brouard  9025: #if defined __INTEL_COMPILER
1.178     brouard  9026: #if defined(__GNUC__)
                   9027:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9028: #endif
1.177     brouard  9029: #elif defined(__GNUC__) 
1.179     brouard  9030: #ifndef  __APPLE__
1.174     brouard  9031: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9032: #endif
1.177     brouard  9033:    struct utsname sysInfo;
1.178     brouard  9034:    int cross = CROSS;
                   9035:    if (cross){
                   9036:           printf("Cross-");
1.191     brouard  9037:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9038:    }
1.174     brouard  9039: #endif
                   9040: 
1.171     brouard  9041: #include <stdint.h>
1.178     brouard  9042: 
1.191     brouard  9043:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9044: #if defined(__clang__)
1.191     brouard  9045:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9046: #endif
                   9047: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9048:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9049: #endif
                   9050: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9051:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9052: #endif
                   9053: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9054:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9055: #endif
                   9056: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9057:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9058: #endif
                   9059: #if defined(_MSC_VER)
1.191     brouard  9060:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9061: #endif
                   9062: #if defined(__PGI)
1.191     brouard  9063:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9064: #endif
                   9065: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9066:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9067: #endif
1.191     brouard  9068:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9069:    
1.167     brouard  9070: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9071: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9072:     // Windows (x64 and x86)
1.191     brouard  9073:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9074: #elif __unix__ // all unices, not all compilers
                   9075:     // Unix
1.191     brouard  9076:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9077: #elif __linux__
                   9078:     // linux
1.191     brouard  9079:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9080: #elif __APPLE__
1.174     brouard  9081:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9082:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9083: #endif
                   9084: 
                   9085: /*  __MINGW32__          */
                   9086: /*  __CYGWIN__  */
                   9087: /* __MINGW64__  */
                   9088: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9089: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9090: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9091: /* _WIN64  // Defined for applications for Win64. */
                   9092: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9093: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9094: 
1.167     brouard  9095: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9096:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9097: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9098:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9099: #else
1.191     brouard  9100:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9101: #endif
                   9102: 
1.169     brouard  9103: #if defined(__GNUC__)
                   9104: # if defined(__GNUC_PATCHLEVEL__)
                   9105: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9106:                             + __GNUC_MINOR__ * 100 \
                   9107:                             + __GNUC_PATCHLEVEL__)
                   9108: # else
                   9109: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9110:                             + __GNUC_MINOR__ * 100)
                   9111: # endif
1.174     brouard  9112:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9113:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9114: 
                   9115:    if (uname(&sysInfo) != -1) {
                   9116:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9117:         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  9118:    }
                   9119:    else
                   9120:       perror("uname() error");
1.179     brouard  9121:    //#ifndef __INTEL_COMPILER 
                   9122: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9123:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9124:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9125: #endif
1.169     brouard  9126: #endif
1.172     brouard  9127: 
                   9128:    //   void main()
                   9129:    //   {
1.169     brouard  9130: #if defined(_MSC_VER)
1.174     brouard  9131:    if (IsWow64()){
1.191     brouard  9132:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9133:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9134:    }
                   9135:    else{
1.191     brouard  9136:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9137:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9138:    }
1.172     brouard  9139:    //     printf("\nPress Enter to continue...");
                   9140:    //     getchar();
                   9141:    //   }
                   9142: 
1.169     brouard  9143: #endif
                   9144:    
1.167     brouard  9145: 
1.219     brouard  9146: }
1.136     brouard  9147: 
1.219     brouard  9148: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9149:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9150:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9151:   /* double ftolpl = 1.e-10; */
1.180     brouard  9152:   double age, agebase, agelim;
1.203     brouard  9153:   double tot;
1.180     brouard  9154: 
1.202     brouard  9155:   strcpy(filerespl,"PL_");
                   9156:   strcat(filerespl,fileresu);
                   9157:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9158:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9159:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9160:   }
1.227     brouard  9161:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9162:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9163:   pstamp(ficrespl);
1.203     brouard  9164:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9165:   fprintf(ficrespl,"#Age ");
                   9166:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9167:   fprintf(ficrespl,"\n");
1.180     brouard  9168:   
1.219     brouard  9169:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9170: 
1.219     brouard  9171:   agebase=ageminpar;
                   9172:   agelim=agemaxpar;
1.180     brouard  9173: 
1.227     brouard  9174:   /* i1=pow(2,ncoveff); */
1.234     brouard  9175:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9176:   if (cptcovn < 1){i1=1;}
1.180     brouard  9177: 
1.238     brouard  9178:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9179:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9180:       if(TKresult[nres]!= k)
                   9181:        continue;
1.235     brouard  9182: 
1.238     brouard  9183:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9184:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9185:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9186:       /* k=k+1; */
                   9187:       /* to clean */
                   9188:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9189:       fprintf(ficrespl,"#******");
                   9190:       printf("#******");
                   9191:       fprintf(ficlog,"#******");
                   9192:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9193:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9194:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9195:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9196:       }
                   9197:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9198:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9199:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9200:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9201:       }
                   9202:       fprintf(ficrespl,"******\n");
                   9203:       printf("******\n");
                   9204:       fprintf(ficlog,"******\n");
                   9205:       if(invalidvarcomb[k]){
                   9206:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9207:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9208:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9209:        continue;
                   9210:       }
1.219     brouard  9211: 
1.238     brouard  9212:       fprintf(ficrespl,"#Age ");
                   9213:       for(j=1;j<=cptcoveff;j++) {
                   9214:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9215:       }
                   9216:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9217:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9218:     
1.238     brouard  9219:       for (age=agebase; age<=agelim; age++){
                   9220:        /* for (age=agebase; age<=agebase; age++){ */
                   9221:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9222:        fprintf(ficrespl,"%.0f ",age );
                   9223:        for(j=1;j<=cptcoveff;j++)
                   9224:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9225:        tot=0.;
                   9226:        for(i=1; i<=nlstate;i++){
                   9227:          tot +=  prlim[i][i];
                   9228:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9229:        }
                   9230:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9231:       } /* Age */
                   9232:       /* was end of cptcod */
                   9233:     } /* cptcov */
                   9234:   } /* nres */
1.219     brouard  9235:   return 0;
1.180     brouard  9236: }
                   9237: 
1.218     brouard  9238: 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){
                   9239:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9240:        
                   9241:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9242:    * at any age between ageminpar and agemaxpar
                   9243:         */
1.235     brouard  9244:   int i, j, k, i1, nres=0 ;
1.217     brouard  9245:   /* double ftolpl = 1.e-10; */
                   9246:   double age, agebase, agelim;
                   9247:   double tot;
1.218     brouard  9248:   /* double ***mobaverage; */
                   9249:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9250: 
                   9251:   strcpy(fileresplb,"PLB_");
                   9252:   strcat(fileresplb,fileresu);
                   9253:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9254:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9255:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9256:   }
                   9257:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9258:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9259:   pstamp(ficresplb);
                   9260:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9261:   fprintf(ficresplb,"#Age ");
                   9262:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9263:   fprintf(ficresplb,"\n");
                   9264:   
1.218     brouard  9265:   
                   9266:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9267:   
                   9268:   agebase=ageminpar;
                   9269:   agelim=agemaxpar;
                   9270:   
                   9271:   
1.227     brouard  9272:   i1=pow(2,cptcoveff);
1.218     brouard  9273:   if (cptcovn < 1){i1=1;}
1.227     brouard  9274:   
1.238     brouard  9275:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9276:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9277:       if(TKresult[nres]!= k)
                   9278:        continue;
                   9279:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9280:       fprintf(ficresplb,"#******");
                   9281:       printf("#******");
                   9282:       fprintf(ficlog,"#******");
                   9283:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9284:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9285:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9286:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9287:       }
                   9288:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9289:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9290:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9291:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9292:       }
                   9293:       fprintf(ficresplb,"******\n");
                   9294:       printf("******\n");
                   9295:       fprintf(ficlog,"******\n");
                   9296:       if(invalidvarcomb[k]){
                   9297:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9298:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9299:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9300:        continue;
                   9301:       }
1.218     brouard  9302:     
1.238     brouard  9303:       fprintf(ficresplb,"#Age ");
                   9304:       for(j=1;j<=cptcoveff;j++) {
                   9305:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9306:       }
                   9307:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9308:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9309:     
                   9310:     
1.238     brouard  9311:       for (age=agebase; age<=agelim; age++){
                   9312:        /* for (age=agebase; age<=agebase; age++){ */
                   9313:        if(mobilavproj > 0){
                   9314:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9315:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9316:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9317:        }else if (mobilavproj == 0){
                   9318:          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);
                   9319:          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);
                   9320:          exit(1);
                   9321:        }else{
                   9322:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9323:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9324:        }
                   9325:        fprintf(ficresplb,"%.0f ",age );
                   9326:        for(j=1;j<=cptcoveff;j++)
                   9327:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9328:        tot=0.;
                   9329:        for(i=1; i<=nlstate;i++){
                   9330:          tot +=  bprlim[i][i];
                   9331:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9332:        }
                   9333:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9334:       } /* Age */
                   9335:       /* was end of cptcod */
                   9336:     } /* end of any combination */
                   9337:   } /* end of nres */  
1.218     brouard  9338:   /* hBijx(p, bage, fage); */
                   9339:   /* fclose(ficrespijb); */
                   9340:   
                   9341:   return 0;
1.217     brouard  9342: }
1.218     brouard  9343:  
1.180     brouard  9344: int hPijx(double *p, int bage, int fage){
                   9345:     /*------------- h Pij x at various ages ------------*/
                   9346: 
                   9347:   int stepsize;
                   9348:   int agelim;
                   9349:   int hstepm;
                   9350:   int nhstepm;
1.235     brouard  9351:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9352: 
                   9353:   double agedeb;
                   9354:   double ***p3mat;
                   9355: 
1.201     brouard  9356:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9357:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9358:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9359:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9360:     }
                   9361:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9362:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9363:   
                   9364:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9365:     /*if (stepm<=24) stepsize=2;*/
                   9366: 
                   9367:     agelim=AGESUP;
                   9368:     hstepm=stepsize*YEARM; /* Every year of age */
                   9369:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9370:                
1.180     brouard  9371:     /* hstepm=1;   aff par mois*/
                   9372:     pstamp(ficrespij);
                   9373:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9374:     i1= pow(2,cptcoveff);
1.218     brouard  9375:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9376:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9377:                /*      k=k+1;  */
1.235     brouard  9378:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9379:     for(k=1; k<=i1;k++){
                   9380:       if(TKresult[nres]!= k)
                   9381:        continue;
1.183     brouard  9382:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9383:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9384:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9385:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9386:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9387:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9388:       }
1.183     brouard  9389:       fprintf(ficrespij,"******\n");
                   9390:       
                   9391:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9392:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9393:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9394:        
                   9395:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9396:        
1.183     brouard  9397:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9398:        oldm=oldms;savm=savms;
1.235     brouard  9399:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9400:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9401:        for(i=1; i<=nlstate;i++)
                   9402:          for(j=1; j<=nlstate+ndeath;j++)
                   9403:            fprintf(ficrespij," %1d-%1d",i,j);
                   9404:        fprintf(ficrespij,"\n");
                   9405:        for (h=0; h<=nhstepm; h++){
                   9406:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9407:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9408:          for(i=1; i<=nlstate;i++)
                   9409:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9410:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9411:          fprintf(ficrespij,"\n");
                   9412:        }
1.183     brouard  9413:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9414:        fprintf(ficrespij,"\n");
                   9415:       }
1.180     brouard  9416:       /*}*/
                   9417:     }
1.218     brouard  9418:     return 0;
1.180     brouard  9419: }
1.218     brouard  9420:  
                   9421:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9422:     /*------------- h Bij x at various ages ------------*/
                   9423: 
                   9424:   int stepsize;
1.218     brouard  9425:   /* int agelim; */
                   9426:        int ageminl;
1.217     brouard  9427:   int hstepm;
                   9428:   int nhstepm;
1.238     brouard  9429:   int h, i, i1, j, k, nres;
1.218     brouard  9430:        
1.217     brouard  9431:   double agedeb;
                   9432:   double ***p3mat;
1.218     brouard  9433:        
                   9434:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9435:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9436:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9437:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9438:   }
                   9439:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9440:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9441:   
                   9442:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9443:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9444:   
1.218     brouard  9445:   /* agelim=AGESUP; */
                   9446:   ageminl=30;
                   9447:   hstepm=stepsize*YEARM; /* Every year of age */
                   9448:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9449:   
                   9450:   /* hstepm=1;   aff par mois*/
                   9451:   pstamp(ficrespijb);
                   9452:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9453:   i1= pow(2,cptcoveff);
1.218     brouard  9454:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9455:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9456:   /*   k=k+1;  */
1.238     brouard  9457:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9458:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9459:       if(TKresult[nres]!= k)
                   9460:        continue;
                   9461:       fprintf(ficrespijb,"\n#****** ");
                   9462:       for(j=1;j<=cptcoveff;j++)
                   9463:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9464:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9465:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9466:       }
                   9467:       fprintf(ficrespijb,"******\n");
                   9468:       if(invalidvarcomb[k]){
                   9469:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9470:        continue;
                   9471:       }
                   9472:       
                   9473:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9474:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9475:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9476:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9477:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9478:        
                   9479:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9480:        
                   9481:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9482:        /* oldm=oldms;savm=savms; */
                   9483:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9484:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9485:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9486:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9487:        for(i=1; i<=nlstate;i++)
                   9488:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9489:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9490:        fprintf(ficrespijb,"\n");
1.238     brouard  9491:        for (h=0; h<=nhstepm; h++){
                   9492:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9493:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9494:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9495:          for(i=1; i<=nlstate;i++)
                   9496:            for(j=1; j<=nlstate+ndeath;j++)
                   9497:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9498:          fprintf(ficrespijb,"\n");
                   9499:        }
                   9500:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9501:        fprintf(ficrespijb,"\n");
                   9502:       } /* end age deb */
                   9503:     } /* end combination */
                   9504:   } /* end nres */
1.218     brouard  9505:   return 0;
                   9506:  } /*  hBijx */
1.217     brouard  9507: 
1.180     brouard  9508: 
1.136     brouard  9509: /***********************************************/
                   9510: /**************** Main Program *****************/
                   9511: /***********************************************/
                   9512: 
                   9513: int main(int argc, char *argv[])
                   9514: {
                   9515: #ifdef GSL
                   9516:   const gsl_multimin_fminimizer_type *T;
                   9517:   size_t iteri = 0, it;
                   9518:   int rval = GSL_CONTINUE;
                   9519:   int status = GSL_SUCCESS;
                   9520:   double ssval;
                   9521: #endif
                   9522:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9523:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9524:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9525:   int jj, ll, li, lj, lk;
1.136     brouard  9526:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9527:   int num_filled;
1.136     brouard  9528:   int itimes;
                   9529:   int NDIM=2;
                   9530:   int vpopbased=0;
1.235     brouard  9531:   int nres=0;
1.136     brouard  9532: 
1.164     brouard  9533:   char ca[32], cb[32];
1.136     brouard  9534:   /*  FILE *fichtm; *//* Html File */
                   9535:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9536:   struct stat info;
1.191     brouard  9537:   double agedeb=0.;
1.194     brouard  9538: 
                   9539:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9540:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9541: 
1.165     brouard  9542:   double fret;
1.191     brouard  9543:   double dum=0.; /* Dummy variable */
1.136     brouard  9544:   double ***p3mat;
1.218     brouard  9545:   /* double ***mobaverage; */
1.164     brouard  9546: 
                   9547:   char line[MAXLINE];
1.197     brouard  9548:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9549: 
1.234     brouard  9550:   char  modeltemp[MAXLINE];
1.230     brouard  9551:   char resultline[MAXLINE];
                   9552:   
1.136     brouard  9553:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9554:   char *tok, *val; /* pathtot */
1.136     brouard  9555:   int firstobs=1, lastobs=10;
1.195     brouard  9556:   int c,  h , cpt, c2;
1.191     brouard  9557:   int jl=0;
                   9558:   int i1, j1, jk, stepsize=0;
1.194     brouard  9559:   int count=0;
                   9560: 
1.164     brouard  9561:   int *tab; 
1.136     brouard  9562:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9563:   int backcast=0;
1.136     brouard  9564:   int mobilav=0,popforecast=0;
1.191     brouard  9565:   int hstepm=0, nhstepm=0;
1.136     brouard  9566:   int agemortsup;
                   9567:   float  sumlpop=0.;
                   9568:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9569:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9570: 
1.191     brouard  9571:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9572:   double ftolpl=FTOL;
                   9573:   double **prlim;
1.217     brouard  9574:   double **bprlim;
1.136     brouard  9575:   double ***param; /* Matrix of parameters */
                   9576:   double  *p;
                   9577:   double **matcov; /* Matrix of covariance */
1.203     brouard  9578:   double **hess; /* Hessian matrix */
1.136     brouard  9579:   double ***delti3; /* Scale */
                   9580:   double *delti; /* Scale */
                   9581:   double ***eij, ***vareij;
                   9582:   double **varpl; /* Variances of prevalence limits by age */
                   9583:   double *epj, vepp;
1.164     brouard  9584: 
1.136     brouard  9585:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9586:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9587: 
1.136     brouard  9588:   double **ximort;
1.145     brouard  9589:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9590:   int *dcwave;
                   9591: 
1.164     brouard  9592:   char z[1]="c";
1.136     brouard  9593: 
                   9594:   /*char  *strt;*/
                   9595:   char strtend[80];
1.126     brouard  9596: 
1.164     brouard  9597: 
1.126     brouard  9598: /*   setlocale (LC_ALL, ""); */
                   9599: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9600: /*   textdomain (PACKAGE); */
                   9601: /*   setlocale (LC_CTYPE, ""); */
                   9602: /*   setlocale (LC_MESSAGES, ""); */
                   9603: 
                   9604:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9605:   rstart_time = time(NULL);  
                   9606:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9607:   start_time = *localtime(&rstart_time);
1.126     brouard  9608:   curr_time=start_time;
1.157     brouard  9609:   /*tml = *localtime(&start_time.tm_sec);*/
                   9610:   /* strcpy(strstart,asctime(&tml)); */
                   9611:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9612: 
                   9613: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9614: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9615: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9616: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9617: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9618: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9619: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9620: /*   strt=asctime(&tmg); */
                   9621: /*   printf("Time(after) =%s",strstart);  */
                   9622: /*  (void) time (&time_value);
                   9623: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9624: *  tm = *localtime(&time_value);
                   9625: *  strstart=asctime(&tm);
                   9626: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9627: */
                   9628: 
                   9629:   nberr=0; /* Number of errors and warnings */
                   9630:   nbwarn=0;
1.184     brouard  9631: #ifdef WIN32
                   9632:   _getcwd(pathcd, size);
                   9633: #else
1.126     brouard  9634:   getcwd(pathcd, size);
1.184     brouard  9635: #endif
1.191     brouard  9636:   syscompilerinfo(0);
1.196     brouard  9637:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9638:   if(argc <=1){
                   9639:     printf("\nEnter the parameter file name: ");
1.205     brouard  9640:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9641:       printf("ERROR Empty parameter file name\n");
                   9642:       goto end;
                   9643:     }
1.126     brouard  9644:     i=strlen(pathr);
                   9645:     if(pathr[i-1]=='\n')
                   9646:       pathr[i-1]='\0';
1.156     brouard  9647:     i=strlen(pathr);
1.205     brouard  9648:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9649:       pathr[i-1]='\0';
1.205     brouard  9650:     }
                   9651:     i=strlen(pathr);
                   9652:     if( i==0 ){
                   9653:       printf("ERROR Empty parameter file name\n");
                   9654:       goto end;
                   9655:     }
                   9656:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9657:       printf("Pathr |%s|\n",pathr);
                   9658:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9659:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9660:       strcpy (pathtot, val);
                   9661:       if(pathr[0] == '\0') break; /* Dirty */
                   9662:     }
                   9663:   }
                   9664:   else{
                   9665:     strcpy(pathtot,argv[1]);
                   9666:   }
                   9667:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9668:   /*cygwin_split_path(pathtot,path,optionfile);
                   9669:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9670:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9671: 
                   9672:   /* Split argv[0], imach program to get pathimach */
                   9673:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9674:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9675:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9676:  /*   strcpy(pathimach,argv[0]); */
                   9677:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9678:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9679:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9680: #ifdef WIN32
                   9681:   _chdir(path); /* Can be a relative path */
                   9682:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9683: #else
1.126     brouard  9684:   chdir(path); /* Can be a relative path */
1.184     brouard  9685:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9686: #endif
                   9687:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9688:   strcpy(command,"mkdir ");
                   9689:   strcat(command,optionfilefiname);
                   9690:   if((outcmd=system(command)) != 0){
1.169     brouard  9691:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9692:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9693:     /* fclose(ficlog); */
                   9694: /*     exit(1); */
                   9695:   }
                   9696: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9697: /*     perror("mkdir"); */
                   9698: /*   } */
                   9699: 
                   9700:   /*-------- arguments in the command line --------*/
                   9701: 
1.186     brouard  9702:   /* Main Log file */
1.126     brouard  9703:   strcat(filelog, optionfilefiname);
                   9704:   strcat(filelog,".log");    /* */
                   9705:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9706:     printf("Problem with logfile %s\n",filelog);
                   9707:     goto end;
                   9708:   }
                   9709:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9710:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9711:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9712:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9713:  path=%s \n\
                   9714:  optionfile=%s\n\
                   9715:  optionfilext=%s\n\
1.156     brouard  9716:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9717: 
1.197     brouard  9718:   syscompilerinfo(1);
1.167     brouard  9719: 
1.126     brouard  9720:   printf("Local time (at start):%s",strstart);
                   9721:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9722:   fflush(ficlog);
                   9723: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9724: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9725: 
                   9726:   /* */
                   9727:   strcpy(fileres,"r");
                   9728:   strcat(fileres, optionfilefiname);
1.201     brouard  9729:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9730:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9731:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9732: 
1.186     brouard  9733:   /* Main ---------arguments file --------*/
1.126     brouard  9734: 
                   9735:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9736:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9737:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9738:     fflush(ficlog);
1.149     brouard  9739:     /* goto end; */
                   9740:     exit(70); 
1.126     brouard  9741:   }
                   9742: 
                   9743: 
                   9744: 
                   9745:   strcpy(filereso,"o");
1.201     brouard  9746:   strcat(filereso,fileresu);
1.126     brouard  9747:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9748:     printf("Problem with Output resultfile: %s\n", filereso);
                   9749:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9750:     fflush(ficlog);
                   9751:     goto end;
                   9752:   }
                   9753: 
                   9754:   /* Reads comments: lines beginning with '#' */
                   9755:   numlinepar=0;
1.197     brouard  9756: 
                   9757:     /* First parameter line */
                   9758:   while(fgets(line, MAXLINE, ficpar)) {
                   9759:     /* If line starts with a # it is a comment */
                   9760:     if (line[0] == '#') {
                   9761:       numlinepar++;
                   9762:       fputs(line,stdout);
                   9763:       fputs(line,ficparo);
                   9764:       fputs(line,ficlog);
                   9765:       continue;
                   9766:     }else
                   9767:       break;
                   9768:   }
                   9769:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9770:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9771:     if (num_filled != 5) {
                   9772:       printf("Should be 5 parameters\n");
                   9773:     }
1.126     brouard  9774:     numlinepar++;
1.197     brouard  9775:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9776:   }
                   9777:   /* Second parameter line */
                   9778:   while(fgets(line, MAXLINE, ficpar)) {
                   9779:     /* If line starts with a # it is a comment */
                   9780:     if (line[0] == '#') {
                   9781:       numlinepar++;
                   9782:       fputs(line,stdout);
                   9783:       fputs(line,ficparo);
                   9784:       fputs(line,ficlog);
                   9785:       continue;
                   9786:     }else
                   9787:       break;
                   9788:   }
1.223     brouard  9789:   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", \
                   9790:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9791:     if (num_filled != 11) {
                   9792:       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  9793:       printf("but line=%s\n",line);
1.197     brouard  9794:     }
1.223     brouard  9795:     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  9796:   }
1.203     brouard  9797:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9798:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9799:   /* Third parameter line */
                   9800:   while(fgets(line, MAXLINE, ficpar)) {
                   9801:     /* If line starts with a # it is a comment */
                   9802:     if (line[0] == '#') {
                   9803:       numlinepar++;
                   9804:       fputs(line,stdout);
                   9805:       fputs(line,ficparo);
                   9806:       fputs(line,ficlog);
                   9807:       continue;
                   9808:     }else
                   9809:       break;
                   9810:   }
1.201     brouard  9811:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9812:     if (num_filled == 0)
                   9813:             model[0]='\0';
                   9814:     else if (num_filled != 1){
1.197     brouard  9815:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9816:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9817:       model[0]='\0';
                   9818:       goto end;
                   9819:     }
                   9820:     else{
                   9821:       if (model[0]=='+'){
                   9822:        for(i=1; i<=strlen(model);i++)
                   9823:          modeltemp[i-1]=model[i];
1.201     brouard  9824:        strcpy(model,modeltemp); 
1.197     brouard  9825:       }
                   9826:     }
1.199     brouard  9827:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9828:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9829:   }
                   9830:   /* 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); */
                   9831:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9832:   /* 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  9833:   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);
                   9834:   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  9835:   fflush(ficlog);
1.190     brouard  9836:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9837:   if(model[0]=='#'){
1.187     brouard  9838:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9839:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9840:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9841:     if(mle != -1){
                   9842:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9843:       exit(1);
                   9844:     }
                   9845:   }
1.126     brouard  9846:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9847:     ungetc(c,ficpar);
                   9848:     fgets(line, MAXLINE, ficpar);
                   9849:     numlinepar++;
1.195     brouard  9850:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9851:       z[0]=line[1];
                   9852:     }
                   9853:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9854:     fputs(line, stdout);
                   9855:     //puts(line);
1.126     brouard  9856:     fputs(line,ficparo);
                   9857:     fputs(line,ficlog);
                   9858:   }
                   9859:   ungetc(c,ficpar);
                   9860: 
                   9861:    
1.145     brouard  9862:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9863:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9864:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9865:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9866:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9867:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9868:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9869:   */
                   9870:   if (strlen(model)>1) 
1.187     brouard  9871:     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  9872:   else
1.187     brouard  9873:     ncovmodel=2; /* Constant and age */
1.133     brouard  9874:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9875:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9876:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9877:     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);
                   9878:     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);
                   9879:     fflush(stdout);
                   9880:     fclose (ficlog);
                   9881:     goto end;
                   9882:   }
1.126     brouard  9883:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9884:   delti=delti3[1][1];
                   9885:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9886:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247   ! brouard  9887: /* We could also provide initial parameters values giving by simple logistic regression 
        !          9888:  * only one way, that is without matrix product. We will have nlstate maximizations */
        !          9889:       /* for(i=1;i<nlstate;i++){ */
        !          9890:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
        !          9891:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
        !          9892:       /* } */
1.126     brouard  9893:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9894:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9895:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9896:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9897:     fclose (ficparo);
                   9898:     fclose (ficlog);
                   9899:     goto end;
                   9900:     exit(0);
1.220     brouard  9901:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9902:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9903:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9904:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9905:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9906:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9907:     hess=matrix(1,npar,1,npar);
1.220     brouard  9908:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9909:     /* Read guessed parameters */
1.126     brouard  9910:     /* Reads comments: lines beginning with '#' */
                   9911:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9912:       ungetc(c,ficpar);
                   9913:       fgets(line, MAXLINE, ficpar);
                   9914:       numlinepar++;
1.141     brouard  9915:       fputs(line,stdout);
1.126     brouard  9916:       fputs(line,ficparo);
                   9917:       fputs(line,ficlog);
                   9918:     }
                   9919:     ungetc(c,ficpar);
                   9920:     
                   9921:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9922:     for(i=1; i <=nlstate; i++){
1.234     brouard  9923:       j=0;
1.126     brouard  9924:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9925:        if(jj==i) continue;
                   9926:        j++;
                   9927:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9928:        if ((i1 != i) || (j1 != jj)){
                   9929:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9930: It might be a problem of design; if ncovcol and the model are correct\n \
                   9931: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9932:          exit(1);
                   9933:        }
                   9934:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9935:        if(mle==1)
                   9936:          printf("%1d%1d",i,jj);
                   9937:        fprintf(ficlog,"%1d%1d",i,jj);
                   9938:        for(k=1; k<=ncovmodel;k++){
                   9939:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9940:          if(mle==1){
                   9941:            printf(" %lf",param[i][j][k]);
                   9942:            fprintf(ficlog," %lf",param[i][j][k]);
                   9943:          }
                   9944:          else
                   9945:            fprintf(ficlog," %lf",param[i][j][k]);
                   9946:          fprintf(ficparo," %lf",param[i][j][k]);
                   9947:        }
                   9948:        fscanf(ficpar,"\n");
                   9949:        numlinepar++;
                   9950:        if(mle==1)
                   9951:          printf("\n");
                   9952:        fprintf(ficlog,"\n");
                   9953:        fprintf(ficparo,"\n");
1.126     brouard  9954:       }
                   9955:     }  
                   9956:     fflush(ficlog);
1.234     brouard  9957:     
1.145     brouard  9958:     /* Reads scales values */
1.126     brouard  9959:     p=param[1][1];
                   9960:     
                   9961:     /* Reads comments: lines beginning with '#' */
                   9962:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9963:       ungetc(c,ficpar);
                   9964:       fgets(line, MAXLINE, ficpar);
                   9965:       numlinepar++;
1.141     brouard  9966:       fputs(line,stdout);
1.126     brouard  9967:       fputs(line,ficparo);
                   9968:       fputs(line,ficlog);
                   9969:     }
                   9970:     ungetc(c,ficpar);
                   9971: 
                   9972:     for(i=1; i <=nlstate; i++){
                   9973:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9974:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9975:        if ( (i1-i) * (j1-j) != 0){
                   9976:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9977:          exit(1);
                   9978:        }
                   9979:        printf("%1d%1d",i,j);
                   9980:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9981:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9982:        for(k=1; k<=ncovmodel;k++){
                   9983:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9984:          printf(" %le",delti3[i][j][k]);
                   9985:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9986:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9987:        }
                   9988:        fscanf(ficpar,"\n");
                   9989:        numlinepar++;
                   9990:        printf("\n");
                   9991:        fprintf(ficparo,"\n");
                   9992:        fprintf(ficlog,"\n");
1.126     brouard  9993:       }
                   9994:     }
                   9995:     fflush(ficlog);
1.234     brouard  9996:     
1.145     brouard  9997:     /* Reads covariance matrix */
1.126     brouard  9998:     delti=delti3[1][1];
1.220     brouard  9999:                
                   10000:                
1.126     brouard  10001:     /* 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  10002:                
1.126     brouard  10003:     /* Reads comments: lines beginning with '#' */
                   10004:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10005:       ungetc(c,ficpar);
                   10006:       fgets(line, MAXLINE, ficpar);
                   10007:       numlinepar++;
1.141     brouard  10008:       fputs(line,stdout);
1.126     brouard  10009:       fputs(line,ficparo);
                   10010:       fputs(line,ficlog);
                   10011:     }
                   10012:     ungetc(c,ficpar);
1.220     brouard  10013:                
1.126     brouard  10014:     matcov=matrix(1,npar,1,npar);
1.203     brouard  10015:     hess=matrix(1,npar,1,npar);
1.131     brouard  10016:     for(i=1; i <=npar; i++)
                   10017:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  10018:                
1.194     brouard  10019:     /* Scans npar lines */
1.126     brouard  10020:     for(i=1; i <=npar; i++){
1.226     brouard  10021:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  10022:       if(count != 3){
1.226     brouard  10023:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10024: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10025: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10026:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10027: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10028: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10029:        exit(1);
1.220     brouard  10030:       }else{
1.226     brouard  10031:        if(mle==1)
                   10032:          printf("%1d%1d%d",i1,j1,jk);
                   10033:       }
                   10034:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10035:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10036:       for(j=1; j <=i; j++){
1.226     brouard  10037:        fscanf(ficpar," %le",&matcov[i][j]);
                   10038:        if(mle==1){
                   10039:          printf(" %.5le",matcov[i][j]);
                   10040:        }
                   10041:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10042:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10043:       }
                   10044:       fscanf(ficpar,"\n");
                   10045:       numlinepar++;
                   10046:       if(mle==1)
1.220     brouard  10047:                                printf("\n");
1.126     brouard  10048:       fprintf(ficlog,"\n");
                   10049:       fprintf(ficparo,"\n");
                   10050:     }
1.194     brouard  10051:     /* End of read covariance matrix npar lines */
1.126     brouard  10052:     for(i=1; i <=npar; i++)
                   10053:       for(j=i+1;j<=npar;j++)
1.226     brouard  10054:        matcov[i][j]=matcov[j][i];
1.126     brouard  10055:     
                   10056:     if(mle==1)
                   10057:       printf("\n");
                   10058:     fprintf(ficlog,"\n");
                   10059:     
                   10060:     fflush(ficlog);
                   10061:     
                   10062:     /*-------- Rewriting parameter file ----------*/
                   10063:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10064:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10065:     strcat(rfileres,".");    /* */
                   10066:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10067:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10068:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10069:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10070:     }
                   10071:     fprintf(ficres,"#%s\n",version);
                   10072:   }    /* End of mle != -3 */
1.218     brouard  10073:   
1.186     brouard  10074:   /*  Main data
                   10075:    */
1.126     brouard  10076:   n= lastobs;
                   10077:   num=lvector(1,n);
                   10078:   moisnais=vector(1,n);
                   10079:   annais=vector(1,n);
                   10080:   moisdc=vector(1,n);
                   10081:   andc=vector(1,n);
1.220     brouard  10082:   weight=vector(1,n);
1.126     brouard  10083:   agedc=vector(1,n);
                   10084:   cod=ivector(1,n);
1.220     brouard  10085:   for(i=1;i<=n;i++){
1.234     brouard  10086:     num[i]=0;
                   10087:     moisnais[i]=0;
                   10088:     annais[i]=0;
                   10089:     moisdc[i]=0;
                   10090:     andc[i]=0;
                   10091:     agedc[i]=0;
                   10092:     cod[i]=0;
                   10093:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10094:   }
1.126     brouard  10095:   mint=matrix(1,maxwav,1,n);
                   10096:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10097:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10098:   tab=ivector(1,NCOVMAX);
1.144     brouard  10099:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10100:   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  10101: 
1.136     brouard  10102:   /* Reads data from file datafile */
                   10103:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10104:     goto end;
                   10105: 
                   10106:   /* Calculation of the number of parameters from char model */
1.234     brouard  10107:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10108:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10109:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10110:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10111:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10112:   */
                   10113:   
                   10114:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10115:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10116:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10117:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10118:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10119:   TvarF=ivector(1,NCOVMAX); /*  */
                   10120:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10121:   TvarV=ivector(1,NCOVMAX); /*  */
                   10122:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10123:   TvarA=ivector(1,NCOVMAX); /*  */
                   10124:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10125:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10126:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10127:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10128:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10129:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10130:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10131:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10132:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10133: 
1.230     brouard  10134:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10135:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10136:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10137:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10138:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10139:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10140:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10141:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10142:   */
                   10143:   /* For model-covariate k tells which data-covariate to use but
                   10144:     because this model-covariate is a construction we invent a new column
                   10145:     ncovcol + k1
                   10146:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10147:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10148:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10149:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10150:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10151:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10152:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10153:   */
1.145     brouard  10154:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10155:   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  10156:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10157:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10158:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10159:                         4 covariates (3 plus signs)
                   10160:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10161:                      */  
1.230     brouard  10162:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10163:                                * individual dummy, fixed or varying:
                   10164:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10165:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10166:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10167:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10168:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10169:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10170:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10171:                                * individual quantitative, fixed or varying:
                   10172:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10173:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10174:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10175: /* Main decodemodel */
                   10176: 
1.187     brouard  10177: 
1.223     brouard  10178:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10179:     goto end;
                   10180: 
1.137     brouard  10181:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10182:     nbwarn++;
                   10183:     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); 
                   10184:     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); 
                   10185:   }
1.136     brouard  10186:     /*  if(mle==1){*/
1.137     brouard  10187:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10188:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10189:   }
                   10190: 
                   10191:     /*-calculation of age at interview from date of interview and age at death -*/
                   10192:   agev=matrix(1,maxwav,1,imx);
                   10193: 
                   10194:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10195:     goto end;
                   10196: 
1.126     brouard  10197: 
1.136     brouard  10198:   agegomp=(int)agemin;
                   10199:   free_vector(moisnais,1,n);
                   10200:   free_vector(annais,1,n);
1.126     brouard  10201:   /* free_matrix(mint,1,maxwav,1,n);
                   10202:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10203:   /* free_vector(moisdc,1,n); */
                   10204:   /* free_vector(andc,1,n); */
1.145     brouard  10205:   /* */
                   10206:   
1.126     brouard  10207:   wav=ivector(1,imx);
1.214     brouard  10208:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10209:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10210:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10211:   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.*/
                   10212:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10213:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10214:    
                   10215:   /* Concatenates waves */
1.214     brouard  10216:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10217:      Death is a valid wave (if date is known).
                   10218:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10219:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10220:      and mw[mi+1][i]. dh depends on stepm.
                   10221:   */
                   10222: 
1.126     brouard  10223:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  10224:   /* */
                   10225:  
1.215     brouard  10226:   free_vector(moisdc,1,n);
                   10227:   free_vector(andc,1,n);
                   10228: 
1.126     brouard  10229:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10230:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10231:   ncodemax[1]=1;
1.145     brouard  10232:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10233:   cptcoveff=0;
1.220     brouard  10234:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10235:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10236:   }
                   10237:   
                   10238:   ncovcombmax=pow(2,cptcoveff);
                   10239:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10240:   for(i=1;i<ncovcombmax;i++)
                   10241:     invalidvarcomb[i]=0;
                   10242:   
1.211     brouard  10243:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10244:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10245:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10246:   
1.200     brouard  10247:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10248:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10249:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10250:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10251:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10252:    * (currently 0 or 1) in the data.
                   10253:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10254:    * corresponding modality (h,j).
                   10255:    */
                   10256: 
1.145     brouard  10257:   h=0;
                   10258:   /*if (cptcovn > 0) */
1.126     brouard  10259:   m=pow(2,cptcoveff);
                   10260:  
1.144     brouard  10261:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10262:           * For k=4 covariates, h goes from 1 to m=2**k
                   10263:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10264:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10265:           *     h\k   1     2     3     4
1.143     brouard  10266:           *______________________________  
                   10267:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10268:           *     2     2     1     1     1
                   10269:           *     3 i=2 1     2     1     1
                   10270:           *     4     2     2     1     1
                   10271:           *     5 i=3 1 i=2 1     2     1
                   10272:           *     6     2     1     2     1
                   10273:           *     7 i=4 1     2     2     1
                   10274:           *     8     2     2     2     1
1.197     brouard  10275:           *     9 i=5 1 i=3 1 i=2 1     2
                   10276:           *    10     2     1     1     2
                   10277:           *    11 i=6 1     2     1     2
                   10278:           *    12     2     2     1     2
                   10279:           *    13 i=7 1 i=4 1     2     2    
                   10280:           *    14     2     1     2     2
                   10281:           *    15 i=8 1     2     2     2
                   10282:           *    16     2     2     2     2
1.143     brouard  10283:           */
1.212     brouard  10284:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10285:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10286:      * and the value of each covariate?
                   10287:      * V1=1, V2=1, V3=2, V4=1 ?
                   10288:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10289:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10290:      * In order to get the real value in the data, we use nbcode
                   10291:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10292:      * We are keeping this crazy system in order to be able (in the future?) 
                   10293:      * to have more than 2 values (0 or 1) for a covariate.
                   10294:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10295:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10296:      *              bbbbbbbb
                   10297:      *              76543210     
                   10298:      *   h-1        00000101 (6-1=5)
1.219     brouard  10299:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10300:      *           &
                   10301:      *     1        00000001 (1)
1.219     brouard  10302:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10303:      *          +1= 00000001 =1 
1.211     brouard  10304:      *
                   10305:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10306:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10307:      *    >>k'            11
                   10308:      *          &   00000001
                   10309:      *            = 00000001
                   10310:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10311:      * Reverse h=6 and m=16?
                   10312:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10313:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10314:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10315:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10316:      * V3=decodtabm(14,3,2**4)=2
                   10317:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10318:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10319:      *          &1 000000001
                   10320:      *           = 000000001
                   10321:      *         +1= 000000010 =2
                   10322:      *                  2211
                   10323:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10324:      *                  V3=2
1.220     brouard  10325:                 * codtabm and decodtabm are identical
1.211     brouard  10326:      */
                   10327: 
1.145     brouard  10328: 
                   10329:  free_ivector(Ndum,-1,NCOVMAX);
                   10330: 
                   10331: 
1.126     brouard  10332:     
1.186     brouard  10333:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10334:   strcpy(optionfilegnuplot,optionfilefiname);
                   10335:   if(mle==-3)
1.201     brouard  10336:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10337:   strcat(optionfilegnuplot,".gp");
                   10338: 
                   10339:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10340:     printf("Problem with file %s",optionfilegnuplot);
                   10341:   }
                   10342:   else{
1.204     brouard  10343:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10344:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10345:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10346:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10347:   }
                   10348:   /*  fclose(ficgp);*/
1.186     brouard  10349: 
                   10350: 
                   10351:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10352: 
                   10353:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10354:   if(mle==-3)
1.201     brouard  10355:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10356:   strcat(optionfilehtm,".htm");
                   10357:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10358:     printf("Problem with %s \n",optionfilehtm);
                   10359:     exit(0);
1.126     brouard  10360:   }
                   10361: 
                   10362:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10363:   strcat(optionfilehtmcov,"-cov.htm");
                   10364:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10365:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10366:   }
                   10367:   else{
                   10368:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10369: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10370: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10371:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10372:   }
                   10373: 
1.213     brouard  10374:   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  10375: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10376: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10377: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10378: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10379: \n\
                   10380: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10381:  <ul><li><h4>Parameter files</h4>\n\
                   10382:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10383:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10384:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10385:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10386:  - Date and time at start: %s</ul>\n",\
                   10387:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10388:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10389:          fileres,fileres,\
                   10390:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10391:   fflush(fichtm);
                   10392: 
                   10393:   strcpy(pathr,path);
                   10394:   strcat(pathr,optionfilefiname);
1.184     brouard  10395: #ifdef WIN32
                   10396:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10397: #else
1.126     brouard  10398:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10399: #endif
                   10400:          
1.126     brouard  10401:   
1.220     brouard  10402:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10403:                 and for any valid combination of covariates
1.126     brouard  10404:      and prints on file fileres'p'. */
1.227     brouard  10405:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10406:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10407: 
                   10408:   fprintf(fichtm,"\n");
                   10409:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10410: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10411: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10412:          imx,agemin,agemax,jmin,jmax,jmean);
                   10413:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10414:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10415:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10416:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10417:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10418: 
1.126     brouard  10419:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10420:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10421:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10422: 
                   10423:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10424:   /* For mortality only */
1.126     brouard  10425:   if (mle==-3){
1.136     brouard  10426:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10427:                for(i=1;i<=NDIM;i++)
                   10428:                        for(j=1;j<=NDIM;j++)
                   10429:                                ximort[i][j]=0.;
1.186     brouard  10430:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10431:     cens=ivector(1,n);
                   10432:     ageexmed=vector(1,n);
                   10433:     agecens=vector(1,n);
                   10434:     dcwave=ivector(1,n);
1.223     brouard  10435:                
1.126     brouard  10436:     for (i=1; i<=imx; i++){
                   10437:       dcwave[i]=-1;
                   10438:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10439:        if (s[m][i]>nlstate) {
                   10440:          dcwave[i]=m;
                   10441:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10442:          break;
                   10443:        }
1.126     brouard  10444:     }
1.226     brouard  10445:     
1.126     brouard  10446:     for (i=1; i<=imx; i++) {
                   10447:       if (wav[i]>0){
1.226     brouard  10448:        ageexmed[i]=agev[mw[1][i]][i];
                   10449:        j=wav[i];
                   10450:        agecens[i]=1.; 
                   10451:        
                   10452:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10453:          agecens[i]=agev[mw[j][i]][i];
                   10454:          cens[i]= 1;
                   10455:        }else if (ageexmed[i]< 1) 
                   10456:          cens[i]= -1;
                   10457:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10458:          cens[i]=0 ;
1.126     brouard  10459:       }
                   10460:       else cens[i]=-1;
                   10461:     }
                   10462:     
                   10463:     for (i=1;i<=NDIM;i++) {
                   10464:       for (j=1;j<=NDIM;j++)
1.226     brouard  10465:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10466:     }
                   10467:     
1.145     brouard  10468:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10469:     /*printf("%lf %lf", p[1], p[2]);*/
                   10470:     
                   10471:     
1.136     brouard  10472: #ifdef GSL
                   10473:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10474: #else
1.126     brouard  10475:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10476: #endif
1.201     brouard  10477:     strcpy(filerespow,"POW-MORT_"); 
                   10478:     strcat(filerespow,fileresu);
1.126     brouard  10479:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10480:       printf("Problem with resultfile: %s\n", filerespow);
                   10481:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10482:     }
1.136     brouard  10483: #ifdef GSL
                   10484:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10485: #else
1.126     brouard  10486:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10487: #endif
1.126     brouard  10488:     /*  for (i=1;i<=nlstate;i++)
                   10489:        for(j=1;j<=nlstate+ndeath;j++)
                   10490:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10491:     */
                   10492:     fprintf(ficrespow,"\n");
1.136     brouard  10493: #ifdef GSL
                   10494:     /* gsl starts here */ 
                   10495:     T = gsl_multimin_fminimizer_nmsimplex;
                   10496:     gsl_multimin_fminimizer *sfm = NULL;
                   10497:     gsl_vector *ss, *x;
                   10498:     gsl_multimin_function minex_func;
                   10499: 
                   10500:     /* Initial vertex size vector */
                   10501:     ss = gsl_vector_alloc (NDIM);
                   10502:     
                   10503:     if (ss == NULL){
                   10504:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10505:     }
                   10506:     /* Set all step sizes to 1 */
                   10507:     gsl_vector_set_all (ss, 0.001);
                   10508: 
                   10509:     /* Starting point */
1.126     brouard  10510:     
1.136     brouard  10511:     x = gsl_vector_alloc (NDIM);
                   10512:     
                   10513:     if (x == NULL){
                   10514:       gsl_vector_free(ss);
                   10515:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10516:     }
                   10517:   
                   10518:     /* Initialize method and iterate */
                   10519:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10520:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10521:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10522:     gsl_vector_set(x, 0, p[1]);
                   10523:     gsl_vector_set(x, 1, p[2]);
                   10524: 
                   10525:     minex_func.f = &gompertz_f;
                   10526:     minex_func.n = NDIM;
                   10527:     minex_func.params = (void *)&p; /* ??? */
                   10528:     
                   10529:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10530:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10531:     
                   10532:     printf("Iterations beginning .....\n\n");
                   10533:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10534: 
                   10535:     iteri=0;
                   10536:     while (rval == GSL_CONTINUE){
                   10537:       iteri++;
                   10538:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10539:       
                   10540:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10541:       fflush(0);
                   10542:       
                   10543:       if (status) 
                   10544:         break;
                   10545:       
                   10546:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10547:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10548:       
                   10549:       if (rval == GSL_SUCCESS)
                   10550:         printf ("converged to a local maximum at\n");
                   10551:       
                   10552:       printf("%5d ", iteri);
                   10553:       for (it = 0; it < NDIM; it++){
                   10554:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10555:       }
                   10556:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10557:     }
                   10558:     
                   10559:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10560:     
                   10561:     gsl_vector_free(x); /* initial values */
                   10562:     gsl_vector_free(ss); /* inital step size */
                   10563:     for (it=0; it<NDIM; it++){
                   10564:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10565:       fprintf(ficrespow," %.12lf", p[it]);
                   10566:     }
                   10567:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10568: #endif
                   10569: #ifdef POWELL
                   10570:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10571: #endif  
1.126     brouard  10572:     fclose(ficrespow);
                   10573:     
1.203     brouard  10574:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10575: 
                   10576:     for(i=1; i <=NDIM; i++)
                   10577:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10578:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10579:     
                   10580:     printf("\nCovariance matrix\n ");
1.203     brouard  10581:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10582:     for(i=1; i <=NDIM; i++) {
                   10583:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10584:                                printf("%f ",matcov[i][j]);
                   10585:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10586:       }
1.203     brouard  10587:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10588:     }
                   10589:     
                   10590:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10591:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10592:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10593:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10594:     }
1.126     brouard  10595:     lsurv=vector(1,AGESUP);
                   10596:     lpop=vector(1,AGESUP);
                   10597:     tpop=vector(1,AGESUP);
                   10598:     lsurv[agegomp]=100000;
                   10599:     
                   10600:     for (k=agegomp;k<=AGESUP;k++) {
                   10601:       agemortsup=k;
                   10602:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10603:     }
                   10604:     
                   10605:     for (k=agegomp;k<agemortsup;k++)
                   10606:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10607:     
                   10608:     for (k=agegomp;k<agemortsup;k++){
                   10609:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10610:       sumlpop=sumlpop+lpop[k];
                   10611:     }
                   10612:     
                   10613:     tpop[agegomp]=sumlpop;
                   10614:     for (k=agegomp;k<(agemortsup-3);k++){
                   10615:       /*  tpop[k+1]=2;*/
                   10616:       tpop[k+1]=tpop[k]-lpop[k];
                   10617:     }
                   10618:     
                   10619:     
                   10620:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10621:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10622:       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]);
                   10623:     
                   10624:     
                   10625:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10626:                ageminpar=50;
                   10627:                agemaxpar=100;
1.194     brouard  10628:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10629:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10630: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10631: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10632:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10633: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10634: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10635:     }else{
                   10636:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10637:                        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  10638:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10639:                }
1.201     brouard  10640:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10641:                     stepm, weightopt,\
                   10642:                     model,imx,p,matcov,agemortsup);
                   10643:     
                   10644:     free_vector(lsurv,1,AGESUP);
                   10645:     free_vector(lpop,1,AGESUP);
                   10646:     free_vector(tpop,1,AGESUP);
1.220     brouard  10647:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10648:     free_ivector(cens,1,n);
                   10649:     free_vector(agecens,1,n);
                   10650:     free_ivector(dcwave,1,n);
1.220     brouard  10651: #ifdef GSL
1.136     brouard  10652: #endif
1.186     brouard  10653:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10654:   /* Standard  */
                   10655:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10656:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10657:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10658:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10659:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10660:     for (k=1; k<=npar;k++)
                   10661:       printf(" %d %8.5f",k,p[k]);
                   10662:     printf("\n");
1.205     brouard  10663:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10664:       /* mlikeli uses func not funcone */
1.247   ! brouard  10665:       /* for(i=1;i<nlstate;i++){ */
        !          10666:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
        !          10667:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
        !          10668:       /* } */
1.205     brouard  10669:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10670:     }
                   10671:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10672:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10673:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10674:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10675:     }
                   10676:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10677:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10678:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10679:     for (k=1; k<=npar;k++)
                   10680:       printf(" %d %8.5f",k,p[k]);
                   10681:     printf("\n");
                   10682:     
                   10683:     /*--------- results files --------------*/
1.224     brouard  10684:     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  10685:     
                   10686:     
                   10687:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10688:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10689:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10690:     for(i=1,jk=1; i <=nlstate; i++){
                   10691:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10692:        if (k != i) {
                   10693:          printf("%d%d ",i,k);
                   10694:          fprintf(ficlog,"%d%d ",i,k);
                   10695:          fprintf(ficres,"%1d%1d ",i,k);
                   10696:          for(j=1; j <=ncovmodel; j++){
                   10697:            printf("%12.7f ",p[jk]);
                   10698:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10699:            fprintf(ficres,"%12.7f ",p[jk]);
                   10700:            jk++; 
                   10701:          }
                   10702:          printf("\n");
                   10703:          fprintf(ficlog,"\n");
                   10704:          fprintf(ficres,"\n");
                   10705:        }
1.126     brouard  10706:       }
                   10707:     }
1.203     brouard  10708:     if(mle != 0){
                   10709:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10710:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10711:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10712:       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");
                   10713:       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");
                   10714:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10715:        for(k=1; k <=(nlstate+ndeath); k++){
                   10716:          if (k != i) {
                   10717:            printf("%d%d ",i,k);
                   10718:            fprintf(ficlog,"%d%d ",i,k);
                   10719:            for(j=1; j <=ncovmodel; j++){
                   10720:              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]));
                   10721:              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]));
                   10722:              jk++; 
                   10723:            }
                   10724:            printf("\n");
                   10725:            fprintf(ficlog,"\n");
                   10726:          }
                   10727:        }
1.193     brouard  10728:       }
1.203     brouard  10729:     } /* end of hesscov and Wald tests */
1.225     brouard  10730:     
1.203     brouard  10731:     /*  */
1.126     brouard  10732:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10733:     printf("# Scales (for hessian or gradient estimation)\n");
                   10734:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10735:     for(i=1,jk=1; i <=nlstate; i++){
                   10736:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10737:        if (j!=i) {
                   10738:          fprintf(ficres,"%1d%1d",i,j);
                   10739:          printf("%1d%1d",i,j);
                   10740:          fprintf(ficlog,"%1d%1d",i,j);
                   10741:          for(k=1; k<=ncovmodel;k++){
                   10742:            printf(" %.5e",delti[jk]);
                   10743:            fprintf(ficlog," %.5e",delti[jk]);
                   10744:            fprintf(ficres," %.5e",delti[jk]);
                   10745:            jk++;
                   10746:          }
                   10747:          printf("\n");
                   10748:          fprintf(ficlog,"\n");
                   10749:          fprintf(ficres,"\n");
                   10750:        }
1.126     brouard  10751:       }
                   10752:     }
                   10753:     
                   10754:     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  10755:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10756:       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");
                   10757:     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");
                   10758:     /* # 121 Var(a12)\n\ */
                   10759:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10760:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10761:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10762:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10763:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10764:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10765:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10766:     
                   10767:     
                   10768:     /* Just to have a covariance matrix which will be more understandable
                   10769:        even is we still don't want to manage dictionary of variables
                   10770:     */
                   10771:     for(itimes=1;itimes<=2;itimes++){
                   10772:       jj=0;
                   10773:       for(i=1; i <=nlstate; i++){
1.225     brouard  10774:        for(j=1; j <=nlstate+ndeath; j++){
                   10775:          if(j==i) continue;
                   10776:          for(k=1; k<=ncovmodel;k++){
                   10777:            jj++;
                   10778:            ca[0]= k+'a'-1;ca[1]='\0';
                   10779:            if(itimes==1){
                   10780:              if(mle>=1)
                   10781:                printf("#%1d%1d%d",i,j,k);
                   10782:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10783:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10784:            }else{
                   10785:              if(mle>=1)
                   10786:                printf("%1d%1d%d",i,j,k);
                   10787:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10788:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10789:            }
                   10790:            ll=0;
                   10791:            for(li=1;li <=nlstate; li++){
                   10792:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10793:                if(lj==li) continue;
                   10794:                for(lk=1;lk<=ncovmodel;lk++){
                   10795:                  ll++;
                   10796:                  if(ll<=jj){
                   10797:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10798:                    if(ll<jj){
                   10799:                      if(itimes==1){
                   10800:                        if(mle>=1)
                   10801:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10802:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10803:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10804:                      }else{
                   10805:                        if(mle>=1)
                   10806:                          printf(" %.5e",matcov[jj][ll]); 
                   10807:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10808:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10809:                      }
                   10810:                    }else{
                   10811:                      if(itimes==1){
                   10812:                        if(mle>=1)
                   10813:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10814:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10815:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10816:                      }else{
                   10817:                        if(mle>=1)
                   10818:                          printf(" %.7e",matcov[jj][ll]); 
                   10819:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10820:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10821:                      }
                   10822:                    }
                   10823:                  }
                   10824:                } /* end lk */
                   10825:              } /* end lj */
                   10826:            } /* end li */
                   10827:            if(mle>=1)
                   10828:              printf("\n");
                   10829:            fprintf(ficlog,"\n");
                   10830:            fprintf(ficres,"\n");
                   10831:            numlinepar++;
                   10832:          } /* end k*/
                   10833:        } /*end j */
1.126     brouard  10834:       } /* end i */
                   10835:     } /* end itimes */
                   10836:     
                   10837:     fflush(ficlog);
                   10838:     fflush(ficres);
1.225     brouard  10839:     while(fgets(line, MAXLINE, ficpar)) {
                   10840:       /* If line starts with a # it is a comment */
                   10841:       if (line[0] == '#') {
                   10842:        numlinepar++;
                   10843:        fputs(line,stdout);
                   10844:        fputs(line,ficparo);
                   10845:        fputs(line,ficlog);
                   10846:        continue;
                   10847:       }else
                   10848:        break;
                   10849:     }
                   10850:     
1.209     brouard  10851:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10852:     /*   ungetc(c,ficpar); */
                   10853:     /*   fgets(line, MAXLINE, ficpar); */
                   10854:     /*   fputs(line,stdout); */
                   10855:     /*   fputs(line,ficparo); */
                   10856:     /* } */
                   10857:     /* ungetc(c,ficpar); */
1.126     brouard  10858:     
                   10859:     estepm=0;
1.209     brouard  10860:     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  10861:       
                   10862:       if (num_filled != 6) {
                   10863:        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);
                   10864:        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);
                   10865:        goto end;
                   10866:       }
                   10867:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10868:     }
                   10869:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10870:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10871:     
1.209     brouard  10872:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10873:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10874:     if (fage <= 2) {
                   10875:       bage = ageminpar;
                   10876:       fage = agemaxpar;
                   10877:     }
                   10878:     
                   10879:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10880:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10881:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10882:                
1.186     brouard  10883:     /* Other stuffs, more or less useful */    
1.126     brouard  10884:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10885:       ungetc(c,ficpar);
                   10886:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10887:       fputs(line,stdout);
1.126     brouard  10888:       fputs(line,ficparo);
                   10889:     }
                   10890:     ungetc(c,ficpar);
                   10891:     
                   10892:     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);
                   10893:     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);
                   10894:     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);
                   10895:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10896:     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);
                   10897:     
                   10898:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10899:       ungetc(c,ficpar);
                   10900:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10901:       fputs(line,stdout);
1.126     brouard  10902:       fputs(line,ficparo);
                   10903:     }
                   10904:     ungetc(c,ficpar);
                   10905:     
                   10906:     
                   10907:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10908:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10909:     
                   10910:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10911:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10912:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10913:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10914:     
                   10915:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10916:       ungetc(c,ficpar);
                   10917:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10918:       fputs(line,stdout);
1.238     brouard  10919:       fputs(line,ficres);
1.126     brouard  10920:       fputs(line,ficparo);
                   10921:     }
                   10922:     ungetc(c,ficpar);
                   10923:     
                   10924:     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);
                   10925:     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);
                   10926:     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);
                   10927:     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);
                   10928:     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);
                   10929:     /* day and month of proj2 are not used but only year anproj2.*/
                   10930:     
1.217     brouard  10931:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10932:       ungetc(c,ficpar);
                   10933:       fgets(line, MAXLINE, ficpar);
                   10934:       fputs(line,stdout);
                   10935:       fputs(line,ficparo);
1.238     brouard  10936:       fputs(line,ficres);
1.217     brouard  10937:     }
                   10938:     ungetc(c,ficpar);
                   10939:     
                   10940:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.223     brouard  10941:     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);
                   10942:     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);
                   10943:     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  10944:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10945:     
1.230     brouard  10946:     /* Results */
1.235     brouard  10947:     nresult=0;
1.230     brouard  10948:     while(fgets(line, MAXLINE, ficpar)) {
                   10949:       /* If line starts with a # it is a comment */
                   10950:       if (line[0] == '#') {
                   10951:        numlinepar++;
                   10952:        fputs(line,stdout);
                   10953:        fputs(line,ficparo);
                   10954:        fputs(line,ficlog);
1.238     brouard  10955:        fputs(line,ficres);
1.230     brouard  10956:        continue;
                   10957:       }else
                   10958:        break;
                   10959:     }
1.240     brouard  10960:     if (!feof(ficpar))
1.230     brouard  10961:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240     brouard  10962:       if (num_filled == 0){
1.230     brouard  10963:        resultline[0]='\0';
1.240     brouard  10964:       break;
                   10965:       } else if (num_filled != 1){
1.230     brouard  10966:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10967:       }
1.235     brouard  10968:       nresult++; /* Sum of resultlines */
                   10969:       printf("Result %d: result=%s\n",nresult, resultline);
                   10970:       if(nresult > MAXRESULTLINES){
                   10971:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10972:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10973:        goto end;
                   10974:       }
                   10975:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  10976:       fprintf(ficparo,"result: %s\n",resultline);
                   10977:       fprintf(ficres,"result: %s\n",resultline);
                   10978:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  10979:       while(fgets(line, MAXLINE, ficpar)) {
                   10980:        /* If line starts with a # it is a comment */
                   10981:        if (line[0] == '#') {
                   10982:          numlinepar++;
                   10983:          fputs(line,stdout);
                   10984:          fputs(line,ficparo);
1.238     brouard  10985:          fputs(line,ficres);
1.230     brouard  10986:          fputs(line,ficlog);
                   10987:          continue;
                   10988:        }else
                   10989:          break;
                   10990:       }
                   10991:       if (feof(ficpar))
                   10992:        break;
                   10993:       else{ /* Processess output results for this combination of covariate values */
                   10994:       }                                   
1.240     brouard  10995:     } /* end while */
1.230     brouard  10996: 
                   10997: 
1.126     brouard  10998:     
1.230     brouard  10999:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  11000:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  11001:     
                   11002:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  11003:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  11004:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11005: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11006: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  11007:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11008: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11009: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  11010:     }else{
1.218     brouard  11011:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  11012:     }
                   11013:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  11014:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   11015:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  11016:                
1.225     brouard  11017:     /*------------ free_vector  -------------*/
                   11018:     /*  chdir(path); */
1.220     brouard  11019:                
1.215     brouard  11020:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   11021:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   11022:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   11023:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  11024:     free_lvector(num,1,n);
                   11025:     free_vector(agedc,1,n);
                   11026:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   11027:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   11028:     fclose(ficparo);
                   11029:     fclose(ficres);
1.220     brouard  11030:                
                   11031:                
1.186     brouard  11032:     /* Other results (useful)*/
1.220     brouard  11033:                
                   11034:                
1.126     brouard  11035:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11036:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11037:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11038:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11039:     fclose(ficrespl);
                   11040: 
                   11041:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11042:     /*#include "hpijx.h"*/
                   11043:     hPijx(p, bage, fage);
1.145     brouard  11044:     fclose(ficrespij);
1.227     brouard  11045:     
1.220     brouard  11046:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11047:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11048:     k=1;
1.126     brouard  11049:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11050:     
1.219     brouard  11051:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11052:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11053:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11054:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11055:        for(k=1;k<=ncovcombmax;k++)
                   11056:          probs[i][j][k]=0.;
1.219     brouard  11057:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11058:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11059:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11060:       for(i=1;i<=AGESUP;i++)
                   11061:        for(j=1;j<=nlstate;j++)
                   11062:          for(k=1;k<=ncovcombmax;k++)
                   11063:            mobaverages[i][j][k]=0.;
1.219     brouard  11064:       mobaverage=mobaverages;
                   11065:       if (mobilav!=0) {
1.235     brouard  11066:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  11067:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11068:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11069:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11070:        }
1.219     brouard  11071:       }
                   11072:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11073:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11074:       else if (mobilavproj !=0) {
1.235     brouard  11075:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  11076:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11077:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11078:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11079:        }
1.219     brouard  11080:       }
                   11081:     }/* end if moving average */
1.227     brouard  11082:     
1.126     brouard  11083:     /*---------- Forecasting ------------------*/
                   11084:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11085:     if(prevfcast==1){
                   11086:       /*    if(stepm ==1){*/
1.225     brouard  11087:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11088:     }
1.217     brouard  11089:     if(backcast==1){
1.219     brouard  11090:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11091:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11092:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11093: 
                   11094:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11095: 
                   11096:       bprlim=matrix(1,nlstate,1,nlstate);
                   11097:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11098:       fclose(ficresplb);
                   11099: 
1.222     brouard  11100:       hBijx(p, bage, fage, mobaverage);
                   11101:       fclose(ficrespijb);
1.219     brouard  11102:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11103: 
                   11104:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11105:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11106:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11107:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11108:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11109:     }
1.217     brouard  11110:     
1.186     brouard  11111:  
                   11112:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11113: 
1.215     brouard  11114:     free_ivector(wav,1,imx);
                   11115:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11116:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11117:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11118:                
                   11119:                
1.127     brouard  11120:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11121:                
1.201     brouard  11122:     strcpy(filerese,"E_");
                   11123:     strcat(filerese,fileresu);
1.126     brouard  11124:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11125:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11126:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11127:     }
1.208     brouard  11128:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11129:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11130: 
                   11131:     pstamp(ficreseij);
1.219     brouard  11132:                
1.235     brouard  11133:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11134:     if (cptcovn < 1){i1=1;}
                   11135:     
                   11136:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11137:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11138:       if(TKresult[nres]!= k)
                   11139:        continue;
1.219     brouard  11140:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11141:       printf("\n#****** ");
1.225     brouard  11142:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11143:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11144:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11145:       }
                   11146:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11147:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11148:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11149:       }
                   11150:       fprintf(ficreseij,"******\n");
1.235     brouard  11151:       printf("******\n");
1.219     brouard  11152:       
                   11153:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11154:       oldm=oldms;savm=savms;
1.235     brouard  11155:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11156:       
1.219     brouard  11157:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11158:     }
                   11159:     fclose(ficreseij);
1.208     brouard  11160:     printf("done evsij\n");fflush(stdout);
                   11161:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11162:                
1.227     brouard  11163:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11164:                
                   11165:                
1.201     brouard  11166:     strcpy(filerest,"T_");
                   11167:     strcat(filerest,fileresu);
1.127     brouard  11168:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11169:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11170:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11171:     }
1.208     brouard  11172:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11173:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11174:                
1.126     brouard  11175: 
1.201     brouard  11176:     strcpy(fileresstde,"STDE_");
                   11177:     strcat(fileresstde,fileresu);
1.126     brouard  11178:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11179:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11180:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11181:     }
1.227     brouard  11182:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11183:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11184: 
1.201     brouard  11185:     strcpy(filerescve,"CVE_");
                   11186:     strcat(filerescve,fileresu);
1.126     brouard  11187:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11188:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11189:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11190:     }
1.227     brouard  11191:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11192:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11193: 
1.201     brouard  11194:     strcpy(fileresv,"V_");
                   11195:     strcat(fileresv,fileresu);
1.126     brouard  11196:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11197:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11198:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11199:     }
1.227     brouard  11200:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11201:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11202: 
1.145     brouard  11203:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11204:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11205:           
1.235     brouard  11206:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11207:     if (cptcovn < 1){i1=1;}
                   11208:     
                   11209:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11210:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11211:       if(TKresult[nres]!= k)
                   11212:        continue;
1.242     brouard  11213:       printf("\n#****** Result for:");
                   11214:       fprintf(ficrest,"\n#****** Result for:");
                   11215:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11216:       for(j=1;j<=cptcoveff;j++){ 
                   11217:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11218:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11219:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11220:       }
1.235     brouard  11221:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11222:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11223:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11224:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11225:       }        
1.208     brouard  11226:       fprintf(ficrest,"******\n");
1.227     brouard  11227:       fprintf(ficlog,"******\n");
                   11228:       printf("******\n");
1.208     brouard  11229:       
                   11230:       fprintf(ficresstdeij,"\n#****** ");
                   11231:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11232:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11233:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11234:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11235:       }
1.235     brouard  11236:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11237:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11238:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11239:       }        
1.208     brouard  11240:       fprintf(ficresstdeij,"******\n");
                   11241:       fprintf(ficrescveij,"******\n");
                   11242:       
                   11243:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11244:       /* pstamp(ficresvij); */
1.225     brouard  11245:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11246:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11247:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11248:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11249:       }        
1.208     brouard  11250:       fprintf(ficresvij,"******\n");
                   11251:       
                   11252:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11253:       oldm=oldms;savm=savms;
1.235     brouard  11254:       printf(" cvevsij ");
                   11255:       fprintf(ficlog, " cvevsij ");
                   11256:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11257:       printf(" end cvevsij \n ");
                   11258:       fprintf(ficlog, " end cvevsij \n ");
                   11259:       
                   11260:       /*
                   11261:        */
                   11262:       /* goto endfree; */
                   11263:       
                   11264:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11265:       pstamp(ficrest);
                   11266:       
                   11267:       
                   11268:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11269:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11270:        cptcod= 0; /* To be deleted */
                   11271:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11272:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11273:        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  11274:        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 ");
                   11275:        if(vpopbased==1)
                   11276:          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);
                   11277:        else
                   11278:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11279:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11280:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11281:        fprintf(ficrest,"\n");
                   11282:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11283:        epj=vector(1,nlstate+1);
                   11284:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11285:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11286:        for(age=bage; age <=fage ;age++){
1.235     brouard  11287:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11288:          if (vpopbased==1) {
                   11289:            if(mobilav ==0){
                   11290:              for(i=1; i<=nlstate;i++)
                   11291:                prlim[i][i]=probs[(int)age][i][k];
                   11292:            }else{ /* mobilav */ 
                   11293:              for(i=1; i<=nlstate;i++)
                   11294:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11295:            }
                   11296:          }
1.219     brouard  11297:          
1.227     brouard  11298:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11299:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11300:          /* printf(" age %4.0f ",age); */
                   11301:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11302:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11303:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11304:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11305:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11306:            }
                   11307:            epj[nlstate+1] +=epj[j];
                   11308:          }
                   11309:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11310:          
1.227     brouard  11311:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11312:            for(j=1;j <=nlstate;j++)
                   11313:              vepp += vareij[i][j][(int)age];
                   11314:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11315:          for(j=1;j <=nlstate;j++){
                   11316:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11317:          }
                   11318:          fprintf(ficrest,"\n");
                   11319:        }
1.208     brouard  11320:       } /* End vpopbased */
                   11321:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11322:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11323:       free_vector(epj,1,nlstate+1);
1.235     brouard  11324:       printf("done selection\n");fflush(stdout);
                   11325:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11326:       
1.145     brouard  11327:       /*}*/
1.235     brouard  11328:     } /* End k selection */
1.227     brouard  11329: 
                   11330:     printf("done State-specific expectancies\n");fflush(stdout);
                   11331:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11332: 
1.126     brouard  11333:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11334:     
1.201     brouard  11335:     strcpy(fileresvpl,"VPL_");
                   11336:     strcat(fileresvpl,fileresu);
1.126     brouard  11337:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11338:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11339:       exit(0);
                   11340:     }
1.208     brouard  11341:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11342:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11343:     
1.145     brouard  11344:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11345:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11346:     
1.235     brouard  11347:     i1=pow(2,cptcoveff);
                   11348:     if (cptcovn < 1){i1=1;}
                   11349: 
                   11350:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11351:     for(k=1; k<=i1;k++){
                   11352:       if(TKresult[nres]!= k)
                   11353:        continue;
1.227     brouard  11354:       fprintf(ficresvpl,"\n#****** ");
                   11355:       printf("\n#****** ");
                   11356:       fprintf(ficlog,"\n#****** ");
                   11357:       for(j=1;j<=cptcoveff;j++) {
                   11358:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11359:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11360:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11361:       }
1.235     brouard  11362:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11363:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11364:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11365:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11366:       }        
1.227     brouard  11367:       fprintf(ficresvpl,"******\n");
                   11368:       printf("******\n");
                   11369:       fprintf(ficlog,"******\n");
                   11370:       
                   11371:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11372:       oldm=oldms;savm=savms;
1.235     brouard  11373:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11374:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11375:       /*}*/
1.126     brouard  11376:     }
1.227     brouard  11377:     
1.126     brouard  11378:     fclose(ficresvpl);
1.208     brouard  11379:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11380:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11381:     
                   11382:     free_vector(weight,1,n);
                   11383:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11384:     free_imatrix(s,1,maxwav+1,1,n);
                   11385:     free_matrix(anint,1,maxwav,1,n); 
                   11386:     free_matrix(mint,1,maxwav,1,n);
                   11387:     free_ivector(cod,1,n);
                   11388:     free_ivector(tab,1,NCOVMAX);
                   11389:     fclose(ficresstdeij);
                   11390:     fclose(ficrescveij);
                   11391:     fclose(ficresvij);
                   11392:     fclose(ficrest);
                   11393:     fclose(ficpar);
                   11394:     
                   11395:     
1.126     brouard  11396:     /*---------- End : free ----------------*/
1.219     brouard  11397:     if (mobilav!=0 ||mobilavproj !=0)
                   11398:       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  11399:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11400:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11401:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11402:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11403:   /* endfree:*/
                   11404:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11405:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11406:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11407:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11408:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11409:   free_matrix(coqvar,1,maxwav,1,n);
                   11410:   free_matrix(covar,0,NCOVMAX,1,n);
                   11411:   free_matrix(matcov,1,npar,1,npar);
                   11412:   free_matrix(hess,1,npar,1,npar);
                   11413:   /*free_vector(delti,1,npar);*/
                   11414:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11415:   free_matrix(agev,1,maxwav,1,imx);
                   11416:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11417:   
                   11418:   free_ivector(ncodemax,1,NCOVMAX);
                   11419:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11420:   free_ivector(Dummy,-1,NCOVMAX);
                   11421:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11422:   free_ivector(DummyV,1,NCOVMAX);
                   11423:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11424:   free_ivector(Typevar,-1,NCOVMAX);
                   11425:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11426:   free_ivector(TvarsQ,1,NCOVMAX);
                   11427:   free_ivector(TvarsQind,1,NCOVMAX);
                   11428:   free_ivector(TvarsD,1,NCOVMAX);
                   11429:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11430:   free_ivector(TvarFD,1,NCOVMAX);
                   11431:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11432:   free_ivector(TvarF,1,NCOVMAX);
                   11433:   free_ivector(TvarFind,1,NCOVMAX);
                   11434:   free_ivector(TvarV,1,NCOVMAX);
                   11435:   free_ivector(TvarVind,1,NCOVMAX);
                   11436:   free_ivector(TvarA,1,NCOVMAX);
                   11437:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11438:   free_ivector(TvarFQ,1,NCOVMAX);
                   11439:   free_ivector(TvarFQind,1,NCOVMAX);
                   11440:   free_ivector(TvarVD,1,NCOVMAX);
                   11441:   free_ivector(TvarVDind,1,NCOVMAX);
                   11442:   free_ivector(TvarVQ,1,NCOVMAX);
                   11443:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11444:   free_ivector(Tvarsel,1,NCOVMAX);
                   11445:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11446:   free_ivector(Tposprod,1,NCOVMAX);
                   11447:   free_ivector(Tprod,1,NCOVMAX);
                   11448:   free_ivector(Tvaraff,1,NCOVMAX);
                   11449:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11450:   free_ivector(Tage,1,NCOVMAX);
                   11451:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11452:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11453:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11454:   
                   11455:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11456:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11457:   fflush(fichtm);
                   11458:   fflush(ficgp);
                   11459:   
1.227     brouard  11460:   
1.126     brouard  11461:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11462:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11463:     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  11464:   }else{
                   11465:     printf("End of Imach\n");
                   11466:     fprintf(ficlog,"End of Imach\n");
                   11467:   }
                   11468:   printf("See log file on %s\n",filelog);
                   11469:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11470:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11471:   rend_time = time(NULL);  
                   11472:   end_time = *localtime(&rend_time);
                   11473:   /* tml = *localtime(&end_time.tm_sec); */
                   11474:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11475:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11476:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11477:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11478:   
1.157     brouard  11479:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11480:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11481:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11482:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11483: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11484:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11485:   fclose(fichtm);
                   11486:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11487:   fclose(fichtmcov);
                   11488:   fclose(ficgp);
                   11489:   fclose(ficlog);
                   11490:   /*------ End -----------*/
1.227     brouard  11491:   
                   11492:   
                   11493:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11494: #ifdef WIN32
1.227     brouard  11495:   if (_chdir(pathcd) != 0)
                   11496:     printf("Can't move to directory %s!\n",path);
                   11497:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11498: #else
1.227     brouard  11499:     if(chdir(pathcd) != 0)
                   11500:       printf("Can't move to directory %s!\n", path);
                   11501:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11502: #endif 
1.126     brouard  11503:     printf("Current directory %s!\n",pathcd);
                   11504:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11505:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11506: #ifdef _WIN32
1.126     brouard  11507:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11508: #endif
                   11509:   if(!stat(plotcmd,&info)){
1.158     brouard  11510:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11511:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11512:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11513:     }else
                   11514:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11515: #ifdef __unix
1.126     brouard  11516:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11517:     if(!stat(plotcmd,&info)){
1.158     brouard  11518:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11519:     }else
                   11520:       strcpy(pplotcmd,plotcmd);
                   11521: #endif
                   11522:   }else
                   11523:     strcpy(pplotcmd,plotcmd);
                   11524:   
                   11525:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11526:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11527:   
1.126     brouard  11528:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11529:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11530:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11531:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11532:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11533:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11534:   }
1.158     brouard  11535:   printf(" Successful, please wait...");
1.126     brouard  11536:   while (z[0] != 'q') {
                   11537:     /* chdir(path); */
1.154     brouard  11538:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11539:     scanf("%s",z);
                   11540: /*     if (z[0] == 'c') system("./imach"); */
                   11541:     if (z[0] == 'e') {
1.158     brouard  11542: #ifdef __APPLE__
1.152     brouard  11543:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11544: #elif __linux
                   11545:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11546: #else
1.152     brouard  11547:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11548: #endif
                   11549:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11550:       system(pplotcmd);
1.126     brouard  11551:     }
                   11552:     else if (z[0] == 'g') system(plotcmd);
                   11553:     else if (z[0] == 'q') exit(0);
                   11554:   }
1.227     brouard  11555: end:
1.126     brouard  11556:   while (z[0] != 'q') {
1.195     brouard  11557:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11558:     scanf("%s",z);
                   11559:   }
                   11560: }

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