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

1.245   ! brouard     1: /* $Id: imach.c,v 1.244 2016/09/02 07:17:34 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.245   ! brouard     4:   Revision 1.244  2016/09/02 07:17:34  brouard
        !             5:   *** empty log message ***
        !             6: 
1.244     brouard     7:   Revision 1.243  2016/09/02 06:45:35  brouard
                      8:   *** empty log message ***
                      9: 
1.243     brouard    10:   Revision 1.242  2016/08/30 15:01:20  brouard
                     11:   Summary: Fixing a lots
                     12: 
1.242     brouard    13:   Revision 1.241  2016/08/29 17:17:25  brouard
                     14:   Summary: gnuplot problem in Back projection to fix
                     15: 
1.241     brouard    16:   Revision 1.240  2016/08/29 07:53:18  brouard
                     17:   Summary: Better
                     18: 
1.240     brouard    19:   Revision 1.239  2016/08/26 15:51:03  brouard
                     20:   Summary: Improvement in Powell output in order to copy and paste
                     21: 
                     22:   Author:
                     23: 
1.239     brouard    24:   Revision 1.238  2016/08/26 14:23:35  brouard
                     25:   Summary: Starting tests of 0.99
                     26: 
1.238     brouard    27:   Revision 1.237  2016/08/26 09:20:19  brouard
                     28:   Summary: to valgrind
                     29: 
1.237     brouard    30:   Revision 1.236  2016/08/25 10:50:18  brouard
                     31:   *** empty log message ***
                     32: 
1.236     brouard    33:   Revision 1.235  2016/08/25 06:59:23  brouard
                     34:   *** empty log message ***
                     35: 
1.235     brouard    36:   Revision 1.234  2016/08/23 16:51:20  brouard
                     37:   *** empty log message ***
                     38: 
1.234     brouard    39:   Revision 1.233  2016/08/23 07:40:50  brouard
                     40:   Summary: not working
                     41: 
1.233     brouard    42:   Revision 1.232  2016/08/22 14:20:21  brouard
                     43:   Summary: not working
                     44: 
1.232     brouard    45:   Revision 1.231  2016/08/22 07:17:15  brouard
                     46:   Summary: not working
                     47: 
1.231     brouard    48:   Revision 1.230  2016/08/22 06:55:53  brouard
                     49:   Summary: Not working
                     50: 
1.230     brouard    51:   Revision 1.229  2016/07/23 09:45:53  brouard
                     52:   Summary: Completing for func too
                     53: 
1.229     brouard    54:   Revision 1.228  2016/07/22 17:45:30  brouard
                     55:   Summary: Fixing some arrays, still debugging
                     56: 
1.227     brouard    57:   Revision 1.226  2016/07/12 18:42:34  brouard
                     58:   Summary: temp
                     59: 
1.226     brouard    60:   Revision 1.225  2016/07/12 08:40:03  brouard
                     61:   Summary: saving but not running
                     62: 
1.225     brouard    63:   Revision 1.224  2016/07/01 13:16:01  brouard
                     64:   Summary: Fixes
                     65: 
1.224     brouard    66:   Revision 1.223  2016/02/19 09:23:35  brouard
                     67:   Summary: temporary
                     68: 
1.223     brouard    69:   Revision 1.222  2016/02/17 08:14:50  brouard
                     70:   Summary: Probably last 0.98 stable version 0.98r6
                     71: 
1.222     brouard    72:   Revision 1.221  2016/02/15 23:35:36  brouard
                     73:   Summary: minor bug
                     74: 
1.220     brouard    75:   Revision 1.219  2016/02/15 00:48:12  brouard
                     76:   *** empty log message ***
                     77: 
1.219     brouard    78:   Revision 1.218  2016/02/12 11:29:23  brouard
                     79:   Summary: 0.99 Back projections
                     80: 
1.218     brouard    81:   Revision 1.217  2015/12/23 17:18:31  brouard
                     82:   Summary: Experimental backcast
                     83: 
1.217     brouard    84:   Revision 1.216  2015/12/18 17:32:11  brouard
                     85:   Summary: 0.98r4 Warning and status=-2
                     86: 
                     87:   Version 0.98r4 is now:
                     88:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     89:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     90:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     91: 
1.216     brouard    92:   Revision 1.215  2015/12/16 08:52:24  brouard
                     93:   Summary: 0.98r4 working
                     94: 
1.215     brouard    95:   Revision 1.214  2015/12/16 06:57:54  brouard
                     96:   Summary: temporary not working
                     97: 
1.214     brouard    98:   Revision 1.213  2015/12/11 18:22:17  brouard
                     99:   Summary: 0.98r4
                    100: 
1.213     brouard   101:   Revision 1.212  2015/11/21 12:47:24  brouard
                    102:   Summary: minor typo
                    103: 
1.212     brouard   104:   Revision 1.211  2015/11/21 12:41:11  brouard
                    105:   Summary: 0.98r3 with some graph of projected cross-sectional
                    106: 
                    107:   Author: Nicolas Brouard
                    108: 
1.211     brouard   109:   Revision 1.210  2015/11/18 17:41:20  brouard
                    110:   Summary: Start working on projected prevalences
                    111: 
1.210     brouard   112:   Revision 1.209  2015/11/17 22:12:03  brouard
                    113:   Summary: Adding ftolpl parameter
                    114:   Author: N Brouard
                    115: 
                    116:   We had difficulties to get smoothed confidence intervals. It was due
                    117:   to the period prevalence which wasn't computed accurately. The inner
                    118:   parameter ftolpl is now an outer parameter of the .imach parameter
                    119:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    120:   computation are long.
                    121: 
1.209     brouard   122:   Revision 1.208  2015/11/17 14:31:57  brouard
                    123:   Summary: temporary
                    124: 
1.208     brouard   125:   Revision 1.207  2015/10/27 17:36:57  brouard
                    126:   *** empty log message ***
                    127: 
1.207     brouard   128:   Revision 1.206  2015/10/24 07:14:11  brouard
                    129:   *** empty log message ***
                    130: 
1.206     brouard   131:   Revision 1.205  2015/10/23 15:50:53  brouard
                    132:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    133: 
1.205     brouard   134:   Revision 1.204  2015/10/01 16:20:26  brouard
                    135:   Summary: Some new graphs of contribution to likelihood
                    136: 
1.204     brouard   137:   Revision 1.203  2015/09/30 17:45:14  brouard
                    138:   Summary: looking at better estimation of the hessian
                    139: 
                    140:   Also a better criteria for convergence to the period prevalence And
                    141:   therefore adding the number of years needed to converge. (The
                    142:   prevalence in any alive state shold sum to one
                    143: 
1.203     brouard   144:   Revision 1.202  2015/09/22 19:45:16  brouard
                    145:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    146: 
1.202     brouard   147:   Revision 1.201  2015/09/15 17:34:58  brouard
                    148:   Summary: 0.98r0
                    149: 
                    150:   - Some new graphs like suvival functions
                    151:   - Some bugs fixed like model=1+age+V2.
                    152: 
1.201     brouard   153:   Revision 1.200  2015/09/09 16:53:55  brouard
                    154:   Summary: Big bug thanks to Flavia
                    155: 
                    156:   Even model=1+age+V2. did not work anymore
                    157: 
1.200     brouard   158:   Revision 1.199  2015/09/07 14:09:23  brouard
                    159:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    160: 
1.199     brouard   161:   Revision 1.198  2015/09/03 07:14:39  brouard
                    162:   Summary: 0.98q5 Flavia
                    163: 
1.198     brouard   164:   Revision 1.197  2015/09/01 18:24:39  brouard
                    165:   *** empty log message ***
                    166: 
1.197     brouard   167:   Revision 1.196  2015/08/18 23:17:52  brouard
                    168:   Summary: 0.98q5
                    169: 
1.196     brouard   170:   Revision 1.195  2015/08/18 16:28:39  brouard
                    171:   Summary: Adding a hack for testing purpose
                    172: 
                    173:   After reading the title, ftol and model lines, if the comment line has
                    174:   a q, starting with #q, the answer at the end of the run is quit. It
                    175:   permits to run test files in batch with ctest. The former workaround was
                    176:   $ echo q | imach foo.imach
                    177: 
1.195     brouard   178:   Revision 1.194  2015/08/18 13:32:00  brouard
                    179:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    180: 
1.194     brouard   181:   Revision 1.193  2015/08/04 07:17:42  brouard
                    182:   Summary: 0.98q4
                    183: 
1.193     brouard   184:   Revision 1.192  2015/07/16 16:49:02  brouard
                    185:   Summary: Fixing some outputs
                    186: 
1.192     brouard   187:   Revision 1.191  2015/07/14 10:00:33  brouard
                    188:   Summary: Some fixes
                    189: 
1.191     brouard   190:   Revision 1.190  2015/05/05 08:51:13  brouard
                    191:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    192: 
                    193:   Fix 1+age+.
                    194: 
1.190     brouard   195:   Revision 1.189  2015/04/30 14:45:16  brouard
                    196:   Summary: 0.98q2
                    197: 
1.189     brouard   198:   Revision 1.188  2015/04/30 08:27:53  brouard
                    199:   *** empty log message ***
                    200: 
1.188     brouard   201:   Revision 1.187  2015/04/29 09:11:15  brouard
                    202:   *** empty log message ***
                    203: 
1.187     brouard   204:   Revision 1.186  2015/04/23 12:01:52  brouard
                    205:   Summary: V1*age is working now, version 0.98q1
                    206: 
                    207:   Some codes had been disabled in order to simplify and Vn*age was
                    208:   working in the optimization phase, ie, giving correct MLE parameters,
                    209:   but, as usual, outputs were not correct and program core dumped.
                    210: 
1.186     brouard   211:   Revision 1.185  2015/03/11 13:26:42  brouard
                    212:   Summary: Inclusion of compile and links command line for Intel Compiler
                    213: 
1.185     brouard   214:   Revision 1.184  2015/03/11 11:52:39  brouard
                    215:   Summary: Back from Windows 8. Intel Compiler
                    216: 
1.184     brouard   217:   Revision 1.183  2015/03/10 20:34:32  brouard
                    218:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    219: 
                    220:   We use directest instead of original Powell test; probably no
                    221:   incidence on the results, but better justifications;
                    222:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    223:   wrong results.
                    224: 
1.183     brouard   225:   Revision 1.182  2015/02/12 08:19:57  brouard
                    226:   Summary: Trying to keep directest which seems simpler and more general
                    227:   Author: Nicolas Brouard
                    228: 
1.182     brouard   229:   Revision 1.181  2015/02/11 23:22:24  brouard
                    230:   Summary: Comments on Powell added
                    231: 
                    232:   Author:
                    233: 
1.181     brouard   234:   Revision 1.180  2015/02/11 17:33:45  brouard
                    235:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    236: 
1.180     brouard   237:   Revision 1.179  2015/01/04 09:57:06  brouard
                    238:   Summary: back to OS/X
                    239: 
1.179     brouard   240:   Revision 1.178  2015/01/04 09:35:48  brouard
                    241:   *** empty log message ***
                    242: 
1.178     brouard   243:   Revision 1.177  2015/01/03 18:40:56  brouard
                    244:   Summary: Still testing ilc32 on OSX
                    245: 
1.177     brouard   246:   Revision 1.176  2015/01/03 16:45:04  brouard
                    247:   *** empty log message ***
                    248: 
1.176     brouard   249:   Revision 1.175  2015/01/03 16:33:42  brouard
                    250:   *** empty log message ***
                    251: 
1.175     brouard   252:   Revision 1.174  2015/01/03 16:15:49  brouard
                    253:   Summary: Still in cross-compilation
                    254: 
1.174     brouard   255:   Revision 1.173  2015/01/03 12:06:26  brouard
                    256:   Summary: trying to detect cross-compilation
                    257: 
1.173     brouard   258:   Revision 1.172  2014/12/27 12:07:47  brouard
                    259:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    260: 
1.172     brouard   261:   Revision 1.171  2014/12/23 13:26:59  brouard
                    262:   Summary: Back from Visual C
                    263: 
                    264:   Still problem with utsname.h on Windows
                    265: 
1.171     brouard   266:   Revision 1.170  2014/12/23 11:17:12  brouard
                    267:   Summary: Cleaning some \%% back to %%
                    268: 
                    269:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    270: 
1.170     brouard   271:   Revision 1.169  2014/12/22 23:08:31  brouard
                    272:   Summary: 0.98p
                    273: 
                    274:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    275: 
1.169     brouard   276:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   277:   Summary: update
1.169     brouard   278: 
1.168     brouard   279:   Revision 1.167  2014/12/22 13:50:56  brouard
                    280:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    281: 
                    282:   Testing on Linux 64
                    283: 
1.167     brouard   284:   Revision 1.166  2014/12/22 11:40:47  brouard
                    285:   *** empty log message ***
                    286: 
1.166     brouard   287:   Revision 1.165  2014/12/16 11:20:36  brouard
                    288:   Summary: After compiling on Visual C
                    289: 
                    290:   * imach.c (Module): Merging 1.61 to 1.162
                    291: 
1.165     brouard   292:   Revision 1.164  2014/12/16 10:52:11  brouard
                    293:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    294: 
                    295:   * imach.c (Module): Merging 1.61 to 1.162
                    296: 
1.164     brouard   297:   Revision 1.163  2014/12/16 10:30:11  brouard
                    298:   * imach.c (Module): Merging 1.61 to 1.162
                    299: 
1.163     brouard   300:   Revision 1.162  2014/09/25 11:43:39  brouard
                    301:   Summary: temporary backup 0.99!
                    302: 
1.162     brouard   303:   Revision 1.1  2014/09/16 11:06:58  brouard
                    304:   Summary: With some code (wrong) for nlopt
                    305: 
                    306:   Author:
                    307: 
                    308:   Revision 1.161  2014/09/15 20:41:41  brouard
                    309:   Summary: Problem with macro SQR on Intel compiler
                    310: 
1.161     brouard   311:   Revision 1.160  2014/09/02 09:24:05  brouard
                    312:   *** empty log message ***
                    313: 
1.160     brouard   314:   Revision 1.159  2014/09/01 10:34:10  brouard
                    315:   Summary: WIN32
                    316:   Author: Brouard
                    317: 
1.159     brouard   318:   Revision 1.158  2014/08/27 17:11:51  brouard
                    319:   *** empty log message ***
                    320: 
1.158     brouard   321:   Revision 1.157  2014/08/27 16:26:55  brouard
                    322:   Summary: Preparing windows Visual studio version
                    323:   Author: Brouard
                    324: 
                    325:   In order to compile on Visual studio, time.h is now correct and time_t
                    326:   and tm struct should be used. difftime should be used but sometimes I
                    327:   just make the differences in raw time format (time(&now).
                    328:   Trying to suppress #ifdef LINUX
                    329:   Add xdg-open for __linux in order to open default browser.
                    330: 
1.157     brouard   331:   Revision 1.156  2014/08/25 20:10:10  brouard
                    332:   *** empty log message ***
                    333: 
1.156     brouard   334:   Revision 1.155  2014/08/25 18:32:34  brouard
                    335:   Summary: New compile, minor changes
                    336:   Author: Brouard
                    337: 
1.155     brouard   338:   Revision 1.154  2014/06/20 17:32:08  brouard
                    339:   Summary: Outputs now all graphs of convergence to period prevalence
                    340: 
1.154     brouard   341:   Revision 1.153  2014/06/20 16:45:46  brouard
                    342:   Summary: If 3 live state, convergence to period prevalence on same graph
                    343:   Author: Brouard
                    344: 
1.153     brouard   345:   Revision 1.152  2014/06/18 17:54:09  brouard
                    346:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    347: 
1.152     brouard   348:   Revision 1.151  2014/06/18 16:43:30  brouard
                    349:   *** empty log message ***
                    350: 
1.151     brouard   351:   Revision 1.150  2014/06/18 16:42:35  brouard
                    352:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    353:   Author: brouard
                    354: 
1.150     brouard   355:   Revision 1.149  2014/06/18 15:51:14  brouard
                    356:   Summary: Some fixes in parameter files errors
                    357:   Author: Nicolas Brouard
                    358: 
1.149     brouard   359:   Revision 1.148  2014/06/17 17:38:48  brouard
                    360:   Summary: Nothing new
                    361:   Author: Brouard
                    362: 
                    363:   Just a new packaging for OS/X version 0.98nS
                    364: 
1.148     brouard   365:   Revision 1.147  2014/06/16 10:33:11  brouard
                    366:   *** empty log message ***
                    367: 
1.147     brouard   368:   Revision 1.146  2014/06/16 10:20:28  brouard
                    369:   Summary: Merge
                    370:   Author: Brouard
                    371: 
                    372:   Merge, before building revised version.
                    373: 
1.146     brouard   374:   Revision 1.145  2014/06/10 21:23:15  brouard
                    375:   Summary: Debugging with valgrind
                    376:   Author: Nicolas Brouard
                    377: 
                    378:   Lot of changes in order to output the results with some covariates
                    379:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    380:   improve the code.
                    381:   No more memory valgrind error but a lot has to be done in order to
                    382:   continue the work of splitting the code into subroutines.
                    383:   Also, decodemodel has been improved. Tricode is still not
                    384:   optimal. nbcode should be improved. Documentation has been added in
                    385:   the source code.
                    386: 
1.144     brouard   387:   Revision 1.143  2014/01/26 09:45:38  brouard
                    388:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    389: 
                    390:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    391:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    392: 
1.143     brouard   393:   Revision 1.142  2014/01/26 03:57:36  brouard
                    394:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    395: 
                    396:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    397: 
1.142     brouard   398:   Revision 1.141  2014/01/26 02:42:01  brouard
                    399:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    400: 
1.141     brouard   401:   Revision 1.140  2011/09/02 10:37:54  brouard
                    402:   Summary: times.h is ok with mingw32 now.
                    403: 
1.140     brouard   404:   Revision 1.139  2010/06/14 07:50:17  brouard
                    405:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    406:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    407: 
1.139     brouard   408:   Revision 1.138  2010/04/30 18:19:40  brouard
                    409:   *** empty log message ***
                    410: 
1.138     brouard   411:   Revision 1.137  2010/04/29 18:11:38  brouard
                    412:   (Module): Checking covariates for more complex models
                    413:   than V1+V2. A lot of change to be done. Unstable.
                    414: 
1.137     brouard   415:   Revision 1.136  2010/04/26 20:30:53  brouard
                    416:   (Module): merging some libgsl code. Fixing computation
                    417:   of likelione (using inter/intrapolation if mle = 0) in order to
                    418:   get same likelihood as if mle=1.
                    419:   Some cleaning of code and comments added.
                    420: 
1.136     brouard   421:   Revision 1.135  2009/10/29 15:33:14  brouard
                    422:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    423: 
1.135     brouard   424:   Revision 1.134  2009/10/29 13:18:53  brouard
                    425:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    426: 
1.134     brouard   427:   Revision 1.133  2009/07/06 10:21:25  brouard
                    428:   just nforces
                    429: 
1.133     brouard   430:   Revision 1.132  2009/07/06 08:22:05  brouard
                    431:   Many tings
                    432: 
1.132     brouard   433:   Revision 1.131  2009/06/20 16:22:47  brouard
                    434:   Some dimensions resccaled
                    435: 
1.131     brouard   436:   Revision 1.130  2009/05/26 06:44:34  brouard
                    437:   (Module): Max Covariate is now set to 20 instead of 8. A
                    438:   lot of cleaning with variables initialized to 0. Trying to make
                    439:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    440: 
1.130     brouard   441:   Revision 1.129  2007/08/31 13:49:27  lievre
                    442:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    443: 
1.129     lievre    444:   Revision 1.128  2006/06/30 13:02:05  brouard
                    445:   (Module): Clarifications on computing e.j
                    446: 
1.128     brouard   447:   Revision 1.127  2006/04/28 18:11:50  brouard
                    448:   (Module): Yes the sum of survivors was wrong since
                    449:   imach-114 because nhstepm was no more computed in the age
                    450:   loop. Now we define nhstepma in the age loop.
                    451:   (Module): In order to speed up (in case of numerous covariates) we
                    452:   compute health expectancies (without variances) in a first step
                    453:   and then all the health expectancies with variances or standard
                    454:   deviation (needs data from the Hessian matrices) which slows the
                    455:   computation.
                    456:   In the future we should be able to stop the program is only health
                    457:   expectancies and graph are needed without standard deviations.
                    458: 
1.127     brouard   459:   Revision 1.126  2006/04/28 17:23:28  brouard
                    460:   (Module): Yes the sum of survivors was wrong since
                    461:   imach-114 because nhstepm was no more computed in the age
                    462:   loop. Now we define nhstepma in the age loop.
                    463:   Version 0.98h
                    464: 
1.126     brouard   465:   Revision 1.125  2006/04/04 15:20:31  lievre
                    466:   Errors in calculation of health expectancies. Age was not initialized.
                    467:   Forecasting file added.
                    468: 
                    469:   Revision 1.124  2006/03/22 17:13:53  lievre
                    470:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    471:   The log-likelihood is printed in the log file
                    472: 
                    473:   Revision 1.123  2006/03/20 10:52:43  brouard
                    474:   * imach.c (Module): <title> changed, corresponds to .htm file
                    475:   name. <head> headers where missing.
                    476: 
                    477:   * imach.c (Module): Weights can have a decimal point as for
                    478:   English (a comma might work with a correct LC_NUMERIC environment,
                    479:   otherwise the weight is truncated).
                    480:   Modification of warning when the covariates values are not 0 or
                    481:   1.
                    482:   Version 0.98g
                    483: 
                    484:   Revision 1.122  2006/03/20 09:45:41  brouard
                    485:   (Module): Weights can have a decimal point as for
                    486:   English (a comma might work with a correct LC_NUMERIC environment,
                    487:   otherwise the weight is truncated).
                    488:   Modification of warning when the covariates values are not 0 or
                    489:   1.
                    490:   Version 0.98g
                    491: 
                    492:   Revision 1.121  2006/03/16 17:45:01  lievre
                    493:   * imach.c (Module): Comments concerning covariates added
                    494: 
                    495:   * imach.c (Module): refinements in the computation of lli if
                    496:   status=-2 in order to have more reliable computation if stepm is
                    497:   not 1 month. Version 0.98f
                    498: 
                    499:   Revision 1.120  2006/03/16 15:10:38  lievre
                    500:   (Module): refinements in the computation of lli if
                    501:   status=-2 in order to have more reliable computation if stepm is
                    502:   not 1 month. Version 0.98f
                    503: 
                    504:   Revision 1.119  2006/03/15 17:42:26  brouard
                    505:   (Module): Bug if status = -2, the loglikelihood was
                    506:   computed as likelihood omitting the logarithm. Version O.98e
                    507: 
                    508:   Revision 1.118  2006/03/14 18:20:07  brouard
                    509:   (Module): varevsij Comments added explaining the second
                    510:   table of variances if popbased=1 .
                    511:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    512:   (Module): Function pstamp added
                    513:   (Module): Version 0.98d
                    514: 
                    515:   Revision 1.117  2006/03/14 17:16:22  brouard
                    516:   (Module): varevsij Comments added explaining the second
                    517:   table of variances if popbased=1 .
                    518:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    519:   (Module): Function pstamp added
                    520:   (Module): Version 0.98d
                    521: 
                    522:   Revision 1.116  2006/03/06 10:29:27  brouard
                    523:   (Module): Variance-covariance wrong links and
                    524:   varian-covariance of ej. is needed (Saito).
                    525: 
                    526:   Revision 1.115  2006/02/27 12:17:45  brouard
                    527:   (Module): One freematrix added in mlikeli! 0.98c
                    528: 
                    529:   Revision 1.114  2006/02/26 12:57:58  brouard
                    530:   (Module): Some improvements in processing parameter
                    531:   filename with strsep.
                    532: 
                    533:   Revision 1.113  2006/02/24 14:20:24  brouard
                    534:   (Module): Memory leaks checks with valgrind and:
                    535:   datafile was not closed, some imatrix were not freed and on matrix
                    536:   allocation too.
                    537: 
                    538:   Revision 1.112  2006/01/30 09:55:26  brouard
                    539:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    540: 
                    541:   Revision 1.111  2006/01/25 20:38:18  brouard
                    542:   (Module): Lots of cleaning and bugs added (Gompertz)
                    543:   (Module): Comments can be added in data file. Missing date values
                    544:   can be a simple dot '.'.
                    545: 
                    546:   Revision 1.110  2006/01/25 00:51:50  brouard
                    547:   (Module): Lots of cleaning and bugs added (Gompertz)
                    548: 
                    549:   Revision 1.109  2006/01/24 19:37:15  brouard
                    550:   (Module): Comments (lines starting with a #) are allowed in data.
                    551: 
                    552:   Revision 1.108  2006/01/19 18:05:42  lievre
                    553:   Gnuplot problem appeared...
                    554:   To be fixed
                    555: 
                    556:   Revision 1.107  2006/01/19 16:20:37  brouard
                    557:   Test existence of gnuplot in imach path
                    558: 
                    559:   Revision 1.106  2006/01/19 13:24:36  brouard
                    560:   Some cleaning and links added in html output
                    561: 
                    562:   Revision 1.105  2006/01/05 20:23:19  lievre
                    563:   *** empty log message ***
                    564: 
                    565:   Revision 1.104  2005/09/30 16:11:43  lievre
                    566:   (Module): sump fixed, loop imx fixed, and simplifications.
                    567:   (Module): If the status is missing at the last wave but we know
                    568:   that the person is alive, then we can code his/her status as -2
                    569:   (instead of missing=-1 in earlier versions) and his/her
                    570:   contributions to the likelihood is 1 - Prob of dying from last
                    571:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    572:   the healthy state at last known wave). Version is 0.98
                    573: 
                    574:   Revision 1.103  2005/09/30 15:54:49  lievre
                    575:   (Module): sump fixed, loop imx fixed, and simplifications.
                    576: 
                    577:   Revision 1.102  2004/09/15 17:31:30  brouard
                    578:   Add the possibility to read data file including tab characters.
                    579: 
                    580:   Revision 1.101  2004/09/15 10:38:38  brouard
                    581:   Fix on curr_time
                    582: 
                    583:   Revision 1.100  2004/07/12 18:29:06  brouard
                    584:   Add version for Mac OS X. Just define UNIX in Makefile
                    585: 
                    586:   Revision 1.99  2004/06/05 08:57:40  brouard
                    587:   *** empty log message ***
                    588: 
                    589:   Revision 1.98  2004/05/16 15:05:56  brouard
                    590:   New version 0.97 . First attempt to estimate force of mortality
                    591:   directly from the data i.e. without the need of knowing the health
                    592:   state at each age, but using a Gompertz model: log u =a + b*age .
                    593:   This is the basic analysis of mortality and should be done before any
                    594:   other analysis, in order to test if the mortality estimated from the
                    595:   cross-longitudinal survey is different from the mortality estimated
                    596:   from other sources like vital statistic data.
                    597: 
                    598:   The same imach parameter file can be used but the option for mle should be -3.
                    599: 
1.133     brouard   600:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   601:   former routines in order to include the new code within the former code.
                    602: 
                    603:   The output is very simple: only an estimate of the intercept and of
                    604:   the slope with 95% confident intervals.
                    605: 
                    606:   Current limitations:
                    607:   A) Even if you enter covariates, i.e. with the
                    608:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    609:   B) There is no computation of Life Expectancy nor Life Table.
                    610: 
                    611:   Revision 1.97  2004/02/20 13:25:42  lievre
                    612:   Version 0.96d. Population forecasting command line is (temporarily)
                    613:   suppressed.
                    614: 
                    615:   Revision 1.96  2003/07/15 15:38:55  brouard
                    616:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    617:   rewritten within the same printf. Workaround: many printfs.
                    618: 
                    619:   Revision 1.95  2003/07/08 07:54:34  brouard
                    620:   * imach.c (Repository):
                    621:   (Repository): Using imachwizard code to output a more meaningful covariance
                    622:   matrix (cov(a12,c31) instead of numbers.
                    623: 
                    624:   Revision 1.94  2003/06/27 13:00:02  brouard
                    625:   Just cleaning
                    626: 
                    627:   Revision 1.93  2003/06/25 16:33:55  brouard
                    628:   (Module): On windows (cygwin) function asctime_r doesn't
                    629:   exist so I changed back to asctime which exists.
                    630:   (Module): Version 0.96b
                    631: 
                    632:   Revision 1.92  2003/06/25 16:30:45  brouard
                    633:   (Module): On windows (cygwin) function asctime_r doesn't
                    634:   exist so I changed back to asctime which exists.
                    635: 
                    636:   Revision 1.91  2003/06/25 15:30:29  brouard
                    637:   * imach.c (Repository): Duplicated warning errors corrected.
                    638:   (Repository): Elapsed time after each iteration is now output. It
                    639:   helps to forecast when convergence will be reached. Elapsed time
                    640:   is stamped in powell.  We created a new html file for the graphs
                    641:   concerning matrix of covariance. It has extension -cov.htm.
                    642: 
                    643:   Revision 1.90  2003/06/24 12:34:15  brouard
                    644:   (Module): Some bugs corrected for windows. Also, when
                    645:   mle=-1 a template is output in file "or"mypar.txt with the design
                    646:   of the covariance matrix to be input.
                    647: 
                    648:   Revision 1.89  2003/06/24 12:30:52  brouard
                    649:   (Module): Some bugs corrected for windows. Also, when
                    650:   mle=-1 a template is output in file "or"mypar.txt with the design
                    651:   of the covariance matrix to be input.
                    652: 
                    653:   Revision 1.88  2003/06/23 17:54:56  brouard
                    654:   * 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.
                    655: 
                    656:   Revision 1.87  2003/06/18 12:26:01  brouard
                    657:   Version 0.96
                    658: 
                    659:   Revision 1.86  2003/06/17 20:04:08  brouard
                    660:   (Module): Change position of html and gnuplot routines and added
                    661:   routine fileappend.
                    662: 
                    663:   Revision 1.85  2003/06/17 13:12:43  brouard
                    664:   * imach.c (Repository): Check when date of death was earlier that
                    665:   current date of interview. It may happen when the death was just
                    666:   prior to the death. In this case, dh was negative and likelihood
                    667:   was wrong (infinity). We still send an "Error" but patch by
                    668:   assuming that the date of death was just one stepm after the
                    669:   interview.
                    670:   (Repository): Because some people have very long ID (first column)
                    671:   we changed int to long in num[] and we added a new lvector for
                    672:   memory allocation. But we also truncated to 8 characters (left
                    673:   truncation)
                    674:   (Repository): No more line truncation errors.
                    675: 
                    676:   Revision 1.84  2003/06/13 21:44:43  brouard
                    677:   * imach.c (Repository): Replace "freqsummary" at a correct
                    678:   place. It differs from routine "prevalence" which may be called
                    679:   many times. Probs is memory consuming and must be used with
                    680:   parcimony.
                    681:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    682: 
                    683:   Revision 1.83  2003/06/10 13:39:11  lievre
                    684:   *** empty log message ***
                    685: 
                    686:   Revision 1.82  2003/06/05 15:57:20  brouard
                    687:   Add log in  imach.c and  fullversion number is now printed.
                    688: 
                    689: */
                    690: /*
                    691:    Interpolated Markov Chain
                    692: 
                    693:   Short summary of the programme:
                    694:   
1.227     brouard   695:   This program computes Healthy Life Expectancies or State-specific
                    696:   (if states aren't health statuses) Expectancies from
                    697:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    698: 
                    699:   -1- a first survey ("cross") where individuals from different ages
                    700:   are interviewed on their health status or degree of disability (in
                    701:   the case of a health survey which is our main interest)
                    702: 
                    703:   -2- at least a second wave of interviews ("longitudinal") which
                    704:   measure each change (if any) in individual health status.  Health
                    705:   expectancies are computed from the time spent in each health state
                    706:   according to a model. More health states you consider, more time is
                    707:   necessary to reach the Maximum Likelihood of the parameters involved
                    708:   in the model.  The simplest model is the multinomial logistic model
                    709:   where pij is the probability to be observed in state j at the second
                    710:   wave conditional to be observed in state i at the first
                    711:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    712:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    713:   have a more complex model than "constant and age", you should modify
                    714:   the program where the markup *Covariates have to be included here
                    715:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   716:   convergence.
                    717: 
                    718:   The advantage of this computer programme, compared to a simple
                    719:   multinomial logistic model, is clear when the delay between waves is not
                    720:   identical for each individual. Also, if a individual missed an
                    721:   intermediate interview, the information is lost, but taken into
                    722:   account using an interpolation or extrapolation.  
                    723: 
                    724:   hPijx is the probability to be observed in state i at age x+h
                    725:   conditional to the observed state i at age x. The delay 'h' can be
                    726:   split into an exact number (nh*stepm) of unobserved intermediate
                    727:   states. This elementary transition (by month, quarter,
                    728:   semester or year) is modelled as a multinomial logistic.  The hPx
                    729:   matrix is simply the matrix product of nh*stepm elementary matrices
                    730:   and the contribution of each individual to the likelihood is simply
                    731:   hPijx.
                    732: 
                    733:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   734:   of the life expectancies. It also computes the period (stable) prevalence.
                    735: 
                    736: Back prevalence and projections:
1.227     brouard   737: 
                    738:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    739:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    740:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    741:    mobilavproj)
                    742: 
                    743:     Computes the back prevalence limit for any combination of
                    744:     covariate values k at any age between ageminpar and agemaxpar and
                    745:     returns it in **bprlim. In the loops,
                    746: 
                    747:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    748:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    749: 
                    750:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   751:    Computes for any combination of covariates k and any age between bage and fage 
                    752:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    753:                        oldm=oldms;savm=savms;
1.227     brouard   754: 
                    755:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   756:      Computes the transition matrix starting at age 'age' over
                    757:      'nhstepm*hstepm*stepm' months (i.e. until
                    758:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   759:      nhstepm*hstepm matrices. 
                    760: 
                    761:      Returns p3mat[i][j][h] after calling
                    762:      p3mat[i][j][h]=matprod2(newm,
                    763:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    764:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    765:      oldm);
1.226     brouard   766: 
                    767: Important routines
                    768: 
                    769: - func (or funcone), computes logit (pij) distinguishing
                    770:   o fixed variables (single or product dummies or quantitative);
                    771:   o varying variables by:
                    772:    (1) wave (single, product dummies, quantitative), 
                    773:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    774:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    775:        % varying dummy (not done) or quantitative (not done);
                    776: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    777:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    778: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    779:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    780:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   781: 
1.226     brouard   782: 
                    783:   
1.133     brouard   784:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    785:            Institut national d'études démographiques, Paris.
1.126     brouard   786:   This software have been partly granted by Euro-REVES, a concerted action
                    787:   from the European Union.
                    788:   It is copyrighted identically to a GNU software product, ie programme and
                    789:   software can be distributed freely for non commercial use. Latest version
                    790:   can be accessed at http://euroreves.ined.fr/imach .
                    791: 
                    792:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    793:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    794:   
                    795:   **********************************************************************/
                    796: /*
                    797:   main
                    798:   read parameterfile
                    799:   read datafile
                    800:   concatwav
                    801:   freqsummary
                    802:   if (mle >= 1)
                    803:     mlikeli
                    804:   print results files
                    805:   if mle==1 
                    806:      computes hessian
                    807:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    808:       begin-prev-date,...
                    809:   open gnuplot file
                    810:   open html file
1.145     brouard   811:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    812:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    813:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    814:     freexexit2 possible for memory heap.
                    815: 
                    816:   h Pij x                         | pij_nom  ficrestpij
                    817:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    818:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    819:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    820: 
                    821:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    822:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    823:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    824:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    825:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    826: 
1.126     brouard   827:   forecasting if prevfcast==1 prevforecast call prevalence()
                    828:   health expectancies
                    829:   Variance-covariance of DFLE
                    830:   prevalence()
                    831:    movingaverage()
                    832:   varevsij() 
                    833:   if popbased==1 varevsij(,popbased)
                    834:   total life expectancies
                    835:   Variance of period (stable) prevalence
                    836:  end
                    837: */
                    838: 
1.187     brouard   839: /* #define DEBUG */
                    840: /* #define DEBUGBRENT */
1.203     brouard   841: /* #define DEBUGLINMIN */
                    842: /* #define DEBUGHESS */
                    843: #define DEBUGHESSIJ
1.224     brouard   844: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   845: #define POWELL /* Instead of NLOPT */
1.224     brouard   846: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   847: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    848: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   849: 
                    850: #include <math.h>
                    851: #include <stdio.h>
                    852: #include <stdlib.h>
                    853: #include <string.h>
1.226     brouard   854: #include <ctype.h>
1.159     brouard   855: 
                    856: #ifdef _WIN32
                    857: #include <io.h>
1.172     brouard   858: #include <windows.h>
                    859: #include <tchar.h>
1.159     brouard   860: #else
1.126     brouard   861: #include <unistd.h>
1.159     brouard   862: #endif
1.126     brouard   863: 
                    864: #include <limits.h>
                    865: #include <sys/types.h>
1.171     brouard   866: 
                    867: #if defined(__GNUC__)
                    868: #include <sys/utsname.h> /* Doesn't work on Windows */
                    869: #endif
                    870: 
1.126     brouard   871: #include <sys/stat.h>
                    872: #include <errno.h>
1.159     brouard   873: /* extern int errno; */
1.126     brouard   874: 
1.157     brouard   875: /* #ifdef LINUX */
                    876: /* #include <time.h> */
                    877: /* #include "timeval.h" */
                    878: /* #else */
                    879: /* #include <sys/time.h> */
                    880: /* #endif */
                    881: 
1.126     brouard   882: #include <time.h>
                    883: 
1.136     brouard   884: #ifdef GSL
                    885: #include <gsl/gsl_errno.h>
                    886: #include <gsl/gsl_multimin.h>
                    887: #endif
                    888: 
1.167     brouard   889: 
1.162     brouard   890: #ifdef NLOPT
                    891: #include <nlopt.h>
                    892: typedef struct {
                    893:   double (* function)(double [] );
                    894: } myfunc_data ;
                    895: #endif
                    896: 
1.126     brouard   897: /* #include <libintl.h> */
                    898: /* #define _(String) gettext (String) */
                    899: 
1.141     brouard   900: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   901: 
                    902: #define GNUPLOTPROGRAM "gnuplot"
                    903: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    904: #define FILENAMELENGTH 132
                    905: 
                    906: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    907: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    908: 
1.144     brouard   909: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    910: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   911: 
                    912: #define NINTERVMAX 8
1.144     brouard   913: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    914: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    915: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   916: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   917: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    918: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   919: #define MAXN 20000
1.144     brouard   920: #define YEARM 12. /**< Number of months per year */
1.218     brouard   921: /* #define AGESUP 130 */
                    922: #define AGESUP 150
                    923: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   924: #define AGEBASE 40
1.194     brouard   925: #define AGEOVERFLOW 1.e20
1.164     brouard   926: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   927: #ifdef _WIN32
                    928: #define DIRSEPARATOR '\\'
                    929: #define CHARSEPARATOR "\\"
                    930: #define ODIRSEPARATOR '/'
                    931: #else
1.126     brouard   932: #define DIRSEPARATOR '/'
                    933: #define CHARSEPARATOR "/"
                    934: #define ODIRSEPARATOR '\\'
                    935: #endif
                    936: 
1.245   ! brouard   937: /* $Id: imach.c,v 1.244 2016/09/02 07:17:34 brouard Exp $ */
1.126     brouard   938: /* $State: Exp $ */
1.196     brouard   939: #include "version.h"
                    940: char version[]=__IMACH_VERSION__;
1.224     brouard   941: 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.245   ! brouard   942: char fullversion[]="$Revision: 1.244 $ $Date: 2016/09/02 07:17:34 $"; 
1.126     brouard   943: char strstart[80];
                    944: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   945: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   946: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   947: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    948: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    949: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   950: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    951: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   952: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    953: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    954: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   955: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    956: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   957: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   958: int nsd=0; /**< Total number of single dummy variables (output) */
                    959: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   960: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   961: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   962: int ntveff=0; /**< ntveff number of effective time varying variables */
                    963: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   964: int cptcov=0; /* Working variable */
1.218     brouard   965: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   966: int npar=NPARMAX;
                    967: int nlstate=2; /* Number of live states */
                    968: int ndeath=1; /* Number of dead states */
1.130     brouard   969: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   970: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   971: int popbased=0;
                    972: 
                    973: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   974: int maxwav=0; /* Maxim number of waves */
                    975: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    976: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    977: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   978:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   979: int mle=1, weightopt=0;
1.126     brouard   980: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    981: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    982: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    983:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   984: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   985: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    986: 
1.130     brouard   987: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   988: double **matprod2(); /* test */
1.126     brouard   989: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    990: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   991: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    992: 
1.136     brouard   993: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   994: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   995: FILE *ficlog, *ficrespow;
1.130     brouard   996: int globpr=0; /* Global variable for printing or not */
1.126     brouard   997: double fretone; /* Only one call to likelihood */
1.130     brouard   998: long ipmx=0; /* Number of contributions */
1.126     brouard   999: double sw; /* Sum of weights */
                   1000: char filerespow[FILENAMELENGTH];
                   1001: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1002: FILE *ficresilk;
                   1003: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1004: FILE *ficresprobmorprev;
                   1005: FILE *fichtm, *fichtmcov; /* Html File */
                   1006: FILE *ficreseij;
                   1007: char filerese[FILENAMELENGTH];
                   1008: FILE *ficresstdeij;
                   1009: char fileresstde[FILENAMELENGTH];
                   1010: FILE *ficrescveij;
                   1011: char filerescve[FILENAMELENGTH];
                   1012: FILE  *ficresvij;
                   1013: char fileresv[FILENAMELENGTH];
                   1014: FILE  *ficresvpl;
                   1015: char fileresvpl[FILENAMELENGTH];
                   1016: char title[MAXLINE];
1.234     brouard  1017: char model[MAXLINE]; /**< The model line */
1.217     brouard  1018: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1019: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1020: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1021: char command[FILENAMELENGTH];
                   1022: int  outcmd=0;
                   1023: 
1.217     brouard  1024: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1025: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1026: char filelog[FILENAMELENGTH]; /* Log file */
                   1027: char filerest[FILENAMELENGTH];
                   1028: char fileregp[FILENAMELENGTH];
                   1029: char popfile[FILENAMELENGTH];
                   1030: 
                   1031: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1032: 
1.157     brouard  1033: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1034: /* struct timezone tzp; */
                   1035: /* extern int gettimeofday(); */
                   1036: struct tm tml, *gmtime(), *localtime();
                   1037: 
                   1038: extern time_t time();
                   1039: 
                   1040: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1041: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1042: struct tm tm;
                   1043: 
1.126     brouard  1044: char strcurr[80], strfor[80];
                   1045: 
                   1046: char *endptr;
                   1047: long lval;
                   1048: double dval;
                   1049: 
                   1050: #define NR_END 1
                   1051: #define FREE_ARG char*
                   1052: #define FTOL 1.0e-10
                   1053: 
                   1054: #define NRANSI 
1.240     brouard  1055: #define ITMAX 200
                   1056: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1057: 
                   1058: #define TOL 2.0e-4 
                   1059: 
                   1060: #define CGOLD 0.3819660 
                   1061: #define ZEPS 1.0e-10 
                   1062: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1063: 
                   1064: #define GOLD 1.618034 
                   1065: #define GLIMIT 100.0 
                   1066: #define TINY 1.0e-20 
                   1067: 
                   1068: static double maxarg1,maxarg2;
                   1069: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1070: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1071:   
                   1072: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1073: #define rint(a) floor(a+0.5)
1.166     brouard  1074: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1075: #define mytinydouble 1.0e-16
1.166     brouard  1076: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1077: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1078: /* static double dsqrarg; */
                   1079: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1080: static double sqrarg;
                   1081: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1082: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1083: int agegomp= AGEGOMP;
                   1084: 
                   1085: int imx; 
                   1086: int stepm=1;
                   1087: /* Stepm, step in month: minimum step interpolation*/
                   1088: 
                   1089: int estepm;
                   1090: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1091: 
                   1092: int m,nb;
                   1093: long *num;
1.197     brouard  1094: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1095: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1096:                   covariate for which somebody answered excluding 
                   1097:                   undefined. Usually 2: 0 and 1. */
                   1098: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1099:                             covariate for which somebody answered including 
                   1100:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1101: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1102: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1103: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1104: double *ageexmed,*agecens;
                   1105: double dateintmean=0;
                   1106: 
                   1107: double *weight;
                   1108: int **s; /* Status */
1.141     brouard  1109: double *agedc;
1.145     brouard  1110: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1111:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1112:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1113: double **coqvar; /* Fixed quantitative covariate iqv */
                   1114: double ***cotvar; /* Time varying covariate itv */
                   1115: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1116: double  idx; 
                   1117: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1118: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1119: /*k          1  2   3   4     5    6    7     8    9 */
                   1120: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1121: /* Tndvar[k]    1   2   3               4          5 */
                   1122: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1123: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1124: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1125: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1126: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1127: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1128: /* Tprod[i]=k           4               7            */
                   1129: /* Tage[i]=k                  5               8      */
                   1130: /* */
                   1131: /* Type                    */
                   1132: /* V         1  2  3  4  5 */
                   1133: /*           F  F  V  V  V */
                   1134: /*           D  Q  D  D  Q */
                   1135: /*                         */
                   1136: int *TvarsD;
                   1137: int *TvarsDind;
                   1138: int *TvarsQ;
                   1139: int *TvarsQind;
                   1140: 
1.235     brouard  1141: #define MAXRESULTLINES 10
                   1142: int nresult=0;
                   1143: int TKresult[MAXRESULTLINES];
1.237     brouard  1144: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1145: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1146: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1147: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1148: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1149: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1150: 
1.234     brouard  1151: /* 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  1152: 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 */
                   1153: 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 */
                   1154: 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 */
                   1155: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1156: 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 */
                   1157: 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  1158: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1159: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1160: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1161: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1162: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1163: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1164: 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 */
                   1165: 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 */
                   1166: 
1.230     brouard  1167: int *Tvarsel; /**< Selected covariates for output */
                   1168: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1169: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1170: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1171: 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  1172: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1173: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1174: int *Tage;
1.227     brouard  1175: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1176: 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  1177: 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*/ 
                   1178: 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  1179: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1180: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1181: int **Tvard;
                   1182: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1183: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1184: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1185:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1186:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1187: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1188: double *lsurv, *lpop, *tpop;
                   1189: 
1.231     brouard  1190: #define FD 1; /* Fixed dummy covariate */
                   1191: #define FQ 2; /* Fixed quantitative covariate */
                   1192: #define FP 3; /* Fixed product covariate */
                   1193: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1194: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1195: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1196: #define VD 10; /* Varying dummy covariate */
                   1197: #define VQ 11; /* Varying quantitative covariate */
                   1198: #define VP 12; /* Varying product covariate */
                   1199: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1200: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1201: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1202: #define APFD 16; /* Age product * fixed dummy covariate */
                   1203: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1204: #define APVD 18; /* Age product * varying dummy covariate */
                   1205: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1206: 
                   1207: #define FTYPE 1; /* Fixed covariate */
                   1208: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1209: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1210: 
                   1211: struct kmodel{
                   1212:        int maintype; /* main type */
                   1213:        int subtype; /* subtype */
                   1214: };
                   1215: struct kmodel modell[NCOVMAX];
                   1216: 
1.143     brouard  1217: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1218: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1219: 
                   1220: /**************** split *************************/
                   1221: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1222: {
                   1223:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1224:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1225:   */ 
                   1226:   char *ss;                            /* pointer */
1.186     brouard  1227:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1228: 
                   1229:   l1 = strlen(path );                  /* length of path */
                   1230:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1231:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1232:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1233:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1234:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1235:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1236:     /* get current working directory */
                   1237:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1238: #ifdef WIN32
                   1239:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1240: #else
                   1241:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1242: #endif
1.126     brouard  1243:       return( GLOCK_ERROR_GETCWD );
                   1244:     }
                   1245:     /* got dirc from getcwd*/
                   1246:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1247:   } else {                             /* strip directory from path */
1.126     brouard  1248:     ss++;                              /* after this, the filename */
                   1249:     l2 = strlen( ss );                 /* length of filename */
                   1250:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1251:     strcpy( name, ss );                /* save file name */
                   1252:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1253:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1254:     printf(" DIRC2 = %s \n",dirc);
                   1255:   }
                   1256:   /* We add a separator at the end of dirc if not exists */
                   1257:   l1 = strlen( dirc );                 /* length of directory */
                   1258:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1259:     dirc[l1] =  DIRSEPARATOR;
                   1260:     dirc[l1+1] = 0; 
                   1261:     printf(" DIRC3 = %s \n",dirc);
                   1262:   }
                   1263:   ss = strrchr( name, '.' );           /* find last / */
                   1264:   if (ss >0){
                   1265:     ss++;
                   1266:     strcpy(ext,ss);                    /* save extension */
                   1267:     l1= strlen( name);
                   1268:     l2= strlen(ss)+1;
                   1269:     strncpy( finame, name, l1-l2);
                   1270:     finame[l1-l2]= 0;
                   1271:   }
                   1272: 
                   1273:   return( 0 );                         /* we're done */
                   1274: }
                   1275: 
                   1276: 
                   1277: /******************************************/
                   1278: 
                   1279: void replace_back_to_slash(char *s, char*t)
                   1280: {
                   1281:   int i;
                   1282:   int lg=0;
                   1283:   i=0;
                   1284:   lg=strlen(t);
                   1285:   for(i=0; i<= lg; i++) {
                   1286:     (s[i] = t[i]);
                   1287:     if (t[i]== '\\') s[i]='/';
                   1288:   }
                   1289: }
                   1290: 
1.132     brouard  1291: char *trimbb(char *out, char *in)
1.137     brouard  1292: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1293:   char *s;
                   1294:   s=out;
                   1295:   while (*in != '\0'){
1.137     brouard  1296:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1297:       in++;
                   1298:     }
                   1299:     *out++ = *in++;
                   1300:   }
                   1301:   *out='\0';
                   1302:   return s;
                   1303: }
                   1304: 
1.187     brouard  1305: /* char *substrchaine(char *out, char *in, char *chain) */
                   1306: /* { */
                   1307: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1308: /*   char *s, *t; */
                   1309: /*   t=in;s=out; */
                   1310: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1311: /*     *out++ = *in++; */
                   1312: /*   } */
                   1313: 
                   1314: /*   /\* *in matches *chain *\/ */
                   1315: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1316: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1317: /*   } */
                   1318: /*   in--; chain--; */
                   1319: /*   while ( (*in != '\0')){ */
                   1320: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1321: /*     *out++ = *in++; */
                   1322: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1323: /*   } */
                   1324: /*   *out='\0'; */
                   1325: /*   out=s; */
                   1326: /*   return out; */
                   1327: /* } */
                   1328: char *substrchaine(char *out, char *in, char *chain)
                   1329: {
                   1330:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1331:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1332: 
                   1333:   char *strloc;
                   1334: 
                   1335:   strcpy (out, in); 
                   1336:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1337:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1338:   if(strloc != NULL){ 
                   1339:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1340:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1341:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1342:   }
                   1343:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1344:   return out;
                   1345: }
                   1346: 
                   1347: 
1.145     brouard  1348: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1349: {
1.187     brouard  1350:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1351:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1352:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1353:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1354:   */
1.160     brouard  1355:   char *s, *t;
1.145     brouard  1356:   t=in;s=in;
                   1357:   while ((*in != occ) && (*in != '\0')){
                   1358:     *alocc++ = *in++;
                   1359:   }
                   1360:   if( *in == occ){
                   1361:     *(alocc)='\0';
                   1362:     s=++in;
                   1363:   }
                   1364:  
                   1365:   if (s == t) {/* occ not found */
                   1366:     *(alocc-(in-s))='\0';
                   1367:     in=s;
                   1368:   }
                   1369:   while ( *in != '\0'){
                   1370:     *blocc++ = *in++;
                   1371:   }
                   1372: 
                   1373:   *blocc='\0';
                   1374:   return t;
                   1375: }
1.137     brouard  1376: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1377: {
1.187     brouard  1378:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1379:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1380:      gives blocc="abcdef2ghi" and alocc="j".
                   1381:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1382:   */
                   1383:   char *s, *t;
                   1384:   t=in;s=in;
                   1385:   while (*in != '\0'){
                   1386:     while( *in == occ){
                   1387:       *blocc++ = *in++;
                   1388:       s=in;
                   1389:     }
                   1390:     *blocc++ = *in++;
                   1391:   }
                   1392:   if (s == t) /* occ not found */
                   1393:     *(blocc-(in-s))='\0';
                   1394:   else
                   1395:     *(blocc-(in-s)-1)='\0';
                   1396:   in=s;
                   1397:   while ( *in != '\0'){
                   1398:     *alocc++ = *in++;
                   1399:   }
                   1400: 
                   1401:   *alocc='\0';
                   1402:   return s;
                   1403: }
                   1404: 
1.126     brouard  1405: int nbocc(char *s, char occ)
                   1406: {
                   1407:   int i,j=0;
                   1408:   int lg=20;
                   1409:   i=0;
                   1410:   lg=strlen(s);
                   1411:   for(i=0; i<= lg; i++) {
1.234     brouard  1412:     if  (s[i] == occ ) j++;
1.126     brouard  1413:   }
                   1414:   return j;
                   1415: }
                   1416: 
1.137     brouard  1417: /* void cutv(char *u,char *v, char*t, char occ) */
                   1418: /* { */
                   1419: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1420: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1421: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1422: /*   int i,lg,j,p=0; */
                   1423: /*   i=0; */
                   1424: /*   lg=strlen(t); */
                   1425: /*   for(j=0; j<=lg-1; j++) { */
                   1426: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1427: /*   } */
1.126     brouard  1428: 
1.137     brouard  1429: /*   for(j=0; j<p; j++) { */
                   1430: /*     (u[j] = t[j]); */
                   1431: /*   } */
                   1432: /*      u[p]='\0'; */
1.126     brouard  1433: 
1.137     brouard  1434: /*    for(j=0; j<= lg; j++) { */
                   1435: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1436: /*   } */
                   1437: /* } */
1.126     brouard  1438: 
1.160     brouard  1439: #ifdef _WIN32
                   1440: char * strsep(char **pp, const char *delim)
                   1441: {
                   1442:   char *p, *q;
                   1443:          
                   1444:   if ((p = *pp) == NULL)
                   1445:     return 0;
                   1446:   if ((q = strpbrk (p, delim)) != NULL)
                   1447:   {
                   1448:     *pp = q + 1;
                   1449:     *q = '\0';
                   1450:   }
                   1451:   else
                   1452:     *pp = 0;
                   1453:   return p;
                   1454: }
                   1455: #endif
                   1456: 
1.126     brouard  1457: /********************** nrerror ********************/
                   1458: 
                   1459: void nrerror(char error_text[])
                   1460: {
                   1461:   fprintf(stderr,"ERREUR ...\n");
                   1462:   fprintf(stderr,"%s\n",error_text);
                   1463:   exit(EXIT_FAILURE);
                   1464: }
                   1465: /*********************** vector *******************/
                   1466: double *vector(int nl, int nh)
                   1467: {
                   1468:   double *v;
                   1469:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1470:   if (!v) nrerror("allocation failure in vector");
                   1471:   return v-nl+NR_END;
                   1472: }
                   1473: 
                   1474: /************************ free vector ******************/
                   1475: void free_vector(double*v, int nl, int nh)
                   1476: {
                   1477:   free((FREE_ARG)(v+nl-NR_END));
                   1478: }
                   1479: 
                   1480: /************************ivector *******************************/
                   1481: int *ivector(long nl,long nh)
                   1482: {
                   1483:   int *v;
                   1484:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1485:   if (!v) nrerror("allocation failure in ivector");
                   1486:   return v-nl+NR_END;
                   1487: }
                   1488: 
                   1489: /******************free ivector **************************/
                   1490: void free_ivector(int *v, long nl, long nh)
                   1491: {
                   1492:   free((FREE_ARG)(v+nl-NR_END));
                   1493: }
                   1494: 
                   1495: /************************lvector *******************************/
                   1496: long *lvector(long nl,long nh)
                   1497: {
                   1498:   long *v;
                   1499:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1500:   if (!v) nrerror("allocation failure in ivector");
                   1501:   return v-nl+NR_END;
                   1502: }
                   1503: 
                   1504: /******************free lvector **************************/
                   1505: void free_lvector(long *v, long nl, long nh)
                   1506: {
                   1507:   free((FREE_ARG)(v+nl-NR_END));
                   1508: }
                   1509: 
                   1510: /******************* imatrix *******************************/
                   1511: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1512:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1513: { 
                   1514:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1515:   int **m; 
                   1516:   
                   1517:   /* allocate pointers to rows */ 
                   1518:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1519:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1520:   m += NR_END; 
                   1521:   m -= nrl; 
                   1522:   
                   1523:   
                   1524:   /* allocate rows and set pointers to them */ 
                   1525:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1526:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1527:   m[nrl] += NR_END; 
                   1528:   m[nrl] -= ncl; 
                   1529:   
                   1530:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1531:   
                   1532:   /* return pointer to array of pointers to rows */ 
                   1533:   return m; 
                   1534: } 
                   1535: 
                   1536: /****************** free_imatrix *************************/
                   1537: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1538:       int **m;
                   1539:       long nch,ncl,nrh,nrl; 
                   1540:      /* free an int matrix allocated by imatrix() */ 
                   1541: { 
                   1542:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1543:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1544: } 
                   1545: 
                   1546: /******************* matrix *******************************/
                   1547: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1548: {
                   1549:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1550:   double **m;
                   1551: 
                   1552:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1553:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1554:   m += NR_END;
                   1555:   m -= nrl;
                   1556: 
                   1557:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1558:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1559:   m[nrl] += NR_END;
                   1560:   m[nrl] -= ncl;
                   1561: 
                   1562:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1563:   return m;
1.145     brouard  1564:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1565: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1566: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1567:    */
                   1568: }
                   1569: 
                   1570: /*************************free matrix ************************/
                   1571: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1572: {
                   1573:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1574:   free((FREE_ARG)(m+nrl-NR_END));
                   1575: }
                   1576: 
                   1577: /******************* ma3x *******************************/
                   1578: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1579: {
                   1580:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1581:   double ***m;
                   1582: 
                   1583:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1584:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1585:   m += NR_END;
                   1586:   m -= nrl;
                   1587: 
                   1588:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1589:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1590:   m[nrl] += NR_END;
                   1591:   m[nrl] -= ncl;
                   1592: 
                   1593:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1594: 
                   1595:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1596:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1597:   m[nrl][ncl] += NR_END;
                   1598:   m[nrl][ncl] -= nll;
                   1599:   for (j=ncl+1; j<=nch; j++) 
                   1600:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1601:   
                   1602:   for (i=nrl+1; i<=nrh; i++) {
                   1603:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1604:     for (j=ncl+1; j<=nch; j++) 
                   1605:       m[i][j]=m[i][j-1]+nlay;
                   1606:   }
                   1607:   return m; 
                   1608:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1609:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1610:   */
                   1611: }
                   1612: 
                   1613: /*************************free ma3x ************************/
                   1614: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1615: {
                   1616:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1617:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1618:   free((FREE_ARG)(m+nrl-NR_END));
                   1619: }
                   1620: 
                   1621: /*************** function subdirf ***********/
                   1622: char *subdirf(char fileres[])
                   1623: {
                   1624:   /* Caution optionfilefiname is hidden */
                   1625:   strcpy(tmpout,optionfilefiname);
                   1626:   strcat(tmpout,"/"); /* Add to the right */
                   1627:   strcat(tmpout,fileres);
                   1628:   return tmpout;
                   1629: }
                   1630: 
                   1631: /*************** function subdirf2 ***********/
                   1632: char *subdirf2(char fileres[], char *preop)
                   1633: {
                   1634:   
                   1635:   /* Caution optionfilefiname is hidden */
                   1636:   strcpy(tmpout,optionfilefiname);
                   1637:   strcat(tmpout,"/");
                   1638:   strcat(tmpout,preop);
                   1639:   strcat(tmpout,fileres);
                   1640:   return tmpout;
                   1641: }
                   1642: 
                   1643: /*************** function subdirf3 ***********/
                   1644: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1645: {
                   1646:   
                   1647:   /* Caution optionfilefiname is hidden */
                   1648:   strcpy(tmpout,optionfilefiname);
                   1649:   strcat(tmpout,"/");
                   1650:   strcat(tmpout,preop);
                   1651:   strcat(tmpout,preop2);
                   1652:   strcat(tmpout,fileres);
                   1653:   return tmpout;
                   1654: }
1.213     brouard  1655:  
                   1656: /*************** function subdirfext ***********/
                   1657: char *subdirfext(char fileres[], char *preop, char *postop)
                   1658: {
                   1659:   
                   1660:   strcpy(tmpout,preop);
                   1661:   strcat(tmpout,fileres);
                   1662:   strcat(tmpout,postop);
                   1663:   return tmpout;
                   1664: }
1.126     brouard  1665: 
1.213     brouard  1666: /*************** function subdirfext3 ***********/
                   1667: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1668: {
                   1669:   
                   1670:   /* Caution optionfilefiname is hidden */
                   1671:   strcpy(tmpout,optionfilefiname);
                   1672:   strcat(tmpout,"/");
                   1673:   strcat(tmpout,preop);
                   1674:   strcat(tmpout,fileres);
                   1675:   strcat(tmpout,postop);
                   1676:   return tmpout;
                   1677: }
                   1678:  
1.162     brouard  1679: char *asc_diff_time(long time_sec, char ascdiff[])
                   1680: {
                   1681:   long sec_left, days, hours, minutes;
                   1682:   days = (time_sec) / (60*60*24);
                   1683:   sec_left = (time_sec) % (60*60*24);
                   1684:   hours = (sec_left) / (60*60) ;
                   1685:   sec_left = (sec_left) %(60*60);
                   1686:   minutes = (sec_left) /60;
                   1687:   sec_left = (sec_left) % (60);
                   1688:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1689:   return ascdiff;
                   1690: }
                   1691: 
1.126     brouard  1692: /***************** f1dim *************************/
                   1693: extern int ncom; 
                   1694: extern double *pcom,*xicom;
                   1695: extern double (*nrfunc)(double []); 
                   1696:  
                   1697: double f1dim(double x) 
                   1698: { 
                   1699:   int j; 
                   1700:   double f;
                   1701:   double *xt; 
                   1702:  
                   1703:   xt=vector(1,ncom); 
                   1704:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1705:   f=(*nrfunc)(xt); 
                   1706:   free_vector(xt,1,ncom); 
                   1707:   return f; 
                   1708: } 
                   1709: 
                   1710: /*****************brent *************************/
                   1711: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1712: {
                   1713:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1714:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1715:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1716:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1717:    * returned function value. 
                   1718:   */
1.126     brouard  1719:   int iter; 
                   1720:   double a,b,d,etemp;
1.159     brouard  1721:   double fu=0,fv,fw,fx;
1.164     brouard  1722:   double ftemp=0.;
1.126     brouard  1723:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1724:   double e=0.0; 
                   1725:  
                   1726:   a=(ax < cx ? ax : cx); 
                   1727:   b=(ax > cx ? ax : cx); 
                   1728:   x=w=v=bx; 
                   1729:   fw=fv=fx=(*f)(x); 
                   1730:   for (iter=1;iter<=ITMAX;iter++) { 
                   1731:     xm=0.5*(a+b); 
                   1732:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1733:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1734:     printf(".");fflush(stdout);
                   1735:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1736: #ifdef DEBUGBRENT
1.126     brouard  1737:     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);
                   1738:     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);
                   1739:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1740: #endif
                   1741:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1742:       *xmin=x; 
                   1743:       return fx; 
                   1744:     } 
                   1745:     ftemp=fu;
                   1746:     if (fabs(e) > tol1) { 
                   1747:       r=(x-w)*(fx-fv); 
                   1748:       q=(x-v)*(fx-fw); 
                   1749:       p=(x-v)*q-(x-w)*r; 
                   1750:       q=2.0*(q-r); 
                   1751:       if (q > 0.0) p = -p; 
                   1752:       q=fabs(q); 
                   1753:       etemp=e; 
                   1754:       e=d; 
                   1755:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1756:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1757:       else { 
1.224     brouard  1758:                                d=p/q; 
                   1759:                                u=x+d; 
                   1760:                                if (u-a < tol2 || b-u < tol2) 
                   1761:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1762:       } 
                   1763:     } else { 
                   1764:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1765:     } 
                   1766:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1767:     fu=(*f)(u); 
                   1768:     if (fu <= fx) { 
                   1769:       if (u >= x) a=x; else b=x; 
                   1770:       SHFT(v,w,x,u) 
1.183     brouard  1771:       SHFT(fv,fw,fx,fu) 
                   1772:     } else { 
                   1773:       if (u < x) a=u; else b=u; 
                   1774:       if (fu <= fw || w == x) { 
1.224     brouard  1775:                                v=w; 
                   1776:                                w=u; 
                   1777:                                fv=fw; 
                   1778:                                fw=fu; 
1.183     brouard  1779:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1780:                                v=u; 
                   1781:                                fv=fu; 
1.183     brouard  1782:       } 
                   1783:     } 
1.126     brouard  1784:   } 
                   1785:   nrerror("Too many iterations in brent"); 
                   1786:   *xmin=x; 
                   1787:   return fx; 
                   1788: } 
                   1789: 
                   1790: /****************** mnbrak ***********************/
                   1791: 
                   1792: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1793:            double (*func)(double)) 
1.183     brouard  1794: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1795: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1796: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1797: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1798:    */
1.126     brouard  1799:   double ulim,u,r,q, dum;
                   1800:   double fu; 
1.187     brouard  1801: 
                   1802:   double scale=10.;
                   1803:   int iterscale=0;
                   1804: 
                   1805:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1806:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1807: 
                   1808: 
                   1809:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1810:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1811:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1812:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1813:   /* } */
                   1814: 
1.126     brouard  1815:   if (*fb > *fa) { 
                   1816:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1817:     SHFT(dum,*fb,*fa,dum) 
                   1818:   } 
1.126     brouard  1819:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1820:   *fc=(*func)(*cx); 
1.183     brouard  1821: #ifdef DEBUG
1.224     brouard  1822:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1823:   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  1824: #endif
1.224     brouard  1825:   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  1826:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1827:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1828:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1829:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1830:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1831:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1832:       fu=(*func)(u); 
1.163     brouard  1833: #ifdef DEBUG
                   1834:       /* f(x)=A(x-u)**2+f(u) */
                   1835:       double A, fparabu; 
                   1836:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1837:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1838:       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);
                   1839:       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  1840:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1841:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1842:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1843:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1844: #endif 
1.184     brouard  1845: #ifdef MNBRAKORIGINAL
1.183     brouard  1846: #else
1.191     brouard  1847: /*       if (fu > *fc) { */
                   1848: /* #ifdef DEBUG */
                   1849: /*       printf("mnbrak4  fu > fc \n"); */
                   1850: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1851: /* #endif */
                   1852: /*     /\* 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 *\\/  *\/ */
                   1853: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1854: /*     dum=u; /\* Shifting c and u *\/ */
                   1855: /*     u = *cx; */
                   1856: /*     *cx = dum; */
                   1857: /*     dum = fu; */
                   1858: /*     fu = *fc; */
                   1859: /*     *fc =dum; */
                   1860: /*       } else { /\* end *\/ */
                   1861: /* #ifdef DEBUG */
                   1862: /*       printf("mnbrak3  fu < fc \n"); */
                   1863: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1864: /* #endif */
                   1865: /*     dum=u; /\* Shifting c and u *\/ */
                   1866: /*     u = *cx; */
                   1867: /*     *cx = dum; */
                   1868: /*     dum = fu; */
                   1869: /*     fu = *fc; */
                   1870: /*     *fc =dum; */
                   1871: /*       } */
1.224     brouard  1872: #ifdef DEBUGMNBRAK
                   1873:                 double A, fparabu; 
                   1874:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1875:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1876:      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);
                   1877:      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  1878: #endif
1.191     brouard  1879:       dum=u; /* Shifting c and u */
                   1880:       u = *cx;
                   1881:       *cx = dum;
                   1882:       dum = fu;
                   1883:       fu = *fc;
                   1884:       *fc =dum;
1.183     brouard  1885: #endif
1.162     brouard  1886:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1887: #ifdef DEBUG
1.224     brouard  1888:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1889:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1890: #endif
1.126     brouard  1891:       fu=(*func)(u); 
                   1892:       if (fu < *fc) { 
1.183     brouard  1893: #ifdef DEBUG
1.224     brouard  1894:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1895:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1896: #endif
                   1897:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1898:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1899: #ifdef DEBUG
                   1900:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1901: #endif
                   1902:       } 
1.162     brouard  1903:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1904: #ifdef DEBUG
1.224     brouard  1905:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1906:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1907: #endif
1.126     brouard  1908:       u=ulim; 
                   1909:       fu=(*func)(u); 
1.183     brouard  1910:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1911: #ifdef DEBUG
1.224     brouard  1912:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1913:       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  1914: #endif
1.126     brouard  1915:       u=(*cx)+GOLD*(*cx-*bx); 
                   1916:       fu=(*func)(u); 
1.224     brouard  1917: #ifdef DEBUG
                   1918:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1919:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1920: #endif
1.183     brouard  1921:     } /* end tests */
1.126     brouard  1922:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1923:     SHFT(*fa,*fb,*fc,fu) 
                   1924: #ifdef DEBUG
1.224     brouard  1925:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1926:       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  1927: #endif
                   1928:   } /* 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  1929: } 
                   1930: 
                   1931: /*************** linmin ************************/
1.162     brouard  1932: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1933: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1934: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1935: the value of func at the returned location p . This is actually all accomplished by calling the
                   1936: routines mnbrak and brent .*/
1.126     brouard  1937: int ncom; 
                   1938: double *pcom,*xicom;
                   1939: double (*nrfunc)(double []); 
                   1940:  
1.224     brouard  1941: #ifdef LINMINORIGINAL
1.126     brouard  1942: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1943: #else
                   1944: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1945: #endif
1.126     brouard  1946: { 
                   1947:   double brent(double ax, double bx, double cx, 
                   1948:               double (*f)(double), double tol, double *xmin); 
                   1949:   double f1dim(double x); 
                   1950:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1951:              double *fc, double (*func)(double)); 
                   1952:   int j; 
                   1953:   double xx,xmin,bx,ax; 
                   1954:   double fx,fb,fa;
1.187     brouard  1955: 
1.203     brouard  1956: #ifdef LINMINORIGINAL
                   1957: #else
                   1958:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1959: #endif
                   1960:   
1.126     brouard  1961:   ncom=n; 
                   1962:   pcom=vector(1,n); 
                   1963:   xicom=vector(1,n); 
                   1964:   nrfunc=func; 
                   1965:   for (j=1;j<=n;j++) { 
                   1966:     pcom[j]=p[j]; 
1.202     brouard  1967:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1968:   } 
1.187     brouard  1969: 
1.203     brouard  1970: #ifdef LINMINORIGINAL
                   1971:   xx=1.;
                   1972: #else
                   1973:   axs=0.0;
                   1974:   xxs=1.;
                   1975:   do{
                   1976:     xx= xxs;
                   1977: #endif
1.187     brouard  1978:     ax=0.;
                   1979:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1980:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1981:     /* 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))   */
                   1982:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1983:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1984:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1985:     /* 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  1986: #ifdef LINMINORIGINAL
                   1987: #else
                   1988:     if (fx != fx){
1.224     brouard  1989:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1990:                        printf("|");
                   1991:                        fprintf(ficlog,"|");
1.203     brouard  1992: #ifdef DEBUGLINMIN
1.224     brouard  1993:                        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  1994: #endif
                   1995:     }
1.224     brouard  1996:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1997: #endif
                   1998:   
1.191     brouard  1999: #ifdef DEBUGLINMIN
                   2000:   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  2001:   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  2002: #endif
1.224     brouard  2003: #ifdef LINMINORIGINAL
                   2004: #else
                   2005:        if(fb == fx){ /* Flat function in the direction */
                   2006:                xmin=xx;
                   2007:     *flat=1;
                   2008:        }else{
                   2009:     *flat=0;
                   2010: #endif
                   2011:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2012:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2013:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2014:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2015:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2016:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2017: #ifdef DEBUG
1.224     brouard  2018:   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);
                   2019:   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);
                   2020: #endif
                   2021: #ifdef LINMINORIGINAL
                   2022: #else
                   2023:                        }
1.126     brouard  2024: #endif
1.191     brouard  2025: #ifdef DEBUGLINMIN
                   2026:   printf("linmin end ");
1.202     brouard  2027:   fprintf(ficlog,"linmin end ");
1.191     brouard  2028: #endif
1.126     brouard  2029:   for (j=1;j<=n;j++) { 
1.203     brouard  2030: #ifdef LINMINORIGINAL
                   2031:     xi[j] *= xmin; 
                   2032: #else
                   2033: #ifdef DEBUGLINMIN
                   2034:     if(xxs <1.0)
                   2035:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2036: #endif
                   2037:     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) */
                   2038: #ifdef DEBUGLINMIN
                   2039:     if(xxs <1.0)
                   2040:       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 );
                   2041: #endif
                   2042: #endif
1.187     brouard  2043:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2044:   } 
1.191     brouard  2045: #ifdef DEBUGLINMIN
1.203     brouard  2046:   printf("\n");
1.191     brouard  2047:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2048:   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  2049:   for (j=1;j<=n;j++) { 
1.202     brouard  2050:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2051:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2052:     if(j % ncovmodel == 0){
1.191     brouard  2053:       printf("\n");
1.202     brouard  2054:       fprintf(ficlog,"\n");
                   2055:     }
1.191     brouard  2056:   }
1.203     brouard  2057: #else
1.191     brouard  2058: #endif
1.126     brouard  2059:   free_vector(xicom,1,n); 
                   2060:   free_vector(pcom,1,n); 
                   2061: } 
                   2062: 
                   2063: 
                   2064: /*************** powell ************************/
1.162     brouard  2065: /*
                   2066: Minimization of a function func of n variables. Input consists of an initial starting point
                   2067: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2068: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2069: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2070: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2071: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2072:  */
1.224     brouard  2073: #ifdef LINMINORIGINAL
                   2074: #else
                   2075:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2076:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2077: #endif
1.126     brouard  2078: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2079:            double (*func)(double [])) 
                   2080: { 
1.224     brouard  2081: #ifdef LINMINORIGINAL
                   2082:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2083:              double (*func)(double [])); 
1.224     brouard  2084: #else 
1.241     brouard  2085:  void linmin(double p[], double xi[], int n, double *fret,
                   2086:             double (*func)(double []),int *flat); 
1.224     brouard  2087: #endif
1.239     brouard  2088:  int i,ibig,j,jk,k; 
1.126     brouard  2089:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2090:   double directest;
1.126     brouard  2091:   double fp,fptt;
                   2092:   double *xits;
                   2093:   int niterf, itmp;
1.224     brouard  2094: #ifdef LINMINORIGINAL
                   2095: #else
                   2096: 
                   2097:   flatdir=ivector(1,n); 
                   2098:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2099: #endif
1.126     brouard  2100: 
                   2101:   pt=vector(1,n); 
                   2102:   ptt=vector(1,n); 
                   2103:   xit=vector(1,n); 
                   2104:   xits=vector(1,n); 
                   2105:   *fret=(*func)(p); 
                   2106:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2107:   rcurr_time = time(NULL);  
1.126     brouard  2108:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2109:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2110:     ibig=0; 
                   2111:     del=0.0; 
1.157     brouard  2112:     rlast_time=rcurr_time;
                   2113:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2114:     rcurr_time = time(NULL);  
                   2115:     curr_time = *localtime(&rcurr_time);
                   2116:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2117:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2118: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2119:     for (i=1;i<=n;i++) {
1.126     brouard  2120:       fprintf(ficrespow," %.12lf", p[i]);
                   2121:     }
1.239     brouard  2122:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2123:     printf("\n#model=  1      +     age ");
                   2124:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2125:     if(nagesqr==1){
1.241     brouard  2126:        printf("  + age*age  ");
                   2127:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2128:     }
                   2129:     for(j=1;j <=ncovmodel-2;j++){
                   2130:       if(Typevar[j]==0) {
                   2131:        printf("  +      V%d  ",Tvar[j]);
                   2132:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2133:       }else if(Typevar[j]==1) {
                   2134:        printf("  +    V%d*age ",Tvar[j]);
                   2135:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2136:       }else if(Typevar[j]==2) {
                   2137:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2138:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2139:       }
                   2140:     }
1.126     brouard  2141:     printf("\n");
1.239     brouard  2142: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2143: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2144:     fprintf(ficlog,"\n");
1.239     brouard  2145:     for(i=1,jk=1; i <=nlstate; i++){
                   2146:       for(k=1; k <=(nlstate+ndeath); k++){
                   2147:        if (k != i) {
                   2148:          printf("%d%d ",i,k);
                   2149:          fprintf(ficlog,"%d%d ",i,k);
                   2150:          for(j=1; j <=ncovmodel; j++){
                   2151:            printf("%12.7f ",p[jk]);
                   2152:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2153:            jk++; 
                   2154:          }
                   2155:          printf("\n");
                   2156:          fprintf(ficlog,"\n");
                   2157:        }
                   2158:       }
                   2159:     }
1.241     brouard  2160:     if(*iter <=3 && *iter >1){
1.157     brouard  2161:       tml = *localtime(&rcurr_time);
                   2162:       strcpy(strcurr,asctime(&tml));
                   2163:       rforecast_time=rcurr_time; 
1.126     brouard  2164:       itmp = strlen(strcurr);
                   2165:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2166:        strcurr[itmp-1]='\0';
1.162     brouard  2167:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2168:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2169:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2170:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2171:        forecast_time = *localtime(&rforecast_time);
                   2172:        strcpy(strfor,asctime(&forecast_time));
                   2173:        itmp = strlen(strfor);
                   2174:        if(strfor[itmp-1]=='\n')
                   2175:          strfor[itmp-1]='\0';
                   2176:        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);
                   2177:        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  2178:       }
                   2179:     }
1.187     brouard  2180:     for (i=1;i<=n;i++) { /* For each direction i */
                   2181:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2182:       fptt=(*fret); 
                   2183: #ifdef DEBUG
1.203     brouard  2184:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2185:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2186: #endif
1.203     brouard  2187:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2188:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2189: #ifdef LINMINORIGINAL
1.188     brouard  2190:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2191: #else
                   2192:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2193:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2194: #endif
                   2195:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2196:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2197:                                /* because that direction will be replaced unless the gain del is small */
                   2198:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2199:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2200:                                /* with the new direction. */
                   2201:                                del=fabs(fptt-(*fret)); 
                   2202:                                ibig=i; 
1.126     brouard  2203:       } 
                   2204: #ifdef DEBUG
                   2205:       printf("%d %.12e",i,(*fret));
                   2206:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2207:       for (j=1;j<=n;j++) {
1.224     brouard  2208:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2209:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2210:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2211:       }
                   2212:       for(j=1;j<=n;j++) {
1.225     brouard  2213:                                printf(" p(%d)=%.12e",j,p[j]);
                   2214:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2215:       }
                   2216:       printf("\n");
                   2217:       fprintf(ficlog,"\n");
                   2218: #endif
1.187     brouard  2219:     } /* end loop on each direction i */
                   2220:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2221:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2222:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2223:       for(j=1;j<=n;j++) {
1.225     brouard  2224:                                if(flatdir[j] >0){
                   2225:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2226:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2227:                                }
                   2228:                                /* printf("\n"); */
                   2229:                                /* fprintf(ficlog,"\n"); */
                   2230:                        }
1.243     brouard  2231:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2232:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2233:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2234:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2235:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2236:       /* decreased of more than 3.84  */
                   2237:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2238:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2239:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2240:                        
1.188     brouard  2241:       /* Starting the program with initial values given by a former maximization will simply change */
                   2242:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2243:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2244:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2245: #ifdef DEBUG
                   2246:       int k[2],l;
                   2247:       k[0]=1;
                   2248:       k[1]=-1;
                   2249:       printf("Max: %.12e",(*func)(p));
                   2250:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2251:       for (j=1;j<=n;j++) {
                   2252:        printf(" %.12e",p[j]);
                   2253:        fprintf(ficlog," %.12e",p[j]);
                   2254:       }
                   2255:       printf("\n");
                   2256:       fprintf(ficlog,"\n");
                   2257:       for(l=0;l<=1;l++) {
                   2258:        for (j=1;j<=n;j++) {
                   2259:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2260:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2261:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2262:        }
                   2263:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2264:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2265:       }
                   2266: #endif
                   2267: 
1.224     brouard  2268: #ifdef LINMINORIGINAL
                   2269: #else
                   2270:       free_ivector(flatdir,1,n); 
                   2271: #endif
1.126     brouard  2272:       free_vector(xit,1,n); 
                   2273:       free_vector(xits,1,n); 
                   2274:       free_vector(ptt,1,n); 
                   2275:       free_vector(pt,1,n); 
                   2276:       return; 
1.192     brouard  2277:     } /* enough precision */ 
1.240     brouard  2278:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2279:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2280:       ptt[j]=2.0*p[j]-pt[j]; 
                   2281:       xit[j]=p[j]-pt[j]; 
                   2282:       pt[j]=p[j]; 
                   2283:     } 
1.181     brouard  2284:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2285: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2286:                if (*iter <=4) {
1.225     brouard  2287: #else
                   2288: #endif
1.224     brouard  2289: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2290: #else
1.161     brouard  2291:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2292: #endif
1.162     brouard  2293:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2294:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2295:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2296:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2297:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2298:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2299:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2300:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2301:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2302:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2303:       /* mu² and del² are equal when f3=f1 */
                   2304:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2305:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2306:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2307:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2308: #ifdef NRCORIGINAL
                   2309:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2310: #else
                   2311:       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  2312:       t= t- del*SQR(fp-fptt);
1.183     brouard  2313: #endif
1.202     brouard  2314:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2315: #ifdef DEBUG
1.181     brouard  2316:       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);
                   2317:       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  2318:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2319:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2320:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2321:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2322:       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);
                   2323:       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);
                   2324: #endif
1.183     brouard  2325: #ifdef POWELLORIGINAL
                   2326:       if (t < 0.0) { /* Then we use it for new direction */
                   2327: #else
1.182     brouard  2328:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2329:                                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  2330:         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  2331:         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  2332:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2333:       } 
1.181     brouard  2334:       if (directest < 0.0) { /* Then we use it for new direction */
                   2335: #endif
1.191     brouard  2336: #ifdef DEBUGLINMIN
1.234     brouard  2337:        printf("Before linmin in direction P%d-P0\n",n);
                   2338:        for (j=1;j<=n;j++) {
                   2339:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2340:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2341:          if(j % ncovmodel == 0){
                   2342:            printf("\n");
                   2343:            fprintf(ficlog,"\n");
                   2344:          }
                   2345:        }
1.224     brouard  2346: #endif
                   2347: #ifdef LINMINORIGINAL
1.234     brouard  2348:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2349: #else
1.234     brouard  2350:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2351:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2352: #endif
1.234     brouard  2353:        
1.191     brouard  2354: #ifdef DEBUGLINMIN
1.234     brouard  2355:        for (j=1;j<=n;j++) { 
                   2356:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2357:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2358:          if(j % ncovmodel == 0){
                   2359:            printf("\n");
                   2360:            fprintf(ficlog,"\n");
                   2361:          }
                   2362:        }
1.224     brouard  2363: #endif
1.234     brouard  2364:        for (j=1;j<=n;j++) { 
                   2365:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2366:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2367:        }
1.224     brouard  2368: #ifdef LINMINORIGINAL
                   2369: #else
1.234     brouard  2370:        for (j=1, flatd=0;j<=n;j++) {
                   2371:          if(flatdir[j]>0)
                   2372:            flatd++;
                   2373:        }
                   2374:        if(flatd >0){
                   2375:          printf("%d flat directions\n",flatd);
                   2376:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2377:          for (j=1;j<=n;j++) { 
                   2378:            if(flatdir[j]>0){
                   2379:              printf("%d ",j);
                   2380:              fprintf(ficlog,"%d ",j);
                   2381:            }
                   2382:          }
                   2383:          printf("\n");
                   2384:          fprintf(ficlog,"\n");
                   2385:        }
1.191     brouard  2386: #endif
1.234     brouard  2387:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2388:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2389:        
1.126     brouard  2390: #ifdef DEBUG
1.234     brouard  2391:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2392:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2393:        for(j=1;j<=n;j++){
                   2394:          printf(" %lf",xit[j]);
                   2395:          fprintf(ficlog," %lf",xit[j]);
                   2396:        }
                   2397:        printf("\n");
                   2398:        fprintf(ficlog,"\n");
1.126     brouard  2399: #endif
1.192     brouard  2400:       } /* end of t or directest negative */
1.224     brouard  2401: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2402: #else
1.234     brouard  2403:       } /* end if (fptt < fp)  */
1.192     brouard  2404: #endif
1.225     brouard  2405: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2406:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2407: #else
1.224     brouard  2408: #endif
1.234     brouard  2409:                } /* loop iteration */ 
1.126     brouard  2410: } 
1.234     brouard  2411:   
1.126     brouard  2412: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2413:   
1.235     brouard  2414:   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  2415:   {
1.235     brouard  2416:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2417:        (and selected quantitative values in nres)
                   2418:        by left multiplying the unit
1.234     brouard  2419:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2420:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2421:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2422:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2423:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2424:   /* Initial matrix pimij */
                   2425:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2426:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2427:   /*  0,                   0                  , 1} */
                   2428:   /*
                   2429:    * and after some iteration: */
                   2430:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2431:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2432:   /*  0,                   0                  , 1} */
                   2433:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2434:   /* {0.51571254859325999, 0.4842874514067399, */
                   2435:   /*  0.51326036147820708, 0.48673963852179264} */
                   2436:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2437:     
1.126     brouard  2438:   int i, ii,j,k;
1.209     brouard  2439:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2440:   /* double **matprod2(); */ /* test */
1.218     brouard  2441:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2442:   double **newm;
1.209     brouard  2443:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2444:   int ncvloop=0;
1.169     brouard  2445:   
1.209     brouard  2446:   min=vector(1,nlstate);
                   2447:   max=vector(1,nlstate);
                   2448:   meandiff=vector(1,nlstate);
                   2449: 
1.218     brouard  2450:        /* Starting with matrix unity */
1.126     brouard  2451:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2452:     for (j=1;j<=nlstate+ndeath;j++){
                   2453:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2454:     }
1.169     brouard  2455:   
                   2456:   cov[1]=1.;
                   2457:   
                   2458:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2459:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2460:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2461:     ncvloop++;
1.126     brouard  2462:     newm=savm;
                   2463:     /* Covariates have to be included here again */
1.138     brouard  2464:     cov[2]=agefin;
1.187     brouard  2465:     if(nagesqr==1)
                   2466:       cov[3]= agefin*agefin;;
1.234     brouard  2467:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2468:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2469:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2470:       /* 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  2471:     }
                   2472:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2473:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2474:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2475:       /* 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  2476:     }
1.237     brouard  2477:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2478:       if(Dummy[Tvar[Tage[k]]]){
                   2479:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2480:       } else{
1.235     brouard  2481:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2482:       }
1.235     brouard  2483:       /* 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  2484:     }
1.237     brouard  2485:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2486:       /* 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  2487:       if(Dummy[Tvard[k][1]==0]){
                   2488:        if(Dummy[Tvard[k][2]==0]){
                   2489:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2490:        }else{
                   2491:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2492:        }
                   2493:       }else{
                   2494:        if(Dummy[Tvard[k][2]==0]){
                   2495:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2496:        }else{
                   2497:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2498:        }
                   2499:       }
1.234     brouard  2500:     }
1.138     brouard  2501:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2502:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2503:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2504:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2505:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2506:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2507:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2508:     
1.126     brouard  2509:     savm=oldm;
                   2510:     oldm=newm;
1.209     brouard  2511: 
                   2512:     for(j=1; j<=nlstate; j++){
                   2513:       max[j]=0.;
                   2514:       min[j]=1.;
                   2515:     }
                   2516:     for(i=1;i<=nlstate;i++){
                   2517:       sumnew=0;
                   2518:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2519:       for(j=1; j<=nlstate; j++){ 
                   2520:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2521:        max[j]=FMAX(max[j],prlim[i][j]);
                   2522:        min[j]=FMIN(min[j],prlim[i][j]);
                   2523:       }
                   2524:     }
                   2525: 
1.126     brouard  2526:     maxmax=0.;
1.209     brouard  2527:     for(j=1; j<=nlstate; j++){
                   2528:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2529:       maxmax=FMAX(maxmax,meandiff[j]);
                   2530:       /* 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  2531:     } /* j loop */
1.203     brouard  2532:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2533:     /* 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  2534:     if(maxmax < ftolpl){
1.209     brouard  2535:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2536:       free_vector(min,1,nlstate);
                   2537:       free_vector(max,1,nlstate);
                   2538:       free_vector(meandiff,1,nlstate);
1.126     brouard  2539:       return prlim;
                   2540:     }
1.169     brouard  2541:   } /* age loop */
1.208     brouard  2542:     /* After some age loop it doesn't converge */
1.209     brouard  2543:   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  2544: 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  2545:   /* 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); */
                   2546:   free_vector(min,1,nlstate);
                   2547:   free_vector(max,1,nlstate);
                   2548:   free_vector(meandiff,1,nlstate);
1.208     brouard  2549:   
1.169     brouard  2550:   return prlim; /* should not reach here */
1.126     brouard  2551: }
                   2552: 
1.217     brouard  2553: 
                   2554:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2555: 
1.218     brouard  2556:  /* 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) */
                   2557:  /* 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  2558:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2559: {
1.218     brouard  2560:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2561:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2562:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2563:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2564:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2565:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2566:   /* Initial matrix pimij */
                   2567:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2568:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2569:   /*  0,                   0                  , 1} */
                   2570:   /*
                   2571:    * and after some iteration: */
                   2572:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2573:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2574:   /*  0,                   0                  , 1} */
                   2575:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2576:   /* {0.51571254859325999, 0.4842874514067399, */
                   2577:   /*  0.51326036147820708, 0.48673963852179264} */
                   2578:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2579: 
                   2580:   int i, ii,j,k;
                   2581:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2582:   /* double **matprod2(); */ /* test */
                   2583:   double **out, cov[NCOVMAX+1], **bmij();
                   2584:   double **newm;
1.218     brouard  2585:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2586:   double        **oldm, **savm;  /* for use */
                   2587: 
1.217     brouard  2588:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2589:   int ncvloop=0;
                   2590:   
                   2591:   min=vector(1,nlstate);
                   2592:   max=vector(1,nlstate);
                   2593:   meandiff=vector(1,nlstate);
                   2594: 
1.218     brouard  2595:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2596:        oldm=oldms; savm=savms;
                   2597: 
                   2598:        /* Starting with matrix unity */
                   2599:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2600:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2601:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2602:     }
                   2603:   
                   2604:   cov[1]=1.;
                   2605:   
                   2606:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2607:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2608:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2609:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2610:     ncvloop++;
1.218     brouard  2611:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2612:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2613:     /* Covariates have to be included here again */
                   2614:     cov[2]=agefin;
                   2615:     if(nagesqr==1)
                   2616:       cov[3]= agefin*agefin;;
1.242     brouard  2617:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2618:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2619:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2620:       /* 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)); */
                   2621:     }
                   2622:     /* for (k=1; k<=cptcovn;k++) { */
                   2623:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2624:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2625:     /*   /\* 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])]); *\/ */
                   2626:     /* } */
                   2627:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2628:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2629:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2630:       /* 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]); */
                   2631:     }
                   2632:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2633:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2634:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2635:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2636:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2637:       if(Dummy[Tvar[Tage[k]]]){
                   2638:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2639:       } else{
                   2640:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2641:       }
                   2642:       /* 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]); */
                   2643:     }
                   2644:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2645:       /* 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]); */
                   2646:       if(Dummy[Tvard[k][1]==0]){
                   2647:        if(Dummy[Tvard[k][2]==0]){
                   2648:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2649:        }else{
                   2650:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2651:        }
                   2652:       }else{
                   2653:        if(Dummy[Tvard[k][2]==0]){
                   2654:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2655:        }else{
                   2656:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2657:        }
                   2658:       }
1.217     brouard  2659:     }
                   2660:     
                   2661:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2662:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2663:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2664:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2665:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2666:                /* ij should be linked to the correct index of cov */
                   2667:                /* age and covariate values ij are in 'cov', but we need to pass
                   2668:                 * ij for the observed prevalence at age and status and covariate
                   2669:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2670:                 */
                   2671:     /* 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 *\/ */
                   2672:     /* 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 *\/ */
                   2673:     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  2674:     savm=oldm;
                   2675:     oldm=newm;
                   2676:     for(j=1; j<=nlstate; j++){
                   2677:       max[j]=0.;
                   2678:       min[j]=1.;
                   2679:     }
                   2680:     for(j=1; j<=nlstate; j++){ 
                   2681:       for(i=1;i<=nlstate;i++){
1.234     brouard  2682:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2683:        bprlim[i][j]= newm[i][j];
                   2684:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2685:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2686:       }
                   2687:     }
1.218     brouard  2688:                
1.217     brouard  2689:     maxmax=0.;
                   2690:     for(i=1; i<=nlstate; i++){
                   2691:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2692:       maxmax=FMAX(maxmax,meandiff[i]);
                   2693:       /* 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); */
                   2694:     } /* j loop */
                   2695:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2696:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2697:     if(maxmax < ftolpl){
1.220     brouard  2698:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2699:       free_vector(min,1,nlstate);
                   2700:       free_vector(max,1,nlstate);
                   2701:       free_vector(meandiff,1,nlstate);
                   2702:       return bprlim;
                   2703:     }
                   2704:   } /* age loop */
                   2705:     /* After some age loop it doesn't converge */
                   2706:   printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
                   2707: 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);
                   2708:   /* 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); */
                   2709:   free_vector(min,1,nlstate);
                   2710:   free_vector(max,1,nlstate);
                   2711:   free_vector(meandiff,1,nlstate);
                   2712:   
                   2713:   return bprlim; /* should not reach here */
                   2714: }
                   2715: 
1.126     brouard  2716: /*************** transition probabilities ***************/ 
                   2717: 
                   2718: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2719: {
1.138     brouard  2720:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2721:      computes the probability to be observed in state j being in state i by appying the
                   2722:      model to the ncovmodel covariates (including constant and age).
                   2723:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2724:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2725:      ncth covariate in the global vector x is given by the formula:
                   2726:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2727:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2728:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2729:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2730:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2731:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2732:   */
                   2733:   double s1, lnpijopii;
1.126     brouard  2734:   /*double t34;*/
1.164     brouard  2735:   int i,j, nc, ii, jj;
1.126     brouard  2736: 
1.223     brouard  2737:   for(i=1; i<= nlstate; i++){
                   2738:     for(j=1; j<i;j++){
                   2739:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2740:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2741:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2742:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2743:       }
                   2744:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2745:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2746:     }
                   2747:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2748:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2749:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2750:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2751:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2752:       }
                   2753:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2754:     }
                   2755:   }
1.218     brouard  2756:   
1.223     brouard  2757:   for(i=1; i<= nlstate; i++){
                   2758:     s1=0;
                   2759:     for(j=1; j<i; j++){
                   2760:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2761:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2762:     }
                   2763:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2764:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2765:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2766:     }
                   2767:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2768:     ps[i][i]=1./(s1+1.);
                   2769:     /* Computing other pijs */
                   2770:     for(j=1; j<i; j++)
                   2771:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2772:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2773:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2774:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2775:   } /* end i */
1.218     brouard  2776:   
1.223     brouard  2777:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2778:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2779:       ps[ii][jj]=0;
                   2780:       ps[ii][ii]=1;
                   2781:     }
                   2782:   }
1.218     brouard  2783:   
                   2784:   
1.223     brouard  2785:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2786:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2787:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2788:   /*   } */
                   2789:   /*   printf("\n "); */
                   2790:   /* } */
                   2791:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2792:   /*
                   2793:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2794:                goto end;*/
1.223     brouard  2795:   return ps;
1.126     brouard  2796: }
                   2797: 
1.218     brouard  2798: /*************** backward transition probabilities ***************/ 
                   2799: 
                   2800:  /* 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 ) */
                   2801: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2802:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2803: {
1.222     brouard  2804:   /* Computes the backward probability at age agefin and covariate ij
                   2805:    * and returns in **ps as well as **bmij.
                   2806:    */
1.218     brouard  2807:   int i, ii, j,k;
1.222     brouard  2808:   
                   2809:   double **out, **pmij();
                   2810:   double sumnew=0.;
1.218     brouard  2811:   double agefin;
1.222     brouard  2812:   
                   2813:   double **dnewm, **dsavm, **doldm;
                   2814:   double **bbmij;
                   2815:   
1.218     brouard  2816:   doldm=ddoldms; /* global pointers */
1.222     brouard  2817:   dnewm=ddnewms;
                   2818:   dsavm=ddsavms;
                   2819:   
                   2820:   agefin=cov[2];
                   2821:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2822:      the observed prevalence (with this covariate ij) */
                   2823:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2824:   /* We do have the matrix Px in savm  and we need pij */
                   2825:   for (j=1;j<=nlstate+ndeath;j++){
                   2826:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2827:     for (ii=1;ii<=nlstate;ii++){
                   2828:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2829:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2830:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2831:       if(sumnew >= 1.e-10){
                   2832:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2833:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2834:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2835:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2836:        /* }else */
                   2837:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2838:       }else{
1.242     brouard  2839:        ;
                   2840:        /* 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  2841:       }
                   2842:     } /*End ii */
                   2843:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2844:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2845:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2846:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2847:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2848:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2849:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2850:   for (j=1;j<=nlstate+ndeath;j++){
                   2851:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2852:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2853:     }
                   2854:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2855:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2856:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2857:   /* end bmij */
                   2858:   return ps; 
1.218     brouard  2859: }
1.217     brouard  2860: /*************** transition probabilities ***************/ 
                   2861: 
1.218     brouard  2862: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2863: {
                   2864:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2865:      computes the probability to be observed in state j being in state i by appying the
                   2866:      model to the ncovmodel covariates (including constant and age).
                   2867:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2868:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2869:      ncth covariate in the global vector x is given by the formula:
                   2870:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2871:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2872:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2873:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2874:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2875:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2876:   */
                   2877:   double s1, lnpijopii;
                   2878:   /*double t34;*/
                   2879:   int i,j, nc, ii, jj;
                   2880: 
1.234     brouard  2881:   for(i=1; i<= nlstate; i++){
                   2882:     for(j=1; j<i;j++){
                   2883:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2884:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2885:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2886:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2887:       }
                   2888:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2889:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2890:     }
                   2891:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2892:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2893:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2894:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2895:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2896:       }
                   2897:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2898:     }
                   2899:   }
                   2900:   
                   2901:   for(i=1; i<= nlstate; i++){
                   2902:     s1=0;
                   2903:     for(j=1; j<i; j++){
                   2904:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2905:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2906:     }
                   2907:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2908:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2909:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2910:     }
                   2911:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2912:     ps[i][i]=1./(s1+1.);
                   2913:     /* Computing other pijs */
                   2914:     for(j=1; j<i; j++)
                   2915:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2916:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2917:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2918:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2919:   } /* end i */
                   2920:   
                   2921:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2922:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2923:       ps[ii][jj]=0;
                   2924:       ps[ii][ii]=1;
                   2925:     }
                   2926:   }
                   2927:   /* Added for backcast */ /* Transposed matrix too */
                   2928:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2929:     s1=0.;
                   2930:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2931:       s1+=ps[ii][jj];
                   2932:     }
                   2933:     for(ii=1; ii<= nlstate; ii++){
                   2934:       ps[ii][jj]=ps[ii][jj]/s1;
                   2935:     }
                   2936:   }
                   2937:   /* Transposition */
                   2938:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2939:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2940:       s1=ps[ii][jj];
                   2941:       ps[ii][jj]=ps[jj][ii];
                   2942:       ps[jj][ii]=s1;
                   2943:     }
                   2944:   }
                   2945:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2946:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2947:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2948:   /*   } */
                   2949:   /*   printf("\n "); */
                   2950:   /* } */
                   2951:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2952:   /*
                   2953:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2954:     goto end;*/
                   2955:   return ps;
1.217     brouard  2956: }
                   2957: 
                   2958: 
1.126     brouard  2959: /**************** Product of 2 matrices ******************/
                   2960: 
1.145     brouard  2961: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2962: {
                   2963:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2964:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2965:   /* in, b, out are matrice of pointers which should have been initialized 
                   2966:      before: only the contents of out is modified. The function returns
                   2967:      a pointer to pointers identical to out */
1.145     brouard  2968:   int i, j, k;
1.126     brouard  2969:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2970:     for(k=ncolol; k<=ncoloh; k++){
                   2971:       out[i][k]=0.;
                   2972:       for(j=ncl; j<=nch; j++)
                   2973:        out[i][k] +=in[i][j]*b[j][k];
                   2974:     }
1.126     brouard  2975:   return out;
                   2976: }
                   2977: 
                   2978: 
                   2979: /************* Higher Matrix Product ***************/
                   2980: 
1.235     brouard  2981: 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  2982: {
1.218     brouard  2983:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2984:      'nhstepm*hstepm*stepm' months (i.e. until
                   2985:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2986:      nhstepm*hstepm matrices. 
                   2987:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2988:      (typically every 2 years instead of every month which is too big 
                   2989:      for the memory).
                   2990:      Model is determined by parameters x and covariates have to be 
                   2991:      included manually here. 
                   2992: 
                   2993:      */
                   2994: 
                   2995:   int i, j, d, h, k;
1.131     brouard  2996:   double **out, cov[NCOVMAX+1];
1.126     brouard  2997:   double **newm;
1.187     brouard  2998:   double agexact;
1.214     brouard  2999:   double agebegin, ageend;
1.126     brouard  3000: 
                   3001:   /* Hstepm could be zero and should return the unit matrix */
                   3002:   for (i=1;i<=nlstate+ndeath;i++)
                   3003:     for (j=1;j<=nlstate+ndeath;j++){
                   3004:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3005:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3006:     }
                   3007:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3008:   for(h=1; h <=nhstepm; h++){
                   3009:     for(d=1; d <=hstepm; d++){
                   3010:       newm=savm;
                   3011:       /* Covariates have to be included here again */
                   3012:       cov[1]=1.;
1.214     brouard  3013:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3014:       cov[2]=agexact;
                   3015:       if(nagesqr==1)
1.227     brouard  3016:        cov[3]= agexact*agexact;
1.235     brouard  3017:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3018:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3019:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3020:        /* 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)); */
                   3021:       }
                   3022:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3023:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3024:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3025:        /* 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]); */
                   3026:       }
                   3027:       for (k=1; k<=cptcovage;k++){
                   3028:        if(Dummy[Tvar[Tage[k]]]){
                   3029:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3030:        } else{
                   3031:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3032:        }
                   3033:        /* 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]); */
                   3034:       }
                   3035:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3036:        /* 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]); */
                   3037:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3038:       }
                   3039:       /* for (k=1; k<=cptcovn;k++)  */
                   3040:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3041:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3042:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3043:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3044:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3045:       
                   3046:       
1.126     brouard  3047:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3048:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3049:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3050:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3051:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3052:       /* if((int)age == 70){ */
                   3053:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3054:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3055:       /*         printf("%d pmmij ",i); */
                   3056:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3057:       /*           printf("%f ",pmmij[i][j]); */
                   3058:       /*         } */
                   3059:       /*         printf(" oldm "); */
                   3060:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3061:       /*           printf("%f ",oldm[i][j]); */
                   3062:       /*         } */
                   3063:       /*         printf("\n"); */
                   3064:       /*       } */
                   3065:       /* } */
1.126     brouard  3066:       savm=oldm;
                   3067:       oldm=newm;
                   3068:     }
                   3069:     for(i=1; i<=nlstate+ndeath; i++)
                   3070:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3071:                                po[i][j][h]=newm[i][j];
                   3072:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3073:       }
1.128     brouard  3074:     /*printf("h=%d ",h);*/
1.126     brouard  3075:   } /* end h */
1.218     brouard  3076:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3077:   return po;
                   3078: }
                   3079: 
1.217     brouard  3080: /************* Higher Back Matrix Product ***************/
1.218     brouard  3081: /* 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  3082: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3083: {
1.218     brouard  3084:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3085:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3086:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3087:      nhstepm*hstepm matrices.
                   3088:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3089:      (typically every 2 years instead of every month which is too big
1.217     brouard  3090:      for the memory).
1.218     brouard  3091:      Model is determined by parameters x and covariates have to be
                   3092:      included manually here.
1.217     brouard  3093: 
1.222     brouard  3094:   */
1.217     brouard  3095: 
                   3096:   int i, j, d, h, k;
                   3097:   double **out, cov[NCOVMAX+1];
                   3098:   double **newm;
                   3099:   double agexact;
                   3100:   double agebegin, ageend;
1.222     brouard  3101:   double **oldm, **savm;
1.217     brouard  3102: 
1.222     brouard  3103:   oldm=oldms;savm=savms;
1.217     brouard  3104:   /* Hstepm could be zero and should return the unit matrix */
                   3105:   for (i=1;i<=nlstate+ndeath;i++)
                   3106:     for (j=1;j<=nlstate+ndeath;j++){
                   3107:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3108:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3109:     }
                   3110:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3111:   for(h=1; h <=nhstepm; h++){
                   3112:     for(d=1; d <=hstepm; d++){
                   3113:       newm=savm;
                   3114:       /* Covariates have to be included here again */
                   3115:       cov[1]=1.;
                   3116:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3117:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3118:       cov[2]=agexact;
                   3119:       if(nagesqr==1)
1.222     brouard  3120:        cov[3]= agexact*agexact;
1.218     brouard  3121:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3122:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3123:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3124:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3125:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3126:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3127:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3128:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3129:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3130:       /* 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  3131:                        
                   3132:                        
1.217     brouard  3133:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3134:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3135:       /* Careful transposed matrix */
1.222     brouard  3136:       /* age is in cov[2] */
1.218     brouard  3137:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3138:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3139:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3140:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3141:       /* if((int)age == 70){ */
                   3142:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3143:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3144:       /*         printf("%d pmmij ",i); */
                   3145:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3146:       /*           printf("%f ",pmmij[i][j]); */
                   3147:       /*         } */
                   3148:       /*         printf(" oldm "); */
                   3149:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3150:       /*           printf("%f ",oldm[i][j]); */
                   3151:       /*         } */
                   3152:       /*         printf("\n"); */
                   3153:       /*       } */
                   3154:       /* } */
                   3155:       savm=oldm;
                   3156:       oldm=newm;
                   3157:     }
                   3158:     for(i=1; i<=nlstate+ndeath; i++)
                   3159:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3160:        po[i][j][h]=newm[i][j];
                   3161:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3162:       }
                   3163:     /*printf("h=%d ",h);*/
                   3164:   } /* end h */
1.222     brouard  3165:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3166:   return po;
                   3167: }
                   3168: 
                   3169: 
1.162     brouard  3170: #ifdef NLOPT
                   3171:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3172:   double fret;
                   3173:   double *xt;
                   3174:   int j;
                   3175:   myfunc_data *d2 = (myfunc_data *) pd;
                   3176: /* xt = (p1-1); */
                   3177:   xt=vector(1,n); 
                   3178:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3179: 
                   3180:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3181:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3182:   printf("Function = %.12lf ",fret);
                   3183:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3184:   printf("\n");
                   3185:  free_vector(xt,1,n);
                   3186:   return fret;
                   3187: }
                   3188: #endif
1.126     brouard  3189: 
                   3190: /*************** log-likelihood *************/
                   3191: double func( double *x)
                   3192: {
1.226     brouard  3193:   int i, ii, j, k, mi, d, kk;
                   3194:   int ioffset=0;
                   3195:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3196:   double **out;
                   3197:   double lli; /* Individual log likelihood */
                   3198:   int s1, s2;
1.228     brouard  3199:   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  3200:   double bbh, survp;
                   3201:   long ipmx;
                   3202:   double agexact;
                   3203:   /*extern weight */
                   3204:   /* We are differentiating ll according to initial status */
                   3205:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3206:   /*for(i=1;i<imx;i++) 
                   3207:     printf(" %d\n",s[4][i]);
                   3208:   */
1.162     brouard  3209: 
1.226     brouard  3210:   ++countcallfunc;
1.162     brouard  3211: 
1.226     brouard  3212:   cov[1]=1.;
1.126     brouard  3213: 
1.226     brouard  3214:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3215:   ioffset=0;
1.226     brouard  3216:   if(mle==1){
                   3217:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3218:       /* Computes the values of the ncovmodel covariates of the model
                   3219:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3220:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3221:         to be observed in j being in i according to the model.
                   3222:       */
1.243     brouard  3223:       ioffset=2+nagesqr ;
1.233     brouard  3224:    /* Fixed */
1.234     brouard  3225:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3226:        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)*/
                   3227:       }
1.226     brouard  3228:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3229:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3230:         has been calculated etc */
                   3231:       /* For an individual i, wav[i] gives the number of effective waves */
                   3232:       /* We compute the contribution to Likelihood of each effective transition
                   3233:         mw[mi][i] is real wave of the mi th effectve wave */
                   3234:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3235:         s2=s[mw[mi+1][i]][i];
                   3236:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3237:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3238:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3239:       */
                   3240:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3241:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3242:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3243:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3244:        }
                   3245:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3246:          for (j=1;j<=nlstate+ndeath;j++){
                   3247:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3248:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3249:          }
                   3250:        for(d=0; d<dh[mi][i]; d++){
                   3251:          newm=savm;
                   3252:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3253:          cov[2]=agexact;
                   3254:          if(nagesqr==1)
                   3255:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3256:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3257:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3258:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3259:          else
                   3260:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3261:          }
                   3262:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3263:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3264:          savm=oldm;
                   3265:          oldm=newm;
                   3266:        } /* end mult */
                   3267:        
                   3268:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3269:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3270:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3271:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3272:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3273:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3274:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3275:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3276:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3277:                                 * -stepm/2 to stepm/2 .
                   3278:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3279:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3280:                                 */
1.234     brouard  3281:        s1=s[mw[mi][i]][i];
                   3282:        s2=s[mw[mi+1][i]][i];
                   3283:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3284:        /* bias bh is positive if real duration
                   3285:         * is higher than the multiple of stepm and negative otherwise.
                   3286:         */
                   3287:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3288:        if( s2 > nlstate){ 
                   3289:          /* i.e. if s2 is a death state and if the date of death is known 
                   3290:             then the contribution to the likelihood is the probability to 
                   3291:             die between last step unit time and current  step unit time, 
                   3292:             which is also equal to probability to die before dh 
                   3293:             minus probability to die before dh-stepm . 
                   3294:             In version up to 0.92 likelihood was computed
                   3295:             as if date of death was unknown. Death was treated as any other
                   3296:             health state: the date of the interview describes the actual state
                   3297:             and not the date of a change in health state. The former idea was
                   3298:             to consider that at each interview the state was recorded
                   3299:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3300:             introduced the exact date of death then we should have modified
                   3301:             the contribution of an exact death to the likelihood. This new
                   3302:             contribution is smaller and very dependent of the step unit
                   3303:             stepm. It is no more the probability to die between last interview
                   3304:             and month of death but the probability to survive from last
                   3305:             interview up to one month before death multiplied by the
                   3306:             probability to die within a month. Thanks to Chris
                   3307:             Jackson for correcting this bug.  Former versions increased
                   3308:             mortality artificially. The bad side is that we add another loop
                   3309:             which slows down the processing. The difference can be up to 10%
                   3310:             lower mortality.
                   3311:          */
                   3312:          /* If, at the beginning of the maximization mostly, the
                   3313:             cumulative probability or probability to be dead is
                   3314:             constant (ie = 1) over time d, the difference is equal to
                   3315:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3316:             s1 at precedent wave, to be dead a month before current
                   3317:             wave is equal to probability, being at state s1 at
                   3318:             precedent wave, to be dead at mont of the current
                   3319:             wave. Then the observed probability (that this person died)
                   3320:             is null according to current estimated parameter. In fact,
                   3321:             it should be very low but not zero otherwise the log go to
                   3322:             infinity.
                   3323:          */
1.183     brouard  3324: /* #ifdef INFINITYORIGINAL */
                   3325: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3326: /* #else */
                   3327: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3328: /*         lli=log(mytinydouble); */
                   3329: /*       else */
                   3330: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3331: /* #endif */
1.226     brouard  3332:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3333:          
1.226     brouard  3334:        } else if  ( s2==-1 ) { /* alive */
                   3335:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3336:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3337:          /*survp += out[s1][j]; */
                   3338:          lli= log(survp);
                   3339:        }
                   3340:        else if  (s2==-4) { 
                   3341:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3342:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3343:          lli= log(survp); 
                   3344:        } 
                   3345:        else if  (s2==-5) { 
                   3346:          for (j=1,survp=0. ; j<=2; j++)  
                   3347:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3348:          lli= log(survp); 
                   3349:        } 
                   3350:        else{
                   3351:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3352:          /*  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 */
                   3353:        } 
                   3354:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3355:        /*if(lli ==000.0)*/
                   3356:        /*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); */
                   3357:        ipmx +=1;
                   3358:        sw += weight[i];
                   3359:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3360:        /* if (lli < log(mytinydouble)){ */
                   3361:        /*   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); */
                   3362:        /*   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]); */
                   3363:        /* } */
                   3364:       } /* end of wave */
                   3365:     } /* end of individual */
                   3366:   }  else if(mle==2){
                   3367:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3368:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3369:       for(mi=1; mi<= wav[i]-1; mi++){
                   3370:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3371:          for (j=1;j<=nlstate+ndeath;j++){
                   3372:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3373:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3374:          }
                   3375:        for(d=0; d<=dh[mi][i]; d++){
                   3376:          newm=savm;
                   3377:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3378:          cov[2]=agexact;
                   3379:          if(nagesqr==1)
                   3380:            cov[3]= agexact*agexact;
                   3381:          for (kk=1; kk<=cptcovage;kk++) {
                   3382:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3383:          }
                   3384:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3385:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3386:          savm=oldm;
                   3387:          oldm=newm;
                   3388:        } /* end mult */
                   3389:       
                   3390:        s1=s[mw[mi][i]][i];
                   3391:        s2=s[mw[mi+1][i]][i];
                   3392:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3393:        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 */
                   3394:        ipmx +=1;
                   3395:        sw += weight[i];
                   3396:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3397:       } /* end of wave */
                   3398:     } /* end of individual */
                   3399:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3400:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3401:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3402:       for(mi=1; mi<= wav[i]-1; mi++){
                   3403:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3404:          for (j=1;j<=nlstate+ndeath;j++){
                   3405:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3406:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3407:          }
                   3408:        for(d=0; d<dh[mi][i]; d++){
                   3409:          newm=savm;
                   3410:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3411:          cov[2]=agexact;
                   3412:          if(nagesqr==1)
                   3413:            cov[3]= agexact*agexact;
                   3414:          for (kk=1; kk<=cptcovage;kk++) {
                   3415:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3416:          }
                   3417:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3418:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3419:          savm=oldm;
                   3420:          oldm=newm;
                   3421:        } /* end mult */
                   3422:       
                   3423:        s1=s[mw[mi][i]][i];
                   3424:        s2=s[mw[mi+1][i]][i];
                   3425:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3426:        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 */
                   3427:        ipmx +=1;
                   3428:        sw += weight[i];
                   3429:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3430:       } /* end of wave */
                   3431:     } /* end of individual */
                   3432:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3433:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3434:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3435:       for(mi=1; mi<= wav[i]-1; mi++){
                   3436:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3437:          for (j=1;j<=nlstate+ndeath;j++){
                   3438:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3439:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3440:          }
                   3441:        for(d=0; d<dh[mi][i]; d++){
                   3442:          newm=savm;
                   3443:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3444:          cov[2]=agexact;
                   3445:          if(nagesqr==1)
                   3446:            cov[3]= agexact*agexact;
                   3447:          for (kk=1; kk<=cptcovage;kk++) {
                   3448:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3449:          }
1.126     brouard  3450:        
1.226     brouard  3451:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3452:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3453:          savm=oldm;
                   3454:          oldm=newm;
                   3455:        } /* end mult */
                   3456:       
                   3457:        s1=s[mw[mi][i]][i];
                   3458:        s2=s[mw[mi+1][i]][i];
                   3459:        if( s2 > nlstate){ 
                   3460:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3461:        } else if  ( s2==-1 ) { /* alive */
                   3462:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3463:            survp += out[s1][j];
                   3464:          lli= log(survp);
                   3465:        }else{
                   3466:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3467:        }
                   3468:        ipmx +=1;
                   3469:        sw += weight[i];
                   3470:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3471: /*     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  3472:       } /* end of wave */
                   3473:     } /* end of individual */
                   3474:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3475:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3476:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3477:       for(mi=1; mi<= wav[i]-1; mi++){
                   3478:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3479:          for (j=1;j<=nlstate+ndeath;j++){
                   3480:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3481:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3482:          }
                   3483:        for(d=0; d<dh[mi][i]; d++){
                   3484:          newm=savm;
                   3485:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3486:          cov[2]=agexact;
                   3487:          if(nagesqr==1)
                   3488:            cov[3]= agexact*agexact;
                   3489:          for (kk=1; kk<=cptcovage;kk++) {
                   3490:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3491:          }
1.126     brouard  3492:        
1.226     brouard  3493:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3494:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3495:          savm=oldm;
                   3496:          oldm=newm;
                   3497:        } /* end mult */
                   3498:       
                   3499:        s1=s[mw[mi][i]][i];
                   3500:        s2=s[mw[mi+1][i]][i];
                   3501:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3502:        ipmx +=1;
                   3503:        sw += weight[i];
                   3504:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3505:        /*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]);*/
                   3506:       } /* end of wave */
                   3507:     } /* end of individual */
                   3508:   } /* End of if */
                   3509:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3510:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3511:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3512:   return -l;
1.126     brouard  3513: }
                   3514: 
                   3515: /*************** log-likelihood *************/
                   3516: double funcone( double *x)
                   3517: {
1.228     brouard  3518:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3519:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3520:   int ioffset=0;
1.131     brouard  3521:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3522:   double **out;
                   3523:   double lli; /* Individual log likelihood */
                   3524:   double llt;
                   3525:   int s1, s2;
1.228     brouard  3526:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3527: 
1.126     brouard  3528:   double bbh, survp;
1.187     brouard  3529:   double agexact;
1.214     brouard  3530:   double agebegin, ageend;
1.126     brouard  3531:   /*extern weight */
                   3532:   /* We are differentiating ll according to initial status */
                   3533:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3534:   /*for(i=1;i<imx;i++) 
                   3535:     printf(" %d\n",s[4][i]);
                   3536:   */
                   3537:   cov[1]=1.;
                   3538: 
                   3539:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3540:   ioffset=0;
                   3541:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3542:     /* ioffset=2+nagesqr+cptcovage; */
                   3543:     ioffset=2+nagesqr;
1.232     brouard  3544:     /* Fixed */
1.224     brouard  3545:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3546:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3547:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3548:       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)*/
                   3549: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3550: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3551: /*    cov[2+6]=covar[2][i]; V2  */
                   3552: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3553: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3554: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3555: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3556: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3557: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3558:     }
1.232     brouard  3559:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3560:     /*   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?)*\/ */
                   3561:     /* } */
1.231     brouard  3562:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3563:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3564:     /* } */
1.225     brouard  3565:     
1.233     brouard  3566: 
                   3567:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3568:     /* Wave varying (but not age varying) */
                   3569:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3570:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3571:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3572:       }
1.232     brouard  3573:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3574:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3575:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3576:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3577:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3578:       /* 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  3579:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3580:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3581:       /*       /\* 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]); *\/ */
                   3582:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3583:       /* } */
1.126     brouard  3584:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3585:        for (j=1;j<=nlstate+ndeath;j++){
                   3586:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3587:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3588:        }
1.214     brouard  3589:       
                   3590:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3591:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3592:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.242     brouard  3593:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3594:          and mw[mi+1][i]. dh depends on stepm.*/
                   3595:        newm=savm;
                   3596:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3597:        cov[2]=agexact;
                   3598:        if(nagesqr==1)
                   3599:          cov[3]= agexact*agexact;
                   3600:        for (kk=1; kk<=cptcovage;kk++) {
                   3601:          if(!FixedV[Tvar[Tage[kk]]])
                   3602:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3603:          else
                   3604:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3605:        }
                   3606:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3607:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3608:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3609:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3610:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3611:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3612:        savm=oldm;
                   3613:        oldm=newm;
1.126     brouard  3614:       } /* end mult */
                   3615:       
                   3616:       s1=s[mw[mi][i]][i];
                   3617:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3618:       /* if(s2==-1){ */
                   3619:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3620:       /*       /\* exit(1); *\/ */
                   3621:       /* } */
1.126     brouard  3622:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3623:       /* bias is positive if real duration
                   3624:        * is higher than the multiple of stepm and negative otherwise.
                   3625:        */
                   3626:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3627:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3628:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3629:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3630:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3631:        lli= log(survp);
1.126     brouard  3632:       }else if (mle==1){
1.242     brouard  3633:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3634:       } else if(mle==2){
1.242     brouard  3635:        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  3636:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3637:        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  3638:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3639:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3640:       } else{  /* mle=0 back to 1 */
1.242     brouard  3641:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3642:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3643:       } /* End of if */
                   3644:       ipmx +=1;
                   3645:       sw += weight[i];
                   3646:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3647:       /*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  3648:       if(globpr){
1.242     brouard  3649:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3650:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3651:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3652:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3653:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3654:          llt +=ll[k]*gipmx/gsw;
                   3655:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3656:        }
                   3657:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3658:       }
1.232     brouard  3659:        } /* end of wave */
                   3660: } /* end of individual */
                   3661: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3662: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3663: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3664: if(globpr==0){ /* First time we count the contributions and weights */
                   3665:        gipmx=ipmx;
                   3666:        gsw=sw;
                   3667: }
                   3668: return -l;
1.126     brouard  3669: }
                   3670: 
                   3671: 
                   3672: /*************** function likelione ***********/
                   3673: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3674: {
                   3675:   /* This routine should help understanding what is done with 
                   3676:      the selection of individuals/waves and
                   3677:      to check the exact contribution to the likelihood.
                   3678:      Plotting could be done.
                   3679:    */
                   3680:   int k;
                   3681: 
                   3682:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3683:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3684:     strcat(fileresilk,fileresu);
1.126     brouard  3685:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3686:       printf("Problem with resultfile: %s\n", fileresilk);
                   3687:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3688:     }
1.214     brouard  3689:     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");
                   3690:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3691:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3692:     for(k=1; k<=nlstate; k++) 
                   3693:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3694:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3695:   }
                   3696: 
                   3697:   *fretone=(*funcone)(p);
                   3698:   if(*globpri !=0){
                   3699:     fclose(ficresilk);
1.205     brouard  3700:     if (mle ==0)
                   3701:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3702:     else if(mle >=1)
                   3703:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3704:     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  3705:     
1.208     brouard  3706:       
                   3707:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3708:       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  3709: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3710:     }
1.207     brouard  3711:     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  3712: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3713:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3714: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3715:     fflush(fichtm);
1.205     brouard  3716:   }
1.126     brouard  3717:   return;
                   3718: }
                   3719: 
                   3720: 
                   3721: /*********** Maximum Likelihood Estimation ***************/
                   3722: 
                   3723: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3724: {
1.165     brouard  3725:   int i,j, iter=0;
1.126     brouard  3726:   double **xi;
                   3727:   double fret;
                   3728:   double fretone; /* Only one call to likelihood */
                   3729:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3730: 
                   3731: #ifdef NLOPT
                   3732:   int creturn;
                   3733:   nlopt_opt opt;
                   3734:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3735:   double *lb;
                   3736:   double minf; /* the minimum objective value, upon return */
                   3737:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3738:   myfunc_data dinst, *d = &dinst;
                   3739: #endif
                   3740: 
                   3741: 
1.126     brouard  3742:   xi=matrix(1,npar,1,npar);
                   3743:   for (i=1;i<=npar;i++)
                   3744:     for (j=1;j<=npar;j++)
                   3745:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3746:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3747:   strcpy(filerespow,"POW_"); 
1.126     brouard  3748:   strcat(filerespow,fileres);
                   3749:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3750:     printf("Problem with resultfile: %s\n", filerespow);
                   3751:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3752:   }
                   3753:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3754:   for (i=1;i<=nlstate;i++)
                   3755:     for(j=1;j<=nlstate+ndeath;j++)
                   3756:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3757:   fprintf(ficrespow,"\n");
1.162     brouard  3758: #ifdef POWELL
1.126     brouard  3759:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3760: #endif
1.126     brouard  3761: 
1.162     brouard  3762: #ifdef NLOPT
                   3763: #ifdef NEWUOA
                   3764:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3765: #else
                   3766:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3767: #endif
                   3768:   lb=vector(0,npar-1);
                   3769:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3770:   nlopt_set_lower_bounds(opt, lb);
                   3771:   nlopt_set_initial_step1(opt, 0.1);
                   3772:   
                   3773:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3774:   d->function = func;
                   3775:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3776:   nlopt_set_min_objective(opt, myfunc, d);
                   3777:   nlopt_set_xtol_rel(opt, ftol);
                   3778:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3779:     printf("nlopt failed! %d\n",creturn); 
                   3780:   }
                   3781:   else {
                   3782:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3783:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3784:     iter=1; /* not equal */
                   3785:   }
                   3786:   nlopt_destroy(opt);
                   3787: #endif
1.126     brouard  3788:   free_matrix(xi,1,npar,1,npar);
                   3789:   fclose(ficrespow);
1.203     brouard  3790:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3791:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3792:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3793: 
                   3794: }
                   3795: 
                   3796: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3797: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3798: {
                   3799:   double  **a,**y,*x,pd;
1.203     brouard  3800:   /* double **hess; */
1.164     brouard  3801:   int i, j;
1.126     brouard  3802:   int *indx;
                   3803: 
                   3804:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3805:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3806:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3807:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3808:   double gompertz(double p[]);
1.203     brouard  3809:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3810: 
                   3811:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3812:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3813:   for (i=1;i<=npar;i++){
1.203     brouard  3814:     printf("%d-",i);fflush(stdout);
                   3815:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3816:    
                   3817:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3818:     
                   3819:     /*  printf(" %f ",p[i]);
                   3820:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3821:   }
                   3822:   
                   3823:   for (i=1;i<=npar;i++) {
                   3824:     for (j=1;j<=npar;j++)  {
                   3825:       if (j>i) { 
1.203     brouard  3826:        printf(".%d-%d",i,j);fflush(stdout);
                   3827:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3828:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3829:        
                   3830:        hess[j][i]=hess[i][j];    
                   3831:        /*printf(" %lf ",hess[i][j]);*/
                   3832:       }
                   3833:     }
                   3834:   }
                   3835:   printf("\n");
                   3836:   fprintf(ficlog,"\n");
                   3837: 
                   3838:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3839:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3840:   
                   3841:   a=matrix(1,npar,1,npar);
                   3842:   y=matrix(1,npar,1,npar);
                   3843:   x=vector(1,npar);
                   3844:   indx=ivector(1,npar);
                   3845:   for (i=1;i<=npar;i++)
                   3846:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3847:   ludcmp(a,npar,indx,&pd);
                   3848: 
                   3849:   for (j=1;j<=npar;j++) {
                   3850:     for (i=1;i<=npar;i++) x[i]=0;
                   3851:     x[j]=1;
                   3852:     lubksb(a,npar,indx,x);
                   3853:     for (i=1;i<=npar;i++){ 
                   3854:       matcov[i][j]=x[i];
                   3855:     }
                   3856:   }
                   3857: 
                   3858:   printf("\n#Hessian matrix#\n");
                   3859:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3860:   for (i=1;i<=npar;i++) { 
                   3861:     for (j=1;j<=npar;j++) { 
1.203     brouard  3862:       printf("%.6e ",hess[i][j]);
                   3863:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3864:     }
                   3865:     printf("\n");
                   3866:     fprintf(ficlog,"\n");
                   3867:   }
                   3868: 
1.203     brouard  3869:   /* printf("\n#Covariance matrix#\n"); */
                   3870:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3871:   /* for (i=1;i<=npar;i++) {  */
                   3872:   /*   for (j=1;j<=npar;j++) {  */
                   3873:   /*     printf("%.6e ",matcov[i][j]); */
                   3874:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3875:   /*   } */
                   3876:   /*   printf("\n"); */
                   3877:   /*   fprintf(ficlog,"\n"); */
                   3878:   /* } */
                   3879: 
1.126     brouard  3880:   /* Recompute Inverse */
1.203     brouard  3881:   /* for (i=1;i<=npar;i++) */
                   3882:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3883:   /* ludcmp(a,npar,indx,&pd); */
                   3884: 
                   3885:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3886: 
                   3887:   /* for (j=1;j<=npar;j++) { */
                   3888:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3889:   /*   x[j]=1; */
                   3890:   /*   lubksb(a,npar,indx,x); */
                   3891:   /*   for (i=1;i<=npar;i++){  */
                   3892:   /*     y[i][j]=x[i]; */
                   3893:   /*     printf("%.3e ",y[i][j]); */
                   3894:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3895:   /*   } */
                   3896:   /*   printf("\n"); */
                   3897:   /*   fprintf(ficlog,"\n"); */
                   3898:   /* } */
                   3899: 
                   3900:   /* Verifying the inverse matrix */
                   3901: #ifdef DEBUGHESS
                   3902:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3903: 
1.203     brouard  3904:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3905:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3906: 
                   3907:   for (j=1;j<=npar;j++) {
                   3908:     for (i=1;i<=npar;i++){ 
1.203     brouard  3909:       printf("%.2f ",y[i][j]);
                   3910:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3911:     }
                   3912:     printf("\n");
                   3913:     fprintf(ficlog,"\n");
                   3914:   }
1.203     brouard  3915: #endif
1.126     brouard  3916: 
                   3917:   free_matrix(a,1,npar,1,npar);
                   3918:   free_matrix(y,1,npar,1,npar);
                   3919:   free_vector(x,1,npar);
                   3920:   free_ivector(indx,1,npar);
1.203     brouard  3921:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3922: 
                   3923: 
                   3924: }
                   3925: 
                   3926: /*************** hessian matrix ****************/
                   3927: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3928: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3929:   int i;
                   3930:   int l=1, lmax=20;
1.203     brouard  3931:   double k1,k2, res, fx;
1.132     brouard  3932:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3933:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3934:   int k=0,kmax=10;
                   3935:   double l1;
                   3936: 
                   3937:   fx=func(x);
                   3938:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3939:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3940:     l1=pow(10,l);
                   3941:     delts=delt;
                   3942:     for(k=1 ; k <kmax; k=k+1){
                   3943:       delt = delta*(l1*k);
                   3944:       p2[theta]=x[theta] +delt;
1.145     brouard  3945:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3946:       p2[theta]=x[theta]-delt;
                   3947:       k2=func(p2)-fx;
                   3948:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3949:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3950:       
1.203     brouard  3951: #ifdef DEBUGHESSII
1.126     brouard  3952:       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);
                   3953:       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);
                   3954: #endif
                   3955:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3956:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3957:        k=kmax;
                   3958:       }
                   3959:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3960:        k=kmax; l=lmax*10;
1.126     brouard  3961:       }
                   3962:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3963:        delts=delt;
                   3964:       }
1.203     brouard  3965:     } /* End loop k */
1.126     brouard  3966:   }
                   3967:   delti[theta]=delts;
                   3968:   return res; 
                   3969:   
                   3970: }
                   3971: 
1.203     brouard  3972: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3973: {
                   3974:   int i;
1.164     brouard  3975:   int l=1, lmax=20;
1.126     brouard  3976:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3977:   double p2[MAXPARM+1];
1.203     brouard  3978:   int k, kmax=1;
                   3979:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3980: 
                   3981:   int firstime=0;
1.203     brouard  3982:   
1.126     brouard  3983:   fx=func(x);
1.203     brouard  3984:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3985:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3986:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3987:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3988:     k1=func(p2)-fx;
                   3989:   
1.203     brouard  3990:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3991:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3992:     k2=func(p2)-fx;
                   3993:   
1.203     brouard  3994:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3995:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3996:     k3=func(p2)-fx;
                   3997:   
1.203     brouard  3998:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3999:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4000:     k4=func(p2)-fx;
1.203     brouard  4001:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4002:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4003:       firstime=1;
1.203     brouard  4004:       kmax=kmax+10;
1.208     brouard  4005:     }
                   4006:     if(kmax >=10 || firstime ==1){
1.218     brouard  4007:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   4008:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  4009:       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);
                   4010:       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);
                   4011:     }
                   4012: #ifdef DEBUGHESSIJ
                   4013:     v1=hess[thetai][thetai];
                   4014:     v2=hess[thetaj][thetaj];
                   4015:     cv12=res;
                   4016:     /* Computing eigen value of Hessian matrix */
                   4017:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4018:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4019:     if ((lc2 <0) || (lc1 <0) ){
                   4020:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4021:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   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:     }
1.126     brouard  4025: #endif
                   4026:   }
                   4027:   return res;
                   4028: }
                   4029: 
1.203     brouard  4030:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4031: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4032: /* { */
                   4033: /*   int i; */
                   4034: /*   int l=1, lmax=20; */
                   4035: /*   double k1,k2,k3,k4,res,fx; */
                   4036: /*   double p2[MAXPARM+1]; */
                   4037: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4038: /*   int k=0,kmax=10; */
                   4039: /*   double l1; */
                   4040:   
                   4041: /*   fx=func(x); */
                   4042: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4043: /*     l1=pow(10,l); */
                   4044: /*     delts=delt; */
                   4045: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4046: /*       delt = delti*(l1*k); */
                   4047: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4048: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4049: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4050: /*       k1=func(p2)-fx; */
                   4051:       
                   4052: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4053: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4054: /*       k2=func(p2)-fx; */
                   4055:       
                   4056: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4057: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4058: /*       k3=func(p2)-fx; */
                   4059:       
                   4060: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4061: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4062: /*       k4=func(p2)-fx; */
                   4063: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4064: /* #ifdef DEBUGHESSIJ */
                   4065: /*       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); */
                   4066: /*       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); */
                   4067: /* #endif */
                   4068: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4069: /*     k=kmax; */
                   4070: /*       } */
                   4071: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4072: /*     k=kmax; l=lmax*10; */
                   4073: /*       } */
                   4074: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4075: /*     delts=delt; */
                   4076: /*       } */
                   4077: /*     } /\* End loop k *\/ */
                   4078: /*   } */
                   4079: /*   delti[theta]=delts; */
                   4080: /*   return res;  */
                   4081: /* } */
                   4082: 
                   4083: 
1.126     brouard  4084: /************** Inverse of matrix **************/
                   4085: void ludcmp(double **a, int n, int *indx, double *d) 
                   4086: { 
                   4087:   int i,imax,j,k; 
                   4088:   double big,dum,sum,temp; 
                   4089:   double *vv; 
                   4090:  
                   4091:   vv=vector(1,n); 
                   4092:   *d=1.0; 
                   4093:   for (i=1;i<=n;i++) { 
                   4094:     big=0.0; 
                   4095:     for (j=1;j<=n;j++) 
                   4096:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   4097:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   4098:     vv[i]=1.0/big; 
                   4099:   } 
                   4100:   for (j=1;j<=n;j++) { 
                   4101:     for (i=1;i<j;i++) { 
                   4102:       sum=a[i][j]; 
                   4103:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4104:       a[i][j]=sum; 
                   4105:     } 
                   4106:     big=0.0; 
                   4107:     for (i=j;i<=n;i++) { 
                   4108:       sum=a[i][j]; 
                   4109:       for (k=1;k<j;k++) 
                   4110:        sum -= a[i][k]*a[k][j]; 
                   4111:       a[i][j]=sum; 
                   4112:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4113:        big=dum; 
                   4114:        imax=i; 
                   4115:       } 
                   4116:     } 
                   4117:     if (j != imax) { 
                   4118:       for (k=1;k<=n;k++) { 
                   4119:        dum=a[imax][k]; 
                   4120:        a[imax][k]=a[j][k]; 
                   4121:        a[j][k]=dum; 
                   4122:       } 
                   4123:       *d = -(*d); 
                   4124:       vv[imax]=vv[j]; 
                   4125:     } 
                   4126:     indx[j]=imax; 
                   4127:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4128:     if (j != n) { 
                   4129:       dum=1.0/(a[j][j]); 
                   4130:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4131:     } 
                   4132:   } 
                   4133:   free_vector(vv,1,n);  /* Doesn't work */
                   4134: ;
                   4135: } 
                   4136: 
                   4137: void lubksb(double **a, int n, int *indx, double b[]) 
                   4138: { 
                   4139:   int i,ii=0,ip,j; 
                   4140:   double sum; 
                   4141:  
                   4142:   for (i=1;i<=n;i++) { 
                   4143:     ip=indx[i]; 
                   4144:     sum=b[ip]; 
                   4145:     b[ip]=b[i]; 
                   4146:     if (ii) 
                   4147:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4148:     else if (sum) ii=i; 
                   4149:     b[i]=sum; 
                   4150:   } 
                   4151:   for (i=n;i>=1;i--) { 
                   4152:     sum=b[i]; 
                   4153:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4154:     b[i]=sum/a[i][i]; 
                   4155:   } 
                   4156: } 
                   4157: 
                   4158: void pstamp(FILE *fichier)
                   4159: {
1.196     brouard  4160:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4161: }
                   4162: 
                   4163: /************ Frequencies ********************/
1.226     brouard  4164: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4165:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4166:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4167: {  /* Some frequencies */
                   4168:   
1.227     brouard  4169:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4170:   int iind=0, iage=0;
                   4171:   int mi; /* Effective wave */
                   4172:   int first;
                   4173:   double ***freq; /* Frequencies */
                   4174:   double *meanq;
                   4175:   double **meanqt;
                   4176:   double *pp, **prop, *posprop, *pospropt;
                   4177:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4178:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4179:   double agebegin, ageend;
                   4180:     
                   4181:   pp=vector(1,nlstate);
                   4182:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4183:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4184:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4185:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4186:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4187:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4188:   strcpy(fileresp,"P_");
                   4189:   strcat(fileresp,fileresu);
                   4190:   /*strcat(fileresphtm,fileresu);*/
                   4191:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4192:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4193:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4194:     exit(0);
                   4195:   }
1.240     brouard  4196:   
1.226     brouard  4197:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4198:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4199:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4200:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4201:     fflush(ficlog);
                   4202:     exit(70); 
                   4203:   }
                   4204:   else{
                   4205:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4206: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4207: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4208:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4209:   }
1.237     brouard  4210:   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  4211:   
1.226     brouard  4212:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4213:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4214:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4215:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4216:     fflush(ficlog);
                   4217:     exit(70); 
1.240     brouard  4218:   } else{
1.226     brouard  4219:     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  4220: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4221: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4222:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4223:   }
1.240     brouard  4224:   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);
                   4225:   
1.226     brouard  4226:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4227:   j1=0;
1.126     brouard  4228:   
1.227     brouard  4229:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4230:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4231:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4232:   
1.226     brouard  4233:   first=1;
1.240     brouard  4234:   
1.226     brouard  4235:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4236:      reference=low_education V1=0,V2=0
                   4237:      med_educ                V1=1 V2=0, 
                   4238:      high_educ               V1=0 V2=1
                   4239:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4240:   */
1.240     brouard  4241:   
1.227     brouard  4242:   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  4243:     posproptt=0.;
                   4244:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4245:       scanf("%d", i);*/
                   4246:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4247:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.240     brouard  4248:        for(m=iagemin; m <= iagemax+3; m++)
                   4249:          freq[i][jk][m]=0;
                   4250:     
1.226     brouard  4251:     for (i=1; i<=nlstate; i++)  {
                   4252:       for(m=iagemin; m <= iagemax+3; m++)
1.240     brouard  4253:        prop[i][m]=0;
1.226     brouard  4254:       posprop[i]=0;
                   4255:       pospropt[i]=0;
                   4256:     }
1.227     brouard  4257:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4258:     /*   meanq[z1]+=0.; */
                   4259:     /*   for(m=1;m<=lastpass;m++){ */
                   4260:     /*         meanqt[m][z1]=0.; */
                   4261:     /*   } */
                   4262:     /* } */
1.240     brouard  4263:     
1.226     brouard  4264:     dateintsum=0;
                   4265:     k2cpt=0;
1.227     brouard  4266:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4267:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4268:       bool=1;
1.227     brouard  4269:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4270:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4271:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4272:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4273:          /* } */
1.234     brouard  4274:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4275:            /* if(Tvaraff[z1] ==-20){ */
                   4276:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4277:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4278:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4279:            /* }else  */
                   4280:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4281:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4282:              bool=0;
                   4283:              /* 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", 
                   4284:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4285:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4286:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4287:            } /* Onlyf fixed */
                   4288:          } /* end z1 */
                   4289:        } /* cptcovn > 0 */
1.227     brouard  4290:       } /* end any */
                   4291:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4292:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4293:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4294:          m=mw[mi][iind];
                   4295:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4296:            for (z1=1; z1<=cptcoveff; z1++) {
                   4297:              if( Fixed[Tmodelind[z1]]==1){
                   4298:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4299:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4300:                  bool=0;
                   4301:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4302:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4303:                  bool=0;
                   4304:                }
                   4305:              }
                   4306:            }
                   4307:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4308:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4309:          if(bool==1){
                   4310:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4311:               and mw[mi+1][iind]. dh depends on stepm. */
                   4312:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4313:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4314:            if(m >=firstpass && m <=lastpass){
                   4315:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4316:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4317:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4318:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4319:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4320:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4321:              if (m<lastpass) {
                   4322:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4323:                /*   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]); */
                   4324:                if(s[m][iind]==-1)
                   4325:                  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.));
                   4326:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4327:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4328:                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 */
                   4329:              }
                   4330:            } /* end if between passes */  
                   4331:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4332:              dateintsum=dateintsum+k2;
                   4333:              k2cpt++;
                   4334:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4335:            }
                   4336:          } /* end bool 2 */
                   4337:        } /* end m */
1.226     brouard  4338:       } /* end bool */
                   4339:     } /* end iind = 1 to imx */
                   4340:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4341:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.240     brouard  4342:     
                   4343:     
1.226     brouard  4344:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4345:     pstamp(ficresp);
1.240     brouard  4346:     if  (cptcoveff>0){
1.226     brouard  4347:       fprintf(ficresp, "\n#********** Variable "); 
                   4348:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4349:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.240     brouard  4350:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4351:       for (z1=1; z1<=cptcoveff; z1++){
1.240     brouard  4352:        if(DummyV[z1]){
                   4353:          fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4354:          fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4355:          fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4356:          fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4357:        }else{
                   4358:          fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4359:          fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4360:          fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4361:          fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4362:        }
1.226     brouard  4363:       }
                   4364:       fprintf(ficresp, "**********\n#");
                   4365:       fprintf(ficresphtm, "**********</h3>\n");
                   4366:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4367:       fprintf(ficlog, "**********\n");
                   4368:     }
                   4369:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4370:     for(i=1; i<=nlstate;i++) {
1.240     brouard  4371:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
1.226     brouard  4372:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4373:     }
                   4374:     fprintf(ficresp, "\n");
                   4375:     fprintf(ficresphtm, "\n");
1.240     brouard  4376:     
1.226     brouard  4377:     /* Header of frequency table by age */
                   4378:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4379:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4380:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4381:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4382:        if(jk!=0 && m!=0)
                   4383:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4384:       }
                   4385:     }
                   4386:     fprintf(ficresphtmfr, "\n");
1.240     brouard  4387:     
1.226     brouard  4388:     /* For each age */
                   4389:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4390:       fprintf(ficresphtm,"<tr>");
                   4391:       if(iage==iagemax+1){
1.240     brouard  4392:        fprintf(ficlog,"1");
                   4393:        fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4394:       }else if(iage==iagemax+2){
1.240     brouard  4395:        fprintf(ficlog,"0");
                   4396:        fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4397:       }else if(iage==iagemax+3){
1.240     brouard  4398:        fprintf(ficlog,"Total");
                   4399:        fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4400:       }else{
1.240     brouard  4401:        if(first==1){
                   4402:          first=0;
                   4403:          printf("See log file for details...\n");
                   4404:        }
                   4405:        fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4406:        fprintf(ficlog,"Age %d", iage);
1.226     brouard  4407:       }
                   4408:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4409:        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4410:          pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4411:       }
                   4412:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4413:        for(m=-1, pos=0; m <=0 ; m++)
                   4414:          pos += freq[jk][m][iage];
                   4415:        if(pp[jk]>=1.e-10){
                   4416:          if(first==1){
                   4417:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4418:          }
                   4419:          fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4420:        }else{
                   4421:          if(first==1)
                   4422:            printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4423:          fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4424:        }
1.226     brouard  4425:       }
1.240     brouard  4426:       
1.226     brouard  4427:       for(jk=1; jk <=nlstate ; jk++){ 
1.240     brouard  4428:        /* posprop[jk]=0; */
                   4429:        for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4430:          pp[jk] += freq[jk][m][iage];
1.226     brouard  4431:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.240     brouard  4432:       
1.226     brouard  4433:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.240     brouard  4434:        pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4435:        posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4436:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4437:        pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4438:                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4439:       }
                   4440:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4441:        if(pos>=1.e-5){
                   4442:          if(first==1)
                   4443:            printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4444:          fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4445:        }else{
                   4446:          if(first==1)
                   4447:            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4448:          fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4449:        }
                   4450:        if( iage <= iagemax){
                   4451:          if(pos>=1.e-5){
                   4452:            fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4453:            fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4454:            /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4455:            /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4456:          }
                   4457:          else{
                   4458:            fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4459:            fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4460:          }
                   4461:        }
                   4462:        pospropt[jk] +=posprop[jk];
1.226     brouard  4463:       } /* end loop jk */
                   4464:       /* pospropt=0.; */
                   4465:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.240     brouard  4466:        for(m=-1; m <=nlstate+ndeath; m++){
                   4467:          if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4468:            if(first==1){
                   4469:              printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4470:            }
                   4471:            fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4472:          }
                   4473:          if(jk!=0 && m!=0)
                   4474:            fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4475:        }
1.226     brouard  4476:       } /* end loop jk */
                   4477:       posproptt=0.; 
                   4478:       for(jk=1; jk <=nlstate; jk++){
1.240     brouard  4479:        posproptt += pospropt[jk];
1.226     brouard  4480:       }
                   4481:       fprintf(ficresphtmfr,"</tr>\n ");
                   4482:       if(iage <= iagemax){
1.240     brouard  4483:        fprintf(ficresp,"\n");
                   4484:        fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4485:       }
                   4486:       if(first==1)
1.240     brouard  4487:        printf("Others in log...\n");
1.226     brouard  4488:       fprintf(ficlog,"\n");
                   4489:     } /* end loop age iage */
                   4490:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4491:     for(jk=1; jk <=nlstate ; jk++){
                   4492:       if(posproptt < 1.e-5){
1.240     brouard  4493:        fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4494:       }else{
1.240     brouard  4495:        fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4496:       }
                   4497:     }
                   4498:     fprintf(ficresphtm,"</tr>\n");
                   4499:     fprintf(ficresphtm,"</table>\n");
                   4500:     fprintf(ficresphtmfr,"</table>\n");
                   4501:     if(posproptt < 1.e-5){
                   4502:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4503:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4504:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4505:       invalidvarcomb[j1]=1;
                   4506:     }else{
                   4507:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4508:       invalidvarcomb[j1]=0;
                   4509:     }
                   4510:     fprintf(ficresphtmfr,"</table>\n");
                   4511:   } /* end selected combination of covariate j1 */
                   4512:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4513:   
1.226     brouard  4514:   fclose(ficresp);
                   4515:   fclose(ficresphtm);
                   4516:   fclose(ficresphtmfr);
                   4517:   free_vector(meanq,1,nqfveff);
                   4518:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4519:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4520:   free_vector(pospropt,1,nlstate);
                   4521:   free_vector(posprop,1,nlstate);
                   4522:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4523:   free_vector(pp,1,nlstate);
                   4524:   /* End of freqsummary */
                   4525: }
1.126     brouard  4526: 
                   4527: /************ Prevalence ********************/
1.227     brouard  4528: 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)
                   4529: {  
                   4530:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4531:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4532:      We still use firstpass and lastpass as another selection.
                   4533:   */
1.126     brouard  4534:  
1.227     brouard  4535:   int i, m, jk, j1, bool, z1,j, iv;
                   4536:   int mi; /* Effective wave */
                   4537:   int iage;
                   4538:   double agebegin, ageend;
                   4539: 
                   4540:   double **prop;
                   4541:   double posprop; 
                   4542:   double  y2; /* in fractional years */
                   4543:   int iagemin, iagemax;
                   4544:   int first; /** to stop verbosity which is redirected to log file */
                   4545: 
                   4546:   iagemin= (int) agemin;
                   4547:   iagemax= (int) agemax;
                   4548:   /*pp=vector(1,nlstate);*/
                   4549:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4550:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4551:   j1=0;
1.222     brouard  4552:   
1.227     brouard  4553:   /*j=cptcoveff;*/
                   4554:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4555:   
1.227     brouard  4556:   first=1;
                   4557:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4558:     for (i=1; i<=nlstate; i++)  
                   4559:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4560:        prop[i][iage]=0.0;
                   4561:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4562:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4563:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4564:     
                   4565:     for (i=1; i<=imx; i++) { /* Each individual */
                   4566:       bool=1;
                   4567:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4568:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4569:        m=mw[mi][i];
                   4570:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4571:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4572:        for (z1=1; z1<=cptcoveff; z1++){
                   4573:          if( Fixed[Tmodelind[z1]]==1){
                   4574:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4575:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4576:              bool=0;
                   4577:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4578:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4579:              bool=0;
                   4580:            }
                   4581:        }
                   4582:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4583:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4584:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4585:          if(m >=firstpass && m <=lastpass){
                   4586:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4587:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4588:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4589:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4590:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4591:                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); 
                   4592:                exit(1);
                   4593:              }
                   4594:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4595:                /*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]]);*/
                   4596:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4597:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4598:              } /* end valid statuses */ 
                   4599:            } /* end selection of dates */
                   4600:          } /* end selection of waves */
                   4601:        } /* end bool */
                   4602:       } /* end wave */
                   4603:     } /* end individual */
                   4604:     for(i=iagemin; i <= iagemax+3; i++){  
                   4605:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4606:        posprop += prop[jk][i]; 
                   4607:       } 
                   4608:       
                   4609:       for(jk=1; jk <=nlstate ; jk++){      
                   4610:        if( i <=  iagemax){ 
                   4611:          if(posprop>=1.e-5){ 
                   4612:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4613:          } else{
                   4614:            if(first==1){
                   4615:              first=0;
                   4616:              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]);
                   4617:            }
                   4618:          }
                   4619:        } 
                   4620:       }/* end jk */ 
                   4621:     }/* end i */ 
1.222     brouard  4622:      /*} *//* end i1 */
1.227     brouard  4623:   } /* end j1 */
1.222     brouard  4624:   
1.227     brouard  4625:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4626:   /*free_vector(pp,1,nlstate);*/
                   4627:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4628: }  /* End of prevalence */
1.126     brouard  4629: 
                   4630: /************* Waves Concatenation ***************/
                   4631: 
                   4632: 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)
                   4633: {
                   4634:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4635:      Death is a valid wave (if date is known).
                   4636:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4637:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4638:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4639:   */
1.126     brouard  4640: 
1.224     brouard  4641:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4642:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4643:      double sum=0., jmean=0.;*/
1.224     brouard  4644:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4645:   int j, k=0,jk, ju, jl;
                   4646:   double sum=0.;
                   4647:   first=0;
1.214     brouard  4648:   firstwo=0;
1.217     brouard  4649:   firsthree=0;
1.218     brouard  4650:   firstfour=0;
1.164     brouard  4651:   jmin=100000;
1.126     brouard  4652:   jmax=-1;
                   4653:   jmean=0.;
1.224     brouard  4654: 
                   4655: /* Treating live states */
1.214     brouard  4656:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4657:     mi=0;  /* First valid wave */
1.227     brouard  4658:     mli=0; /* Last valid wave */
1.126     brouard  4659:     m=firstpass;
1.214     brouard  4660:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4661:       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 */
                   4662:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4663:       }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 */
                   4664:        mw[++mi][i]=m;
                   4665:        mli=m;
1.224     brouard  4666:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4667:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4668:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4669:       }
1.227     brouard  4670:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4671: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4672:        break;
1.224     brouard  4673: #else
1.227     brouard  4674:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4675:          if(firsthree == 0){
                   4676:            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);
                   4677:            firsthree=1;
                   4678:          }
                   4679:          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);
                   4680:          mw[++mi][i]=m;
                   4681:          mli=m;
                   4682:        }
                   4683:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4684:          nbwarn++;
                   4685:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4686:            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);
                   4687:            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);
                   4688:          }
                   4689:          break;
                   4690:        }
                   4691:        break;
1.224     brouard  4692: #endif
1.227     brouard  4693:       }/* End m >= lastpass */
1.126     brouard  4694:     }/* end while */
1.224     brouard  4695: 
1.227     brouard  4696:     /* 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  4697:     /* After last pass */
1.224     brouard  4698: /* Treating death states */
1.214     brouard  4699:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4700:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4701:       /* } */
1.126     brouard  4702:       mi++;    /* Death is another wave */
                   4703:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4704:       /* Only death is a correct wave */
1.126     brouard  4705:       mw[mi][i]=m;
1.224     brouard  4706:     }
                   4707: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4708:     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  4709:       /* m++; */
                   4710:       /* mi++; */
                   4711:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4712:       /* mw[mi][i]=m; */
1.218     brouard  4713:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4714:        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 */
                   4715:          nbwarn++;
                   4716:          if(firstfiv==0){
                   4717:            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 );
                   4718:            firstfiv=1;
                   4719:          }else{
                   4720:            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 );
                   4721:          }
                   4722:        }else{ /* Death occured afer last wave potential bias */
                   4723:          nberr++;
                   4724:          if(firstwo==0){
                   4725:            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 );
                   4726:            firstwo=1;
                   4727:          }
                   4728:          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 );
                   4729:        }
1.218     brouard  4730:       }else{ /* end date of interview is known */
1.227     brouard  4731:        /* death is known but not confirmed by death status at any wave */
                   4732:        if(firstfour==0){
                   4733:          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 );
                   4734:          firstfour=1;
                   4735:        }
                   4736:        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  4737:       }
1.224     brouard  4738:     } /* end if date of death is known */
                   4739: #endif
                   4740:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4741:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4742:     if(mi==0){
                   4743:       nbwarn++;
                   4744:       if(first==0){
1.227     brouard  4745:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4746:        first=1;
1.126     brouard  4747:       }
                   4748:       if(first==1){
1.227     brouard  4749:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4750:       }
                   4751:     } /* end mi==0 */
                   4752:   } /* End individuals */
1.214     brouard  4753:   /* wav and mw are no more changed */
1.223     brouard  4754:        
1.214     brouard  4755:   
1.126     brouard  4756:   for(i=1; i<=imx; i++){
                   4757:     for(mi=1; mi<wav[i];mi++){
                   4758:       if (stepm <=0)
1.227     brouard  4759:        dh[mi][i]=1;
1.126     brouard  4760:       else{
1.227     brouard  4761:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4762:          if (agedc[i] < 2*AGESUP) {
                   4763:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4764:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4765:            else if(j<0){
                   4766:              nberr++;
                   4767:              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]);
                   4768:              j=1; /* Temporary Dangerous patch */
                   4769:              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);
                   4770:              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]);
                   4771:              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);
                   4772:            }
                   4773:            k=k+1;
                   4774:            if (j >= jmax){
                   4775:              jmax=j;
                   4776:              ijmax=i;
                   4777:            }
                   4778:            if (j <= jmin){
                   4779:              jmin=j;
                   4780:              ijmin=i;
                   4781:            }
                   4782:            sum=sum+j;
                   4783:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4784:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4785:          }
                   4786:        }
                   4787:        else{
                   4788:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4789: /*       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  4790:                                        
1.227     brouard  4791:          k=k+1;
                   4792:          if (j >= jmax) {
                   4793:            jmax=j;
                   4794:            ijmax=i;
                   4795:          }
                   4796:          else if (j <= jmin){
                   4797:            jmin=j;
                   4798:            ijmin=i;
                   4799:          }
                   4800:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4801:          /*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]);*/
                   4802:          if(j<0){
                   4803:            nberr++;
                   4804:            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]);
                   4805:            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]);
                   4806:          }
                   4807:          sum=sum+j;
                   4808:        }
                   4809:        jk= j/stepm;
                   4810:        jl= j -jk*stepm;
                   4811:        ju= j -(jk+1)*stepm;
                   4812:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4813:          if(jl==0){
                   4814:            dh[mi][i]=jk;
                   4815:            bh[mi][i]=0;
                   4816:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4817:                  * to avoid the price of an extra matrix product in likelihood */
                   4818:            dh[mi][i]=jk+1;
                   4819:            bh[mi][i]=ju;
                   4820:          }
                   4821:        }else{
                   4822:          if(jl <= -ju){
                   4823:            dh[mi][i]=jk;
                   4824:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4825:                                 * is higher than the multiple of stepm and negative otherwise.
                   4826:                                 */
                   4827:          }
                   4828:          else{
                   4829:            dh[mi][i]=jk+1;
                   4830:            bh[mi][i]=ju;
                   4831:          }
                   4832:          if(dh[mi][i]==0){
                   4833:            dh[mi][i]=1; /* At least one step */
                   4834:            bh[mi][i]=ju; /* At least one step */
                   4835:            /*  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);*/
                   4836:          }
                   4837:        } /* end if mle */
1.126     brouard  4838:       }
                   4839:     } /* end wave */
                   4840:   }
                   4841:   jmean=sum/k;
                   4842:   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  4843:   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  4844: }
1.126     brouard  4845: 
                   4846: /*********** Tricode ****************************/
1.220     brouard  4847:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  4848:  {
                   4849:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4850:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   4851:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   4852:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4853:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   4854:     */
1.130     brouard  4855: 
1.242     brouard  4856:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   4857:    int modmaxcovj=0; /* Modality max of covariates j */
                   4858:    int cptcode=0; /* Modality max of covariates j */
                   4859:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  4860: 
                   4861: 
1.242     brouard  4862:    /* cptcoveff=0;  */
                   4863:    /* *cptcov=0; */
1.126     brouard  4864:  
1.242     brouard  4865:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4866: 
1.242     brouard  4867:    /* Loop on covariates without age and products and no quantitative variable */
                   4868:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
                   4869:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4870:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4871:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4872:        switch(Fixed[k]) {
                   4873:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   4874:         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*/
                   4875:           ij=(int)(covar[Tvar[k]][i]);
                   4876:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4877:            * If product of Vn*Vm, still boolean *:
                   4878:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4879:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4880:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4881:              modality of the nth covariate of individual i. */
                   4882:           if (ij > modmaxcovj)
                   4883:             modmaxcovj=ij; 
                   4884:           else if (ij < modmincovj) 
                   4885:             modmincovj=ij; 
                   4886:           if ((ij < -1) && (ij > NCOVMAX)){
                   4887:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4888:             exit(1);
                   4889:           }else
                   4890:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4891:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4892:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4893:           /* getting the maximum value of the modality of the covariate
                   4894:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4895:              female ies 1, then modmaxcovj=1.
                   4896:           */
                   4897:         } /* end for loop on individuals i */
                   4898:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4899:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4900:         cptcode=modmaxcovj;
                   4901:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4902:         /*for (i=0; i<=cptcode; i++) {*/
                   4903:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4904:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4905:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4906:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4907:             if( j != -1){
                   4908:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4909:                                  covariate for which somebody answered excluding 
                   4910:                                  undefined. Usually 2: 0 and 1. */
                   4911:             }
                   4912:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4913:                                     covariate for which somebody answered including 
                   4914:                                     undefined. Usually 3: -1, 0 and 1. */
                   4915:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4916:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4917:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  4918:                        
1.242     brouard  4919:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4920:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4921:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4922:         /* modmincovj=3; modmaxcovj = 7; */
                   4923:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4924:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4925:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   4926:         /* nbcode[Tvar[j]][ij]=k; */
                   4927:         /* nbcode[Tvar[j]][1]=0; */
                   4928:         /* nbcode[Tvar[j]][2]=1; */
                   4929:         /* nbcode[Tvar[j]][3]=2; */
                   4930:         /* To be continued (not working yet). */
                   4931:         ij=0; /* ij is similar to i but can jump over null modalities */
                   4932:         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*/
                   4933:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4934:             break;
                   4935:           }
                   4936:           ij++;
                   4937:           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*/
                   4938:           cptcode = ij; /* New max modality for covar j */
                   4939:         } /* end of loop on modality i=-1 to 1 or more */
                   4940:         break;
                   4941:        case 1: /* Testing on varying covariate, could be simple and
                   4942:                * should look at waves or product of fixed *
                   4943:                * varying. No time to test -1, assuming 0 and 1 only */
                   4944:         ij=0;
                   4945:         for(i=0; i<=1;i++){
                   4946:           nbcode[Tvar[k]][++ij]=i;
                   4947:         }
                   4948:         break;
                   4949:        default:
                   4950:         break;
                   4951:        } /* end switch */
                   4952:      } /* end dummy test */
                   4953:     
                   4954:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4955:      /*        /\*recode from 0 *\/ */
                   4956:      /*                                     k is a modality. If we have model=V1+V1*sex  */
                   4957:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4958:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4959:      /*        } */
                   4960:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4961:      /*        if (ij > ncodemax[j]) { */
                   4962:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4963:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4964:      /*          break; */
                   4965:      /*        } */
                   4966:      /*   }  /\* end of loop on modality k *\/ */
                   4967:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4968:   
                   4969:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   4970:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   4971:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   4972:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4973:      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 */ 
                   4974:      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 */
                   4975:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   4976:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4977:   
                   4978:    ij=0;
                   4979:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4980:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4981:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4982:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4983:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4984:        /* If product not in single variable we don't print results */
                   4985:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4986:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   4987:        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*/
                   4988:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   4989:        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 */
                   4990:        if(Fixed[k]!=0)
                   4991:         anyvaryingduminmodel=1;
                   4992:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   4993:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4994:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   4995:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   4996:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   4997:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4998:      } 
                   4999:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5000:    /* ij--; */
                   5001:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5002:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5003:                * because they can be excluded from the model and real
                   5004:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5005:    for(j=ij+1; j<= cptcovt; j++){
                   5006:      Tvaraff[j]=0;
                   5007:      Tmodelind[j]=0;
                   5008:    }
                   5009:    for(j=ntveff+1; j<= cptcovt; j++){
                   5010:      TmodelInvind[j]=0;
                   5011:    }
                   5012:    /* To be sorted */
                   5013:    ;
                   5014:  }
1.126     brouard  5015: 
1.145     brouard  5016: 
1.126     brouard  5017: /*********** Health Expectancies ****************/
                   5018: 
1.235     brouard  5019:  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  5020: 
                   5021: {
                   5022:   /* Health expectancies, no variances */
1.164     brouard  5023:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5024:   int nhstepma, nstepma; /* Decreasing with age */
                   5025:   double age, agelim, hf;
                   5026:   double ***p3mat;
                   5027:   double eip;
                   5028: 
1.238     brouard  5029:   /* pstamp(ficreseij); */
1.126     brouard  5030:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5031:   fprintf(ficreseij,"# Age");
                   5032:   for(i=1; i<=nlstate;i++){
                   5033:     for(j=1; j<=nlstate;j++){
                   5034:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5035:     }
                   5036:     fprintf(ficreseij," e%1d. ",i);
                   5037:   }
                   5038:   fprintf(ficreseij,"\n");
                   5039: 
                   5040:   
                   5041:   if(estepm < stepm){
                   5042:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5043:   }
                   5044:   else  hstepm=estepm;   
                   5045:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5046:    * This is mainly to measure the difference between two models: for example
                   5047:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5048:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5049:    * progression in between and thus overestimating or underestimating according
                   5050:    * to the curvature of the survival function. If, for the same date, we 
                   5051:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5052:    * to compare the new estimate of Life expectancy with the same linear 
                   5053:    * hypothesis. A more precise result, taking into account a more precise
                   5054:    * curvature will be obtained if estepm is as small as stepm. */
                   5055: 
                   5056:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5057:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5058:      nhstepm is the number of hstepm from age to agelim 
                   5059:      nstepm is the number of stepm from age to agelin. 
                   5060:      Look at hpijx to understand the reason of that which relies in memory size
                   5061:      and note for a fixed period like estepm months */
                   5062:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5063:      survival function given by stepm (the optimization length). Unfortunately it
                   5064:      means that if the survival funtion is printed only each two years of age and if
                   5065:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5066:      results. So we changed our mind and took the option of the best precision.
                   5067:   */
                   5068:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5069: 
                   5070:   agelim=AGESUP;
                   5071:   /* If stepm=6 months */
                   5072:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5073:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5074:     
                   5075: /* nhstepm age range expressed in number of stepm */
                   5076:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5077:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5078:   /* if (stepm >= YEARM) hstepm=1;*/
                   5079:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5080:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5081: 
                   5082:   for (age=bage; age<=fage; age ++){ 
                   5083:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5084:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5085:     /* if (stepm >= YEARM) hstepm=1;*/
                   5086:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5087: 
                   5088:     /* If stepm=6 months */
                   5089:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5090:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5091:     
1.235     brouard  5092:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5093:     
                   5094:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5095:     
                   5096:     printf("%d|",(int)age);fflush(stdout);
                   5097:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5098:     
                   5099:     /* Computing expectancies */
                   5100:     for(i=1; i<=nlstate;i++)
                   5101:       for(j=1; j<=nlstate;j++)
                   5102:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5103:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5104:          
                   5105:          /* 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]);*/
                   5106: 
                   5107:        }
                   5108: 
                   5109:     fprintf(ficreseij,"%3.0f",age );
                   5110:     for(i=1; i<=nlstate;i++){
                   5111:       eip=0;
                   5112:       for(j=1; j<=nlstate;j++){
                   5113:        eip +=eij[i][j][(int)age];
                   5114:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5115:       }
                   5116:       fprintf(ficreseij,"%9.4f", eip );
                   5117:     }
                   5118:     fprintf(ficreseij,"\n");
                   5119:     
                   5120:   }
                   5121:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5122:   printf("\n");
                   5123:   fprintf(ficlog,"\n");
                   5124:   
                   5125: }
                   5126: 
1.235     brouard  5127:  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  5128: 
                   5129: {
                   5130:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5131:      to initial status i, ei. .
1.126     brouard  5132:   */
                   5133:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5134:   int nhstepma, nstepma; /* Decreasing with age */
                   5135:   double age, agelim, hf;
                   5136:   double ***p3matp, ***p3matm, ***varhe;
                   5137:   double **dnewm,**doldm;
                   5138:   double *xp, *xm;
                   5139:   double **gp, **gm;
                   5140:   double ***gradg, ***trgradg;
                   5141:   int theta;
                   5142: 
                   5143:   double eip, vip;
                   5144: 
                   5145:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5146:   xp=vector(1,npar);
                   5147:   xm=vector(1,npar);
                   5148:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5149:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5150:   
                   5151:   pstamp(ficresstdeij);
                   5152:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5153:   fprintf(ficresstdeij,"# Age");
                   5154:   for(i=1; i<=nlstate;i++){
                   5155:     for(j=1; j<=nlstate;j++)
                   5156:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5157:     fprintf(ficresstdeij," e%1d. ",i);
                   5158:   }
                   5159:   fprintf(ficresstdeij,"\n");
                   5160: 
                   5161:   pstamp(ficrescveij);
                   5162:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5163:   fprintf(ficrescveij,"# Age");
                   5164:   for(i=1; i<=nlstate;i++)
                   5165:     for(j=1; j<=nlstate;j++){
                   5166:       cptj= (j-1)*nlstate+i;
                   5167:       for(i2=1; i2<=nlstate;i2++)
                   5168:        for(j2=1; j2<=nlstate;j2++){
                   5169:          cptj2= (j2-1)*nlstate+i2;
                   5170:          if(cptj2 <= cptj)
                   5171:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5172:        }
                   5173:     }
                   5174:   fprintf(ficrescveij,"\n");
                   5175:   
                   5176:   if(estepm < stepm){
                   5177:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5178:   }
                   5179:   else  hstepm=estepm;   
                   5180:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5181:    * This is mainly to measure the difference between two models: for example
                   5182:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5183:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5184:    * progression in between and thus overestimating or underestimating according
                   5185:    * to the curvature of the survival function. If, for the same date, we 
                   5186:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5187:    * to compare the new estimate of Life expectancy with the same linear 
                   5188:    * hypothesis. A more precise result, taking into account a more precise
                   5189:    * curvature will be obtained if estepm is as small as stepm. */
                   5190: 
                   5191:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5192:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5193:      nhstepm is the number of hstepm from age to agelim 
                   5194:      nstepm is the number of stepm from age to agelin. 
                   5195:      Look at hpijx to understand the reason of that which relies in memory size
                   5196:      and note for a fixed period like estepm months */
                   5197:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5198:      survival function given by stepm (the optimization length). Unfortunately it
                   5199:      means that if the survival funtion is printed only each two years of age and if
                   5200:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5201:      results. So we changed our mind and took the option of the best precision.
                   5202:   */
                   5203:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5204: 
                   5205:   /* If stepm=6 months */
                   5206:   /* nhstepm age range expressed in number of stepm */
                   5207:   agelim=AGESUP;
                   5208:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5209:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5210:   /* if (stepm >= YEARM) hstepm=1;*/
                   5211:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5212:   
                   5213:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5214:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5215:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5216:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5217:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5218:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5219: 
                   5220:   for (age=bage; age<=fage; age ++){ 
                   5221:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5222:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5223:     /* if (stepm >= YEARM) hstepm=1;*/
                   5224:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5225:                
1.126     brouard  5226:     /* If stepm=6 months */
                   5227:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5228:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5229:     
                   5230:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5231:                
1.126     brouard  5232:     /* Computing  Variances of health expectancies */
                   5233:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5234:        decrease memory allocation */
                   5235:     for(theta=1; theta <=npar; theta++){
                   5236:       for(i=1; i<=npar; i++){ 
1.222     brouard  5237:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5238:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5239:       }
1.235     brouard  5240:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5241:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5242:                        
1.126     brouard  5243:       for(j=1; j<= nlstate; j++){
1.222     brouard  5244:        for(i=1; i<=nlstate; i++){
                   5245:          for(h=0; h<=nhstepm-1; h++){
                   5246:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5247:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5248:          }
                   5249:        }
1.126     brouard  5250:       }
1.218     brouard  5251:                        
1.126     brouard  5252:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5253:        for(h=0; h<=nhstepm-1; h++){
                   5254:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5255:        }
1.126     brouard  5256:     }/* End theta */
                   5257:     
                   5258:     
                   5259:     for(h=0; h<=nhstepm-1; h++)
                   5260:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5261:        for(theta=1; theta <=npar; theta++)
                   5262:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5263:     
1.218     brouard  5264:                
1.222     brouard  5265:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5266:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5267:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5268:                
1.222     brouard  5269:     printf("%d|",(int)age);fflush(stdout);
                   5270:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5271:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5272:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5273:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5274:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5275:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5276:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5277:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5278:       }
                   5279:     }
1.218     brouard  5280:                
1.126     brouard  5281:     /* Computing expectancies */
1.235     brouard  5282:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5283:     for(i=1; i<=nlstate;i++)
                   5284:       for(j=1; j<=nlstate;j++)
1.222     brouard  5285:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5286:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5287:                                        
1.222     brouard  5288:          /* 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  5289:                                        
1.222     brouard  5290:        }
1.218     brouard  5291:                
1.126     brouard  5292:     fprintf(ficresstdeij,"%3.0f",age );
                   5293:     for(i=1; i<=nlstate;i++){
                   5294:       eip=0.;
                   5295:       vip=0.;
                   5296:       for(j=1; j<=nlstate;j++){
1.222     brouard  5297:        eip += eij[i][j][(int)age];
                   5298:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5299:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5300:        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  5301:       }
                   5302:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5303:     }
                   5304:     fprintf(ficresstdeij,"\n");
1.218     brouard  5305:                
1.126     brouard  5306:     fprintf(ficrescveij,"%3.0f",age );
                   5307:     for(i=1; i<=nlstate;i++)
                   5308:       for(j=1; j<=nlstate;j++){
1.222     brouard  5309:        cptj= (j-1)*nlstate+i;
                   5310:        for(i2=1; i2<=nlstate;i2++)
                   5311:          for(j2=1; j2<=nlstate;j2++){
                   5312:            cptj2= (j2-1)*nlstate+i2;
                   5313:            if(cptj2 <= cptj)
                   5314:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5315:          }
1.126     brouard  5316:       }
                   5317:     fprintf(ficrescveij,"\n");
1.218     brouard  5318:                
1.126     brouard  5319:   }
                   5320:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5321:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5322:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5323:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5324:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5325:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5326:   printf("\n");
                   5327:   fprintf(ficlog,"\n");
1.218     brouard  5328:        
1.126     brouard  5329:   free_vector(xm,1,npar);
                   5330:   free_vector(xp,1,npar);
                   5331:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5332:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5333:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5334: }
1.218     brouard  5335:  
1.126     brouard  5336: /************ Variance ******************/
1.235     brouard  5337:  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  5338:  {
                   5339:    /* Variance of health expectancies */
                   5340:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5341:    /* double **newm;*/
                   5342:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5343:   
                   5344:    /* int movingaverage(); */
                   5345:    double **dnewm,**doldm;
                   5346:    double **dnewmp,**doldmp;
                   5347:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5348:    int k;
                   5349:    double *xp;
                   5350:    double **gp, **gm;  /* for var eij */
                   5351:    double ***gradg, ***trgradg; /*for var eij */
                   5352:    double **gradgp, **trgradgp; /* for var p point j */
                   5353:    double *gpp, *gmp; /* for var p point j */
                   5354:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5355:    double ***p3mat;
                   5356:    double age,agelim, hf;
                   5357:    /* double ***mobaverage; */
                   5358:    int theta;
                   5359:    char digit[4];
                   5360:    char digitp[25];
                   5361: 
                   5362:    char fileresprobmorprev[FILENAMELENGTH];
                   5363: 
                   5364:    if(popbased==1){
                   5365:      if(mobilav!=0)
                   5366:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5367:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5368:    }
                   5369:    else 
                   5370:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5371: 
1.218     brouard  5372:    /* if (mobilav!=0) { */
                   5373:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5374:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5375:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5376:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5377:    /*   } */
                   5378:    /* } */
                   5379: 
                   5380:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5381:    sprintf(digit,"%-d",ij);
                   5382:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5383:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5384:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5385:    strcat(fileresprobmorprev,fileresu);
                   5386:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5387:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5388:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5389:    }
                   5390:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5391:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5392:    pstamp(ficresprobmorprev);
                   5393:    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  5394:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5395:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5396:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5397:    }
                   5398:    for(j=1;j<=cptcoveff;j++) 
                   5399:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5400:    fprintf(ficresprobmorprev,"\n");
                   5401: 
1.218     brouard  5402:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5403:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5404:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5405:      for(i=1; i<=nlstate;i++)
                   5406:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5407:    }  
                   5408:    fprintf(ficresprobmorprev,"\n");
                   5409:   
                   5410:    fprintf(ficgp,"\n# Routine varevsij");
                   5411:    fprintf(ficgp,"\nunset title \n");
                   5412:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5413:    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");
                   5414:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5415:    /*   } */
                   5416:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5417:    pstamp(ficresvij);
                   5418:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5419:    if(popbased==1)
                   5420:      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);
                   5421:    else
                   5422:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5423:    fprintf(ficresvij,"# Age");
                   5424:    for(i=1; i<=nlstate;i++)
                   5425:      for(j=1; j<=nlstate;j++)
                   5426:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5427:    fprintf(ficresvij,"\n");
                   5428: 
                   5429:    xp=vector(1,npar);
                   5430:    dnewm=matrix(1,nlstate,1,npar);
                   5431:    doldm=matrix(1,nlstate,1,nlstate);
                   5432:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5433:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5434: 
                   5435:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5436:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5437:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5438:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5439:   
1.218     brouard  5440:    if(estepm < stepm){
                   5441:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5442:    }
                   5443:    else  hstepm=estepm;   
                   5444:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5445:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5446:       nhstepm is the number of hstepm from age to agelim 
                   5447:       nstepm is the number of stepm from age to agelim. 
                   5448:       Look at function hpijx to understand why because of memory size limitations, 
                   5449:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5450:       survival function given by stepm (the optimization length). Unfortunately it
                   5451:       means that if the survival funtion is printed every two years of age and if
                   5452:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5453:       results. So we changed our mind and took the option of the best precision.
                   5454:    */
                   5455:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5456:    agelim = AGESUP;
                   5457:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5458:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5459:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5460:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5461:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5462:      gp=matrix(0,nhstepm,1,nlstate);
                   5463:      gm=matrix(0,nhstepm,1,nlstate);
                   5464:                
                   5465:                
                   5466:      for(theta=1; theta <=npar; theta++){
                   5467:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5468:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5469:        }
                   5470:                        
1.242     brouard  5471:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5472:                        
                   5473:        if (popbased==1) {
                   5474:         if(mobilav ==0){
                   5475:           for(i=1; i<=nlstate;i++)
                   5476:             prlim[i][i]=probs[(int)age][i][ij];
                   5477:         }else{ /* mobilav */ 
                   5478:           for(i=1; i<=nlstate;i++)
                   5479:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5480:         }
                   5481:        }
                   5482:                        
1.235     brouard  5483:        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  5484:        for(j=1; j<= nlstate; j++){
                   5485:         for(h=0; h<=nhstepm; h++){
                   5486:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5487:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5488:         }
                   5489:        }
                   5490:        /* Next for computing probability of death (h=1 means
                   5491:          computed over hstepm matrices product = hstepm*stepm months) 
                   5492:          as a weighted average of prlim.
                   5493:        */
                   5494:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5495:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5496:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5497:        }    
                   5498:        /* end probability of death */
                   5499:                        
                   5500:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5501:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5502:                        
1.242     brouard  5503:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5504:                        
                   5505:        if (popbased==1) {
                   5506:         if(mobilav ==0){
                   5507:           for(i=1; i<=nlstate;i++)
                   5508:             prlim[i][i]=probs[(int)age][i][ij];
                   5509:         }else{ /* mobilav */ 
                   5510:           for(i=1; i<=nlstate;i++)
                   5511:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5512:         }
                   5513:        }
                   5514:                        
1.235     brouard  5515:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5516:                        
                   5517:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5518:         for(h=0; h<=nhstepm; h++){
                   5519:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5520:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5521:         }
                   5522:        }
                   5523:        /* This for computing probability of death (h=1 means
                   5524:          computed over hstepm matrices product = hstepm*stepm months) 
                   5525:          as a weighted average of prlim.
                   5526:        */
                   5527:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5528:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5529:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5530:        }    
                   5531:        /* end probability of death */
                   5532:                        
                   5533:        for(j=1; j<= nlstate; j++) /* vareij */
                   5534:         for(h=0; h<=nhstepm; h++){
                   5535:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5536:         }
                   5537:                        
                   5538:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5539:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5540:        }
                   5541:                        
                   5542:      } /* End theta */
                   5543:                
                   5544:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5545:                
                   5546:      for(h=0; h<=nhstepm; h++) /* veij */
                   5547:        for(j=1; j<=nlstate;j++)
                   5548:         for(theta=1; theta <=npar; theta++)
                   5549:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5550:                
                   5551:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5552:        for(theta=1; theta <=npar; theta++)
                   5553:         trgradgp[j][theta]=gradgp[theta][j];
                   5554:                
                   5555:                
                   5556:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5557:      for(i=1;i<=nlstate;i++)
                   5558:        for(j=1;j<=nlstate;j++)
                   5559:         vareij[i][j][(int)age] =0.;
                   5560:                
                   5561:      for(h=0;h<=nhstepm;h++){
                   5562:        for(k=0;k<=nhstepm;k++){
                   5563:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5564:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5565:         for(i=1;i<=nlstate;i++)
                   5566:           for(j=1;j<=nlstate;j++)
                   5567:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5568:        }
                   5569:      }
                   5570:                
                   5571:      /* pptj */
                   5572:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5573:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5574:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5575:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5576:         varppt[j][i]=doldmp[j][i];
                   5577:      /* end ppptj */
                   5578:      /*  x centered again */
                   5579:                
1.242     brouard  5580:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5581:                
                   5582:      if (popbased==1) {
                   5583:        if(mobilav ==0){
                   5584:         for(i=1; i<=nlstate;i++)
                   5585:           prlim[i][i]=probs[(int)age][i][ij];
                   5586:        }else{ /* mobilav */ 
                   5587:         for(i=1; i<=nlstate;i++)
                   5588:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5589:        }
                   5590:      }
                   5591:                
                   5592:      /* This for computing probability of death (h=1 means
                   5593:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5594:        as a weighted average of prlim.
                   5595:      */
1.235     brouard  5596:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5597:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5598:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5599:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5600:      }    
                   5601:      /* end probability of death */
                   5602:                
                   5603:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5604:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5605:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5606:        for(i=1; i<=nlstate;i++){
                   5607:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5608:        }
                   5609:      } 
                   5610:      fprintf(ficresprobmorprev,"\n");
                   5611:                
                   5612:      fprintf(ficresvij,"%.0f ",age );
                   5613:      for(i=1; i<=nlstate;i++)
                   5614:        for(j=1; j<=nlstate;j++){
                   5615:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5616:        }
                   5617:      fprintf(ficresvij,"\n");
                   5618:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5619:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5620:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5621:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5622:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5623:    } /* End age */
                   5624:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5625:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5626:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5627:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5628:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5629:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5630:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5631:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5632:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5633:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5634:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5635:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5636:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5637:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5638:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5639:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5640:    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);
                   5641:    /*  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  5642:     */
1.218     brouard  5643:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5644:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5645: 
1.218     brouard  5646:    free_vector(xp,1,npar);
                   5647:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5648:    free_matrix(dnewm,1,nlstate,1,npar);
                   5649:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5650:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5651:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5652:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5653:    fclose(ficresprobmorprev);
                   5654:    fflush(ficgp);
                   5655:    fflush(fichtm); 
                   5656:  }  /* end varevsij */
1.126     brouard  5657: 
                   5658: /************ Variance of prevlim ******************/
1.235     brouard  5659:  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  5660: {
1.205     brouard  5661:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5662:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5663: 
1.126     brouard  5664:   double **dnewm,**doldm;
                   5665:   int i, j, nhstepm, hstepm;
                   5666:   double *xp;
                   5667:   double *gp, *gm;
                   5668:   double **gradg, **trgradg;
1.208     brouard  5669:   double **mgm, **mgp;
1.126     brouard  5670:   double age,agelim;
                   5671:   int theta;
                   5672:   
                   5673:   pstamp(ficresvpl);
                   5674:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5675:   fprintf(ficresvpl,"# Age ");
                   5676:   if(nresult >=1)
                   5677:     fprintf(ficresvpl," Result# ");
1.126     brouard  5678:   for(i=1; i<=nlstate;i++)
                   5679:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5680:   fprintf(ficresvpl,"\n");
                   5681: 
                   5682:   xp=vector(1,npar);
                   5683:   dnewm=matrix(1,nlstate,1,npar);
                   5684:   doldm=matrix(1,nlstate,1,nlstate);
                   5685:   
                   5686:   hstepm=1*YEARM; /* Every year of age */
                   5687:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5688:   agelim = AGESUP;
                   5689:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5690:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5691:     if (stepm >= YEARM) hstepm=1;
                   5692:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5693:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5694:     mgp=matrix(1,npar,1,nlstate);
                   5695:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5696:     gp=vector(1,nlstate);
                   5697:     gm=vector(1,nlstate);
                   5698: 
                   5699:     for(theta=1; theta <=npar; theta++){
                   5700:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5701:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5702:       }
1.209     brouard  5703:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5704:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5705:       else
1.235     brouard  5706:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5707:       for(i=1;i<=nlstate;i++){
1.126     brouard  5708:        gp[i] = prlim[i][i];
1.208     brouard  5709:        mgp[theta][i] = prlim[i][i];
                   5710:       }
1.126     brouard  5711:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5712:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5713:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5714:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5715:       else
1.235     brouard  5716:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5717:       for(i=1;i<=nlstate;i++){
1.126     brouard  5718:        gm[i] = prlim[i][i];
1.208     brouard  5719:        mgm[theta][i] = prlim[i][i];
                   5720:       }
1.126     brouard  5721:       for(i=1;i<=nlstate;i++)
                   5722:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5723:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5724:     } /* End theta */
                   5725: 
                   5726:     trgradg =matrix(1,nlstate,1,npar);
                   5727: 
                   5728:     for(j=1; j<=nlstate;j++)
                   5729:       for(theta=1; theta <=npar; theta++)
                   5730:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5731:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5732:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5733:     /*   for(j=1; j<=nlstate;j++){ */
                   5734:     /*         printf(" %d ",j); */
                   5735:     /*         for(theta=1; theta <=npar; theta++) */
                   5736:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5737:     /*         printf("\n "); */
                   5738:     /*   } */
                   5739:     /* } */
                   5740:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5741:     /*   printf("\n gradg %d ",(int)age); */
                   5742:     /*   for(j=1; j<=nlstate;j++){ */
                   5743:     /*         printf("%d ",j); */
                   5744:     /*         for(theta=1; theta <=npar; theta++) */
                   5745:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5746:     /*         printf("\n "); */
                   5747:     /*   } */
                   5748:     /* } */
1.126     brouard  5749: 
                   5750:     for(i=1;i<=nlstate;i++)
                   5751:       varpl[i][(int)age] =0.;
1.209     brouard  5752:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5753:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5754:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5755:     }else{
1.126     brouard  5756:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5757:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5758:     }
1.126     brouard  5759:     for(i=1;i<=nlstate;i++)
                   5760:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5761: 
                   5762:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  5763:     if(nresult >=1)
                   5764:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  5765:     for(i=1; i<=nlstate;i++)
                   5766:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5767:     fprintf(ficresvpl,"\n");
                   5768:     free_vector(gp,1,nlstate);
                   5769:     free_vector(gm,1,nlstate);
1.208     brouard  5770:     free_matrix(mgm,1,npar,1,nlstate);
                   5771:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5772:     free_matrix(gradg,1,npar,1,nlstate);
                   5773:     free_matrix(trgradg,1,nlstate,1,npar);
                   5774:   } /* End age */
                   5775: 
                   5776:   free_vector(xp,1,npar);
                   5777:   free_matrix(doldm,1,nlstate,1,npar);
                   5778:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5779: 
                   5780: }
                   5781: 
                   5782: /************ Variance of one-step probabilities  ******************/
                   5783: 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  5784:  {
                   5785:    int i, j=0,  k1, l1, tj;
                   5786:    int k2, l2, j1,  z1;
                   5787:    int k=0, l;
                   5788:    int first=1, first1, first2;
                   5789:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5790:    double **dnewm,**doldm;
                   5791:    double *xp;
                   5792:    double *gp, *gm;
                   5793:    double **gradg, **trgradg;
                   5794:    double **mu;
                   5795:    double age, cov[NCOVMAX+1];
                   5796:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5797:    int theta;
                   5798:    char fileresprob[FILENAMELENGTH];
                   5799:    char fileresprobcov[FILENAMELENGTH];
                   5800:    char fileresprobcor[FILENAMELENGTH];
                   5801:    double ***varpij;
                   5802: 
                   5803:    strcpy(fileresprob,"PROB_"); 
                   5804:    strcat(fileresprob,fileres);
                   5805:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5806:      printf("Problem with resultfile: %s\n", fileresprob);
                   5807:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5808:    }
                   5809:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5810:    strcat(fileresprobcov,fileresu);
                   5811:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5812:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5813:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5814:    }
                   5815:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5816:    strcat(fileresprobcor,fileresu);
                   5817:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5818:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5819:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5820:    }
                   5821:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5822:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5823:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5824:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5825:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5826:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5827:    pstamp(ficresprob);
                   5828:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5829:    fprintf(ficresprob,"# Age");
                   5830:    pstamp(ficresprobcov);
                   5831:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5832:    fprintf(ficresprobcov,"# Age");
                   5833:    pstamp(ficresprobcor);
                   5834:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5835:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5836: 
                   5837: 
1.222     brouard  5838:    for(i=1; i<=nlstate;i++)
                   5839:      for(j=1; j<=(nlstate+ndeath);j++){
                   5840:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5841:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5842:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5843:      }  
                   5844:    /* fprintf(ficresprob,"\n");
                   5845:       fprintf(ficresprobcov,"\n");
                   5846:       fprintf(ficresprobcor,"\n");
                   5847:    */
                   5848:    xp=vector(1,npar);
                   5849:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5850:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5851:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5852:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5853:    first=1;
                   5854:    fprintf(ficgp,"\n# Routine varprob");
                   5855:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5856:    fprintf(fichtm,"\n");
                   5857: 
                   5858:    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);
                   5859:    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);
                   5860:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5861: and drawn. It helps understanding how is the covariance between two incidences.\
                   5862:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5863:    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  5864: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5865: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5866: standard deviations wide on each axis. <br>\
                   5867:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5868:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5869: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5870: 
1.222     brouard  5871:    cov[1]=1;
                   5872:    /* tj=cptcoveff; */
1.225     brouard  5873:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5874:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5875:    j1=0;
1.224     brouard  5876:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5877:      if  (cptcovn>0) {
                   5878:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5879:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5880:        fprintf(ficresprob, "**********\n#\n");
                   5881:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5882:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5883:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5884:                        
1.222     brouard  5885:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5886:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5887:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5888:                        
                   5889:                        
1.222     brouard  5890:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5891:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5892:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5893:                        
1.222     brouard  5894:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5895:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5896:        fprintf(ficresprobcor, "**********\n#");    
                   5897:        if(invalidvarcomb[j1]){
                   5898:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5899:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5900:         continue;
                   5901:        }
                   5902:      }
                   5903:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5904:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5905:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5906:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5907:      for (age=bage; age<=fage; age ++){ 
                   5908:        cov[2]=age;
                   5909:        if(nagesqr==1)
                   5910:         cov[3]= age*age;
                   5911:        for (k=1; k<=cptcovn;k++) {
                   5912:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5913:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5914:                                                                    * 1  1 1 1 1
                   5915:                                                                    * 2  2 1 1 1
                   5916:                                                                    * 3  1 2 1 1
                   5917:                                                                    */
                   5918:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5919:        }
                   5920:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5921:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5922:        for (k=1; k<=cptcovprod;k++)
                   5923:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5924:                        
                   5925:                        
1.222     brouard  5926:        for(theta=1; theta <=npar; theta++){
                   5927:         for(i=1; i<=npar; i++)
                   5928:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5929:                                
1.222     brouard  5930:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5931:                                
1.222     brouard  5932:         k=0;
                   5933:         for(i=1; i<= (nlstate); i++){
                   5934:           for(j=1; j<=(nlstate+ndeath);j++){
                   5935:             k=k+1;
                   5936:             gp[k]=pmmij[i][j];
                   5937:           }
                   5938:         }
1.220     brouard  5939:                                
1.222     brouard  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);
                   5944:         k=0;
                   5945:         for(i=1; i<=(nlstate); i++){
                   5946:           for(j=1; j<=(nlstate+ndeath);j++){
                   5947:             k=k+1;
                   5948:             gm[k]=pmmij[i][j];
                   5949:           }
                   5950:         }
1.220     brouard  5951:                                
1.222     brouard  5952:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5953:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5954:        }
1.126     brouard  5955: 
1.222     brouard  5956:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5957:         for(theta=1; theta <=npar; theta++)
                   5958:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5959:                        
1.222     brouard  5960:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5961:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5962:                        
1.222     brouard  5963:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5964:                        
1.222     brouard  5965:        k=0;
                   5966:        for(i=1; i<=(nlstate); i++){
                   5967:         for(j=1; j<=(nlstate+ndeath);j++){
                   5968:           k=k+1;
                   5969:           mu[k][(int) age]=pmmij[i][j];
                   5970:         }
                   5971:        }
                   5972:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5973:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5974:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5975:                        
1.222     brouard  5976:        /*printf("\n%d ",(int)age);
                   5977:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5978:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5979:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5980:         }*/
1.220     brouard  5981:                        
1.222     brouard  5982:        fprintf(ficresprob,"\n%d ",(int)age);
                   5983:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5984:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5985:                        
1.222     brouard  5986:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5987:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5988:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5989:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5990:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5991:        }
                   5992:        i=0;
                   5993:        for (k=1; k<=(nlstate);k++){
                   5994:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5995:           i++;
                   5996:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5997:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5998:           for (j=1; j<=i;j++){
                   5999:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6000:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6001:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6002:           }
                   6003:         }
                   6004:        }/* end of loop for state */
                   6005:      } /* end of loop for age */
                   6006:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6007:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6008:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6009:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6010:     
                   6011:      /* Confidence intervalle of pij  */
                   6012:      /*
                   6013:        fprintf(ficgp,"\nunset parametric;unset label");
                   6014:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6015:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6016:        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);
                   6017:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6018:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6019:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6020:      */
                   6021:                
                   6022:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6023:      first1=1;first2=2;
                   6024:      for (k2=1; k2<=(nlstate);k2++){
                   6025:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6026:         if(l2==k2) continue;
                   6027:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6028:         for (k1=1; k1<=(nlstate);k1++){
                   6029:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6030:             if(l1==k1) continue;
                   6031:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6032:             if(i<=j) continue;
                   6033:             for (age=bage; age<=fage; age ++){ 
                   6034:               if ((int)age %5==0){
                   6035:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6036:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6037:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6038:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6039:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6040:                 c12=cv12/sqrt(v1*v2);
                   6041:                 /* Computing eigen value of matrix of covariance */
                   6042:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6043:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6044:                 if ((lc2 <0) || (lc1 <0) ){
                   6045:                   if(first2==1){
                   6046:                     first1=0;
                   6047:                     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);
                   6048:                   }
                   6049:                   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);
                   6050:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6051:                   /* lc2=fabs(lc2); */
                   6052:                 }
1.220     brouard  6053:                                                                
1.222     brouard  6054:                 /* Eigen vectors */
                   6055:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6056:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6057:                 v21=(lc1-v1)/cv12*v11;
                   6058:                 v12=-v21;
                   6059:                 v22=v11;
                   6060:                 tnalp=v21/v11;
                   6061:                 if(first1==1){
                   6062:                   first1=0;
                   6063:                   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);
                   6064:                 }
                   6065:                 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);
                   6066:                 /*printf(fignu*/
                   6067:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6068:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6069:                 if(first==1){
                   6070:                   first=0;
                   6071:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6072:                   fprintf(ficgp,"\nset parametric;unset label");
                   6073:                   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);
                   6074:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6075:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6076:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6077: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6078:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6079:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6080:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6081:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6082:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6083:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6084:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6085:                   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",      \
                   6086:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6087:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6088:                 }else{
                   6089:                   first=0;
                   6090:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6091:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6092:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6093:                   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", \
                   6094:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6095:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6096:                 }/* if first */
                   6097:               } /* age mod 5 */
                   6098:             } /* end loop age */
                   6099:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6100:             first=1;
                   6101:           } /*l12 */
                   6102:         } /* k12 */
                   6103:        } /*l1 */
                   6104:      }/* k1 */
                   6105:    }  /* loop on combination of covariates j1 */
                   6106:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6107:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6108:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6109:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6110:    free_vector(xp,1,npar);
                   6111:    fclose(ficresprob);
                   6112:    fclose(ficresprobcov);
                   6113:    fclose(ficresprobcor);
                   6114:    fflush(ficgp);
                   6115:    fflush(fichtmcov);
                   6116:  }
1.126     brouard  6117: 
                   6118: 
                   6119: /******************* Printing html file ***********/
1.201     brouard  6120: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6121:                  int lastpass, int stepm, int weightopt, char model[],\
                   6122:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6123:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6124:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6125:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6126:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6127: 
                   6128:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6129:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6130: </ul>");
1.237     brouard  6131:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6132: </ul>", model);
1.214     brouard  6133:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6134:    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",
                   6135:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6136:    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  6137:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6138:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6139:    fprintf(fichtm,"\
                   6140:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6141:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6142:    fprintf(fichtm,"\
1.217     brouard  6143:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6144:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6145:    fprintf(fichtm,"\
1.126     brouard  6146:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6147:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6148:    fprintf(fichtm,"\
1.217     brouard  6149:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6150:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6151:    fprintf(fichtm,"\
1.211     brouard  6152:  - (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  6153:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6154:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6155:    if(prevfcast==1){
                   6156:      fprintf(fichtm,"\
                   6157:  - Prevalence projections by age and states:                           \
1.201     brouard  6158:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6159:    }
1.126     brouard  6160: 
1.222     brouard  6161:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6162: 
1.225     brouard  6163:    m=pow(2,cptcoveff);
1.222     brouard  6164:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6165: 
1.222     brouard  6166:    jj1=0;
1.237     brouard  6167: 
                   6168:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6169:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.237     brouard  6170:      if(TKresult[nres]!= k1)
                   6171:        continue;
1.220     brouard  6172: 
1.222     brouard  6173:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6174:      jj1++;
                   6175:      if (cptcovn > 0) {
                   6176:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6177:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6178:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6179:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6180:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6181:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6182:        }
1.237     brouard  6183:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6184:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6185:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6186:       }
                   6187:        
1.230     brouard  6188:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6189:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6190:        if(invalidvarcomb[k1]){
                   6191:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6192:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6193:         continue;
                   6194:        }
                   6195:      }
                   6196:      /* aij, bij */
1.241     brouard  6197:      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> \
                   6198: <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  6199:      /* Pij */
1.241     brouard  6200:      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> \
                   6201: <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  6202:      /* Quasi-incidences */
                   6203:      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  6204:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6205:  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  6206: 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> \
                   6207: <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  6208:      /* Survival functions (period) in state j */
                   6209:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6210:        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> \
                   6211: <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  6212:      }
                   6213:      /* State specific survival functions (period) */
                   6214:      for(cpt=1; cpt<=nlstate;cpt++){
                   6215:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6216:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6217:  <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  6218:      }
                   6219:      /* Period (stable) prevalence in each health state */
                   6220:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6221:        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> \
                   6222: <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  6223:      }
                   6224:      if(backcast==1){
                   6225:        /* Period (stable) back prevalence in each health state */
                   6226:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6227:         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> \
                   6228: <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  6229:        }
1.217     brouard  6230:      }
1.222     brouard  6231:      if(prevfcast==1){
                   6232:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6233:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6234:         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> \
                   6235: <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  6236:        }
                   6237:      }
1.220     brouard  6238:         
1.222     brouard  6239:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6240:        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> \
                   6241: <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  6242:      }
                   6243:      /* } /\* end i1 *\/ */
                   6244:    }/* End k1 */
                   6245:    fprintf(fichtm,"</ul>");
1.126     brouard  6246: 
1.222     brouard  6247:    fprintf(fichtm,"\
1.126     brouard  6248: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6249:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6250:  - 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  6251: But because parameters are usually highly correlated (a higher incidence of disability \
                   6252: and a higher incidence of recovery can give very close observed transition) it might \
                   6253: be very useful to look not only at linear confidence intervals estimated from the \
                   6254: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6255: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6256: covariance matrix of the one-step probabilities. \
                   6257: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6258: 
1.222     brouard  6259:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6260:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6261:    fprintf(fichtm,"\
1.126     brouard  6262:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6263:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6264: 
1.222     brouard  6265:    fprintf(fichtm,"\
1.126     brouard  6266:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6267:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6268:    fprintf(fichtm,"\
1.126     brouard  6269:  - 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): \
                   6270:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6271:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6272:    fprintf(fichtm,"\
1.126     brouard  6273:  - (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): \
                   6274:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6275:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6276:    fprintf(fichtm,"\
1.128     brouard  6277:  - 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  6278:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6279:    fprintf(fichtm,"\
1.128     brouard  6280:  - 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  6281:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6282:    fprintf(fichtm,"\
1.126     brouard  6283:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6284:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6285: 
                   6286: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6287: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6288: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6289: /*     <br>",fileres,fileres,fileres,fileres); */
                   6290: /*  else  */
                   6291: /*    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  6292:    fflush(fichtm);
                   6293:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6294: 
1.225     brouard  6295:    m=pow(2,cptcoveff);
1.222     brouard  6296:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6297: 
1.222     brouard  6298:    jj1=0;
1.237     brouard  6299: 
1.241     brouard  6300:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6301:    for(k1=1; k1<=m;k1++){
1.237     brouard  6302:      if(TKresult[nres]!= k1)
                   6303:        continue;
1.222     brouard  6304:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6305:      jj1++;
1.126     brouard  6306:      if (cptcovn > 0) {
                   6307:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6308:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6309:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6310:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6311:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6312:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6313:       }
                   6314: 
1.126     brouard  6315:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6316: 
1.222     brouard  6317:        if(invalidvarcomb[k1]){
                   6318:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6319:         continue;
                   6320:        }
1.126     brouard  6321:      }
                   6322:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6323:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
1.241     brouard  6324: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
                   6325: <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  6326:      }
                   6327:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6328: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6329: true period expectancies (those weighted with period prevalences are also\
                   6330:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6331:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6332: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6333:      /* } /\* end i1 *\/ */
                   6334:    }/* End k1 */
1.241     brouard  6335:   }/* End nres */
1.222     brouard  6336:    fprintf(fichtm,"</ul>");
                   6337:    fflush(fichtm);
1.126     brouard  6338: }
                   6339: 
                   6340: /******************* Gnuplot file **************/
1.223     brouard  6341: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6342: 
                   6343:   char dirfileres[132],optfileres[132];
1.223     brouard  6344:   char gplotcondition[132];
1.237     brouard  6345:   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  6346:   int lv=0, vlv=0, kl=0;
1.130     brouard  6347:   int ng=0;
1.201     brouard  6348:   int vpopbased;
1.223     brouard  6349:   int ioffset; /* variable offset for columns */
1.235     brouard  6350:   int nres=0; /* Index of resultline */
1.219     brouard  6351: 
1.126     brouard  6352: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6353: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6354: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6355: /*   } */
                   6356: 
                   6357:   /*#ifdef windows */
                   6358:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6359:   /*#endif */
1.225     brouard  6360:   m=pow(2,cptcoveff);
1.126     brouard  6361: 
1.202     brouard  6362:   /* Contribution to likelihood */
                   6363:   /* Plot the probability implied in the likelihood */
1.223     brouard  6364:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6365:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6366:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6367:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6368: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6369:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6370: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6371:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6372:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6373:   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));
                   6374:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6375:   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));
                   6376:   for (i=1; i<= nlstate ; i ++) {
                   6377:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6378:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6379:     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);
                   6380:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6381:       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);
                   6382:     }
                   6383:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6384:   }
                   6385:   /* 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 */               
                   6386:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6387:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6388:   fprintf(ficgp,"\nset out;unset log\n");
                   6389:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6390: 
1.126     brouard  6391:   strcpy(dirfileres,optionfilefiname);
                   6392:   strcpy(optfileres,"vpl");
1.223     brouard  6393:   /* 1eme*/
1.238     brouard  6394:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6395:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6396:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6397:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6398:        if(TKresult[nres]!= k1)
                   6399:          continue;
                   6400:        /* We are interested in selected combination by the resultline */
                   6401:        printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
                   6402:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6403:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6404:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6405:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6406:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6407:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6408:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6409:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   6410:          printf(" V%d=%d ",Tvaraff[k],vlv);
                   6411:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6412:        }
                   6413:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6414:          printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6415:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6416:        }       
                   6417:        printf("\n#\n");
                   6418:        fprintf(ficgp,"\n#\n");
                   6419:        if(invalidvarcomb[k1]){
                   6420:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6421:          continue;
                   6422:        }
1.235     brouard  6423:       
1.241     brouard  6424:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6425:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   6426:        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  6427:       
1.238     brouard  6428:        for (i=1; i<= nlstate ; i ++) {
                   6429:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6430:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6431:        }
1.242     brouard  6432:        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  6433:        for (i=1; i<= nlstate ; i ++) {
                   6434:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6435:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6436:        } 
1.242     brouard  6437:        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  6438:        for (i=1; i<= nlstate ; i ++) {
                   6439:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6440:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6441:        }  
                   6442:        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));
                   6443:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6444:          /* 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  6445:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6446:          if(cptcoveff ==0){
1.245   ! brouard  6447:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  6448:          }else{
                   6449:            kl=0;
                   6450:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6451:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6452:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6453:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6454:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6455:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6456:              kl++;
1.238     brouard  6457:              /* 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 *\/ */
                   6458:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6459:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6460:              /* ''  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*/
                   6461:              if(k==cptcoveff){
1.245   ! brouard  6462:                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  6463:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6464:              }else{
                   6465:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6466:                kl++;
                   6467:              }
                   6468:            } /* end covariate */
                   6469:          } /* end if no covariate */
                   6470:        } /* end if backcast */
                   6471:        fprintf(ficgp,"\nset out \n");
                   6472:       } /* nres */
1.201     brouard  6473:     } /* k1 */
                   6474:   } /* cpt */
1.235     brouard  6475: 
                   6476:   
1.126     brouard  6477:   /*2 eme*/
1.238     brouard  6478:   for (k1=1; k1<= m ; k1 ++){  
                   6479:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6480:       if(TKresult[nres]!= k1)
                   6481:        continue;
                   6482:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6483:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6484:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6485:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6486:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6487:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6488:        vlv= nbcode[Tvaraff[k]][lv];
                   6489:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6490:       }
1.237     brouard  6491:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6492:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6493:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6494:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6495:       }
1.211     brouard  6496:       fprintf(ficgp,"\n#\n");
1.223     brouard  6497:       if(invalidvarcomb[k1]){
                   6498:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6499:        continue;
                   6500:       }
1.219     brouard  6501:                        
1.241     brouard  6502:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6503:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6504:        if(vpopbased==0)
                   6505:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6506:        else
                   6507:          fprintf(ficgp,"\nreplot ");
                   6508:        for (i=1; i<= nlstate+1 ; i ++) {
                   6509:          k=2*i;
                   6510:          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);
                   6511:          for (j=1; j<= nlstate+1 ; j ++) {
                   6512:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6513:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6514:          }   
                   6515:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6516:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6517:          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);
                   6518:          for (j=1; j<= nlstate+1 ; j ++) {
                   6519:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6520:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6521:          }   
                   6522:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6523:          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);
                   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== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6529:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6530:        } /* state */
                   6531:       } /* vpopbased */
1.244     brouard  6532:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  6533:     } /* end nres */
                   6534:   } /* k1 end 2 eme*/
                   6535:        
                   6536:        
                   6537:   /*3eme*/
                   6538:   for (k1=1; k1<= m ; k1 ++){
                   6539:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.240     brouard  6540:       if(TKresult[nres]!= k1)
1.238     brouard  6541:        continue;
                   6542: 
                   6543:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6544:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6545:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6546:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6547:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6548:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6549:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6550:          vlv= nbcode[Tvaraff[k]][lv];
                   6551:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6552:        }
                   6553:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6554:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6555:        }       
                   6556:        fprintf(ficgp,"\n#\n");
                   6557:        if(invalidvarcomb[k1]){
                   6558:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6559:          continue;
                   6560:        }
                   6561:                        
                   6562:        /*       k=2+nlstate*(2*cpt-2); */
                   6563:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6564:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6565:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6566: 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  6567:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6568:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6569:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6570:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6571:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6572:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6573:                                
1.238     brouard  6574:        */
                   6575:        for (i=1; i< nlstate ; i ++) {
                   6576:          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);
                   6577:          /*    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  6578:                                
1.238     brouard  6579:        } 
                   6580:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6581:       }
                   6582:     } /* end nres */
                   6583:   } /* end kl 3eme */
1.126     brouard  6584:   
1.223     brouard  6585:   /* 4eme */
1.201     brouard  6586:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6587:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6588:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6589:       if(TKresult[nres]!= k1)
1.223     brouard  6590:        continue;
1.238     brouard  6591:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6592:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6593:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6594:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6595:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6596:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6597:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6598:          vlv= nbcode[Tvaraff[k]][lv];
                   6599:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6600:        }
                   6601:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6602:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6603:        }       
                   6604:        fprintf(ficgp,"\n#\n");
                   6605:        if(invalidvarcomb[k1]){
                   6606:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6607:          continue;
1.223     brouard  6608:        }
1.238     brouard  6609:       
1.241     brouard  6610:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6611:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6612: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6613:        k=3;
                   6614:        for (i=1; i<= nlstate ; i ++){
                   6615:          if(i==1){
                   6616:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6617:          }else{
                   6618:            fprintf(ficgp,", '' ");
                   6619:          }
                   6620:          l=(nlstate+ndeath)*(i-1)+1;
                   6621:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6622:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6623:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6624:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6625:        } /* nlstate */
                   6626:        fprintf(ficgp,"\nset out\n");
                   6627:       } /* end cpt state*/ 
                   6628:     } /* end nres */
                   6629:   } /* end covariate k1 */  
                   6630: 
1.220     brouard  6631: /* 5eme */
1.201     brouard  6632:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6633:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6634:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6635:       if(TKresult[nres]!= k1)
1.227     brouard  6636:        continue;
1.238     brouard  6637:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6638:        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);
                   6639:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6640:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6641:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6642:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6643:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6644:          vlv= nbcode[Tvaraff[k]][lv];
                   6645:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6646:        }
                   6647:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6648:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6649:        }       
                   6650:        fprintf(ficgp,"\n#\n");
                   6651:        if(invalidvarcomb[k1]){
                   6652:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6653:          continue;
                   6654:        }
1.227     brouard  6655:       
1.241     brouard  6656:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6657:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6658: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6659:        k=3;
                   6660:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6661:          if(j==1)
                   6662:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6663:          else
                   6664:            fprintf(ficgp,", '' ");
                   6665:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6666:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6667:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6668:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6669:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6670:        } /* nlstate */
                   6671:        fprintf(ficgp,", '' ");
                   6672:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6673:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6674:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6675:          if(j < nlstate)
                   6676:            fprintf(ficgp,"$%d +",k+l);
                   6677:          else
                   6678:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6679:        }
                   6680:        fprintf(ficgp,"\nset out\n");
                   6681:       } /* end cpt state*/ 
                   6682:     } /* end covariate */  
                   6683:   } /* end nres */
1.227     brouard  6684:   
1.220     brouard  6685: /* 6eme */
1.202     brouard  6686:   /* CV preval stable (period) for each covariate */
1.237     brouard  6687:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6688:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6689:     if(TKresult[nres]!= k1)
                   6690:       continue;
1.153     brouard  6691:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6692:       
1.211     brouard  6693:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6694:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6695:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6696:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6697:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6698:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6699:        vlv= nbcode[Tvaraff[k]][lv];
                   6700:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6701:       }
1.237     brouard  6702:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6703:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6704:       }        
1.211     brouard  6705:       fprintf(ficgp,"\n#\n");
1.223     brouard  6706:       if(invalidvarcomb[k1]){
1.227     brouard  6707:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6708:        continue;
1.223     brouard  6709:       }
1.227     brouard  6710:       
1.241     brouard  6711:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6712:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6713: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6714:       k=3; /* Offset */
1.153     brouard  6715:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6716:        if(i==1)
                   6717:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6718:        else
                   6719:          fprintf(ficgp,", '' ");
                   6720:        l=(nlstate+ndeath)*(i-1)+1;
                   6721:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6722:        for (j=2; j<= nlstate ; j ++)
                   6723:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6724:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6725:       } /* nlstate */
1.201     brouard  6726:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6727:     } /* end cpt state*/ 
                   6728:   } /* end covariate */  
1.227     brouard  6729:   
                   6730:   
1.220     brouard  6731: /* 7eme */
1.218     brouard  6732:   if(backcast == 1){
1.217     brouard  6733:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6734:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6735:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6736:       if(TKresult[nres]!= k1)
                   6737:        continue;
1.218     brouard  6738:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6739:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6740:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6741:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6742:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6743:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6744:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6745:          vlv= nbcode[Tvaraff[k]][lv];
                   6746:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6747:        }
1.237     brouard  6748:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6749:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6750:        }       
1.227     brouard  6751:        fprintf(ficgp,"\n#\n");
                   6752:        if(invalidvarcomb[k1]){
                   6753:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6754:          continue;
                   6755:        }
                   6756:        
1.241     brouard  6757:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  6758:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6759: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6760:        k=3; /* Offset */
                   6761:        for (i=1; i<= nlstate ; i ++){
                   6762:          if(i==1)
                   6763:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6764:          else
                   6765:            fprintf(ficgp,", '' ");
                   6766:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6767:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6768:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6769:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6770:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6771:          /* for (j=2; j<= nlstate ; j ++) */
                   6772:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6773:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6774:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6775:        } /* nlstate */
                   6776:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6777:       } /* end cpt state*/ 
                   6778:     } /* end covariate */  
                   6779:   } /* End if backcast */
                   6780:   
1.223     brouard  6781:   /* 8eme */
1.218     brouard  6782:   if(prevfcast==1){
                   6783:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6784:     
1.237     brouard  6785:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6786:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6787:       if(TKresult[nres]!= k1)
                   6788:        continue;
1.211     brouard  6789:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6790:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6791:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6792:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6793:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6794:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6795:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6796:          vlv= nbcode[Tvaraff[k]][lv];
                   6797:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6798:        }
1.237     brouard  6799:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6800:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6801:        }       
1.227     brouard  6802:        fprintf(ficgp,"\n#\n");
                   6803:        if(invalidvarcomb[k1]){
                   6804:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6805:          continue;
                   6806:        }
                   6807:        
                   6808:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  6809:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  6810:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  6811: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6812:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6813:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6814:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6815:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6816:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6817:          if(i==1){
                   6818:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6819:          }else{
                   6820:            fprintf(ficgp,",\\\n '' ");
                   6821:          }
                   6822:          if(cptcoveff ==0){ /* No covariate */
                   6823:            ioffset=2; /* Age is in 2 */
                   6824:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6825:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6826:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6827:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6828:            fprintf(ficgp," u %d:(", ioffset); 
                   6829:            if(i==nlstate+1)
                   6830:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6831:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6832:            else
                   6833:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6834:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6835:          }else{ /* more than 2 covariates */
                   6836:            if(cptcoveff ==1){
                   6837:              ioffset=4; /* Age is in 4 */
                   6838:            }else{
                   6839:              ioffset=6; /* Age is in 6 */
                   6840:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6841:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6842:            }   
                   6843:            fprintf(ficgp," u %d:(",ioffset); 
                   6844:            kl=0;
                   6845:            strcpy(gplotcondition,"(");
                   6846:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6847:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6848:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6849:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6850:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6851:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6852:              kl++;
                   6853:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6854:              kl++;
                   6855:              if(k <cptcoveff && cptcoveff>1)
                   6856:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6857:            }
                   6858:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6859:            /* 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 *\/ */
                   6860:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6861:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6862:            /* ''  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*/
                   6863:            if(i==nlstate+1){
                   6864:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6865:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6866:            }else{
                   6867:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6868:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6869:            }
                   6870:          } /* end if covariate */
                   6871:        } /* nlstate */
                   6872:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6873:       } /* end cpt state*/
                   6874:     } /* end covariate */
                   6875:   } /* End if prevfcast */
1.227     brouard  6876:   
                   6877:   
1.238     brouard  6878:   /* 9eme writing MLE parameters */
                   6879:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6880:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6881:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6882:     for(k=1; k <=(nlstate+ndeath); k++){
                   6883:       if (k != i) {
1.227     brouard  6884:        fprintf(ficgp,"#   current state %d\n",k);
                   6885:        for(j=1; j <=ncovmodel; j++){
                   6886:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6887:          jk++; 
                   6888:        }
                   6889:        fprintf(ficgp,"\n");
1.126     brouard  6890:       }
                   6891:     }
1.223     brouard  6892:   }
1.187     brouard  6893:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6894:   
1.145     brouard  6895:   /*goto avoid;*/
1.238     brouard  6896:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   6897:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6898:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6899:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6900:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6901:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6902:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6903:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6904:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6905:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6906:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6907:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6908:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6909:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6910:   fprintf(ficgp,"#\n");
1.223     brouard  6911:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  6912:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6913:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  6914:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6915:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6916:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6917:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6918:       if(TKresult[nres]!= jk)
                   6919:        continue;
                   6920:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6921:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6922:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6923:       }        
                   6924:       fprintf(ficgp,"\n#\n");
1.241     brouard  6925:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  6926:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6927:       if (ng==1){
                   6928:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6929:        fprintf(ficgp,"\nunset log y");
                   6930:       }else if (ng==2){
                   6931:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6932:        fprintf(ficgp,"\nset log y");
                   6933:       }else if (ng==3){
                   6934:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6935:        fprintf(ficgp,"\nset log y");
                   6936:       }else
                   6937:        fprintf(ficgp,"\nunset title ");
                   6938:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6939:       i=1;
                   6940:       for(k2=1; k2<=nlstate; k2++) {
                   6941:        k3=i;
                   6942:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6943:          if (k != k2){
                   6944:            switch( ng) {
                   6945:            case 1:
                   6946:              if(nagesqr==0)
                   6947:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6948:              else /* nagesqr =1 */
                   6949:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6950:              break;
                   6951:            case 2: /* ng=2 */
                   6952:              if(nagesqr==0)
                   6953:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6954:              else /* nagesqr =1 */
                   6955:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6956:              break;
                   6957:            case 3:
                   6958:              if(nagesqr==0)
                   6959:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6960:              else /* nagesqr =1 */
                   6961:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6962:              break;
                   6963:            }
                   6964:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  6965:            ijp=1; /* product no age */
                   6966:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   6967:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  6968:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  6969:              if(j==Tage[ij]) { /* Product by age */
                   6970:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  6971:                  if(DummyV[j]==0){
1.237     brouard  6972:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   6973:                  }else{ /* quantitative */
                   6974:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   6975:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6976:                  }
                   6977:                  ij++;
                   6978:                }
                   6979:              }else if(j==Tprod[ijp]) { /* */ 
                   6980:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   6981:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  6982:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   6983:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  6984:                      /* 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)]); */
                   6985:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   6986:                    }else{ /* Vn is dummy and Vm is quanti */
                   6987:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   6988:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6989:                    }
                   6990:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  6991:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  6992:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   6993:                    }else{ /* Both quanti */
                   6994:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6995:                    }
                   6996:                  }
1.238     brouard  6997:                  ijp++;
1.237     brouard  6998:                }
                   6999:              } else{  /* simple covariate */
                   7000:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   7001:                if(Dummy[j]==0){
                   7002:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   7003:                }else{ /* quantitative */
                   7004:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  7005:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7006:                }
1.237     brouard  7007:              } /* end simple */
                   7008:            } /* end j */
1.223     brouard  7009:          }else{
                   7010:            i=i-ncovmodel;
                   7011:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7012:              fprintf(ficgp," (1.");
                   7013:          }
1.227     brouard  7014:          
1.223     brouard  7015:          if(ng != 1){
                   7016:            fprintf(ficgp,")/(1");
1.227     brouard  7017:            
1.223     brouard  7018:            for(k1=1; k1 <=nlstate; k1++){ 
                   7019:              if(nagesqr==0)
                   7020:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7021:              else /* nagesqr =1 */
                   7022:                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  7023:               
1.223     brouard  7024:              ij=1;
                   7025:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7026:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7027:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7028:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7029:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7030:                    ij++;
                   7031:                  }
                   7032:                }
                   7033:                else
1.225     brouard  7034:                  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  7035:              }
                   7036:              fprintf(ficgp,")");
                   7037:            }
                   7038:            fprintf(ficgp,")");
                   7039:            if(ng ==2)
                   7040:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7041:            else /* ng= 3 */
                   7042:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7043:          }else{ /* end ng <> 1 */
                   7044:            if( k !=k2) /* logit p11 is hard to draw */
                   7045:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7046:          }
                   7047:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7048:            fprintf(ficgp,",");
                   7049:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7050:            fprintf(ficgp,",");
                   7051:          i=i+ncovmodel;
                   7052:        } /* end k */
                   7053:       } /* end k2 */
                   7054:       fprintf(ficgp,"\n set out\n");
                   7055:     } /* end jk */
                   7056:   } /* end ng */
                   7057:   /* avoid: */
                   7058:   fflush(ficgp); 
1.126     brouard  7059: }  /* end gnuplot */
                   7060: 
                   7061: 
                   7062: /*************** Moving average **************/
1.219     brouard  7063: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7064:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7065:    
1.222     brouard  7066:    int i, cpt, cptcod;
                   7067:    int modcovmax =1;
                   7068:    int mobilavrange, mob;
                   7069:    int iage=0;
                   7070: 
                   7071:    double sum=0.;
                   7072:    double age;
                   7073:    double *sumnewp, *sumnewm;
                   7074:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7075:   
                   7076:   
1.225     brouard  7077:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7078:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7079: 
                   7080:    sumnewp = vector(1,ncovcombmax);
                   7081:    sumnewm = vector(1,ncovcombmax);
                   7082:    agemingood = vector(1,ncovcombmax); 
                   7083:    agemaxgood = vector(1,ncovcombmax);
                   7084: 
                   7085:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7086:      sumnewm[cptcod]=0.;
                   7087:      sumnewp[cptcod]=0.;
                   7088:      agemingood[cptcod]=0;
                   7089:      agemaxgood[cptcod]=0;
                   7090:    }
                   7091:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7092:   
                   7093:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7094:      if(mobilav==1) mobilavrange=5; /* default */
                   7095:      else mobilavrange=mobilav;
                   7096:      for (age=bage; age<=fage; age++)
                   7097:        for (i=1; i<=nlstate;i++)
                   7098:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7099:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7100:      /* We keep the original values on the extreme ages bage, fage and for 
                   7101:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7102:        we use a 5 terms etc. until the borders are no more concerned. 
                   7103:      */ 
                   7104:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7105:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7106:         for (i=1; i<=nlstate;i++){
                   7107:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7108:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7109:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7110:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7111:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7112:             }
                   7113:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7114:           }
                   7115:         }
                   7116:        }/* end age */
                   7117:      }/* end mob */
                   7118:    }else
                   7119:      return -1;
                   7120:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7121:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7122:      if(invalidvarcomb[cptcod]){
                   7123:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7124:        continue;
                   7125:      }
1.219     brouard  7126: 
1.222     brouard  7127:      agemingood[cptcod]=fage-(mob-1)/2;
                   7128:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7129:        sumnewm[cptcod]=0.;
                   7130:        for (i=1; i<=nlstate;i++){
                   7131:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7132:        }
                   7133:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7134:         agemingood[cptcod]=age;
                   7135:        }else{ /* bad */
                   7136:         for (i=1; i<=nlstate;i++){
                   7137:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7138:         } /* i */
                   7139:        } /* end bad */
                   7140:      }/* age */
                   7141:      sum=0.;
                   7142:      for (i=1; i<=nlstate;i++){
                   7143:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7144:      }
                   7145:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7146:        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);
                   7147:        /* for (i=1; i<=nlstate;i++){ */
                   7148:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7149:        /* } /\* i *\/ */
                   7150:      } /* end bad */
                   7151:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7152:      /* From youngest, finding the oldest wrong */
                   7153:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7154:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7155:        sumnewm[cptcod]=0.;
                   7156:        for (i=1; i<=nlstate;i++){
                   7157:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7158:        }
                   7159:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7160:         agemaxgood[cptcod]=age;
                   7161:        }else{ /* bad */
                   7162:         for (i=1; i<=nlstate;i++){
                   7163:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7164:         } /* i */
                   7165:        } /* end bad */
                   7166:      }/* age */
                   7167:      sum=0.;
                   7168:      for (i=1; i<=nlstate;i++){
                   7169:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7170:      }
                   7171:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7172:        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);
                   7173:        /* for (i=1; i<=nlstate;i++){ */
                   7174:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7175:        /* } /\* i *\/ */
                   7176:      } /* end bad */
                   7177:                
                   7178:      for (age=bage; age<=fage; age++){
1.235     brouard  7179:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7180:        sumnewp[cptcod]=0.;
                   7181:        sumnewm[cptcod]=0.;
                   7182:        for (i=1; i<=nlstate;i++){
                   7183:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7184:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7185:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7186:        }
                   7187:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7188:      }
                   7189:      /* printf("\n"); */
                   7190:      /* } */
                   7191:      /* brutal averaging */
                   7192:      for (i=1; i<=nlstate;i++){
                   7193:        for (age=1; age<=bage; age++){
                   7194:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7195:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7196:        }       
                   7197:        for (age=fage; age<=AGESUP; age++){
                   7198:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7199:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7200:        }
                   7201:      } /* end i status */
                   7202:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7203:        for (age=1; age<=AGESUP; age++){
                   7204:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7205:         mobaverage[(int)age][i][cptcod]=0.;
                   7206:        }
                   7207:      }
                   7208:    }/* end cptcod */
                   7209:    free_vector(sumnewm,1, ncovcombmax);
                   7210:    free_vector(sumnewp,1, ncovcombmax);
                   7211:    free_vector(agemaxgood,1, ncovcombmax);
                   7212:    free_vector(agemingood,1, ncovcombmax);
                   7213:    return 0;
                   7214:  }/* End movingaverage */
1.218     brouard  7215:  
1.126     brouard  7216: 
                   7217: /************** Forecasting ******************/
1.235     brouard  7218:  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  7219:   /* proj1, year, month, day of starting projection 
                   7220:      agemin, agemax range of age
                   7221:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7222:      anproj2 year of en of projection (same day and month as proj1).
                   7223:   */
1.235     brouard  7224:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7225:   double agec; /* generic age */
                   7226:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7227:   double *popeffectif,*popcount;
                   7228:   double ***p3mat;
1.218     brouard  7229:   /* double ***mobaverage; */
1.126     brouard  7230:   char fileresf[FILENAMELENGTH];
                   7231: 
                   7232:   agelim=AGESUP;
1.211     brouard  7233:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7234:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7235:      We still use firstpass and lastpass as another selection.
                   7236:   */
1.214     brouard  7237:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7238:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7239:  
1.201     brouard  7240:   strcpy(fileresf,"F_"); 
                   7241:   strcat(fileresf,fileresu);
1.126     brouard  7242:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7243:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7244:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7245:   }
1.235     brouard  7246:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7247:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7248: 
1.225     brouard  7249:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7250: 
                   7251: 
                   7252:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7253:   if (stepm<=12) stepsize=1;
                   7254:   if(estepm < stepm){
                   7255:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7256:   }
                   7257:   else  hstepm=estepm;   
                   7258: 
                   7259:   hstepm=hstepm/stepm; 
                   7260:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7261:                                fractional in yp1 */
                   7262:   anprojmean=yp;
                   7263:   yp2=modf((yp1*12),&yp);
                   7264:   mprojmean=yp;
                   7265:   yp1=modf((yp2*30.5),&yp);
                   7266:   jprojmean=yp;
                   7267:   if(jprojmean==0) jprojmean=1;
                   7268:   if(mprojmean==0) jprojmean=1;
                   7269: 
1.227     brouard  7270:   i1=pow(2,cptcoveff);
1.126     brouard  7271:   if (cptcovn < 1){i1=1;}
                   7272:   
                   7273:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7274:   
                   7275:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7276:   
1.126     brouard  7277: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7278:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7279:   for(k=1; k<=i1;k++){
                   7280:     if(TKresult[nres]!= k)
                   7281:       continue;
1.227     brouard  7282:     if(invalidvarcomb[k]){
                   7283:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7284:       continue;
                   7285:     }
                   7286:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7287:     for(j=1;j<=cptcoveff;j++) {
                   7288:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7289:     }
1.235     brouard  7290:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7291:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7292:     }
1.227     brouard  7293:     fprintf(ficresf," yearproj age");
                   7294:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7295:       for(i=1; i<=nlstate;i++)               
                   7296:        fprintf(ficresf," p%d%d",i,j);
                   7297:       fprintf(ficresf," wp.%d",j);
                   7298:     }
                   7299:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7300:       fprintf(ficresf,"\n");
                   7301:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7302:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7303:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7304:        nhstepm = nhstepm/hstepm; 
                   7305:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7306:        oldm=oldms;savm=savms;
1.235     brouard  7307:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7308:        
                   7309:        for (h=0; h<=nhstepm; h++){
                   7310:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7311:            fprintf(ficresf,"\n");
                   7312:            for(j=1;j<=cptcoveff;j++) 
                   7313:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7314:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7315:          } 
                   7316:          for(j=1; j<=nlstate+ndeath;j++) {
                   7317:            ppij=0.;
                   7318:            for(i=1; i<=nlstate;i++) {
                   7319:              if (mobilav==1) 
                   7320:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7321:              else {
                   7322:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7323:              }
                   7324:              if (h*hstepm/YEARM*stepm== yearp) {
                   7325:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7326:              }
                   7327:            } /* end i */
                   7328:            if (h*hstepm/YEARM*stepm==yearp) {
                   7329:              fprintf(ficresf," %.3f", ppij);
                   7330:            }
                   7331:          }/* end j */
                   7332:        } /* end h */
                   7333:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7334:       } /* end agec */
                   7335:     } /* end yearp */
                   7336:   } /* end  k */
1.219     brouard  7337:        
1.126     brouard  7338:   fclose(ficresf);
1.215     brouard  7339:   printf("End of Computing forecasting \n");
                   7340:   fprintf(ficlog,"End of Computing forecasting\n");
                   7341: 
1.126     brouard  7342: }
                   7343: 
1.218     brouard  7344: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7345: /* 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  7346: /*   /\* back1, year, month, day of starting backection  */
                   7347: /*      agemin, agemax range of age */
                   7348: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7349: /*      anback2 year of en of backection (same day and month as back1). */
                   7350: /*   *\/ */
                   7351: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7352: /*   double agec; /\* generic age *\/ */
                   7353: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7354: /*   double *popeffectif,*popcount; */
                   7355: /*   double ***p3mat; */
                   7356: /*   /\* double ***mobaverage; *\/ */
                   7357: /*   char fileresfb[FILENAMELENGTH]; */
                   7358:        
                   7359: /*   agelim=AGESUP; */
                   7360: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7361: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7362: /*      We still use firstpass and lastpass as another selection. */
                   7363: /*   *\/ */
                   7364: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7365: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7366: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7367:        
                   7368: /*   strcpy(fileresfb,"FB_");  */
                   7369: /*   strcat(fileresfb,fileresu); */
                   7370: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7371: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7372: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7373: /*   } */
                   7374: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7375: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7376:        
1.225     brouard  7377: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7378:        
                   7379: /*   /\* if (mobilav!=0) { *\/ */
                   7380: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7381: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7382: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7383: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7384: /*   /\*   } *\/ */
                   7385: /*   /\* } *\/ */
                   7386:        
                   7387: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7388: /*   if (stepm<=12) stepsize=1; */
                   7389: /*   if(estepm < stepm){ */
                   7390: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7391: /*   } */
                   7392: /*   else  hstepm=estepm;    */
                   7393:        
                   7394: /*   hstepm=hstepm/stepm;  */
                   7395: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7396: /*                                fractional in yp1 *\/ */
                   7397: /*   anprojmean=yp; */
                   7398: /*   yp2=modf((yp1*12),&yp); */
                   7399: /*   mprojmean=yp; */
                   7400: /*   yp1=modf((yp2*30.5),&yp); */
                   7401: /*   jprojmean=yp; */
                   7402: /*   if(jprojmean==0) jprojmean=1; */
                   7403: /*   if(mprojmean==0) jprojmean=1; */
                   7404:        
1.225     brouard  7405: /*   i1=cptcoveff; */
1.218     brouard  7406: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7407:   
1.218     brouard  7408: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7409:   
1.218     brouard  7410: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7411:        
                   7412: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7413: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7414: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7415: /*       k=k+1; */
                   7416: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7417: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7418: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7419: /*       } */
                   7420: /*       fprintf(ficresfb," yearbproj age"); */
                   7421: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7422: /*                             for(i=1; i<=nlstate;i++)               */
                   7423: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7424: /*                             fprintf(ficresfb," p.%d",j); */
                   7425: /*       } */
                   7426: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7427: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7428: /*                             fprintf(ficresfb,"\n"); */
                   7429: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7430: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7431: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7432: /*                                     nhstepm = nhstepm/hstepm;  */
                   7433: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7434: /*                                     oldm=oldms;savm=savms; */
                   7435: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7436: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7437: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7438: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7439: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7440: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7441: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7442: /*                                             }  */
                   7443: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7444: /*                                                     ppij=0.; */
                   7445: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7446: /*                                                             if (mobilav==1)  */
                   7447: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7448: /*                                                             else { */
                   7449: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7450: /*                                                             } */
                   7451: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7452: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7453: /*                                                             } */
                   7454: /*                                                     } /\* end i *\/ */
                   7455: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7456: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7457: /*                                                     } */
                   7458: /*                                             }/\* end j *\/ */
                   7459: /*                                     } /\* end h *\/ */
                   7460: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7461: /*                             } /\* end agec *\/ */
                   7462: /*       } /\* end yearp *\/ */
                   7463: /*     } /\* end cptcod *\/ */
                   7464: /*   } /\* end  cptcov *\/ */
                   7465:        
                   7466: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7467:        
                   7468: /*   fclose(ficresfb); */
                   7469: /*   printf("End of Computing Back forecasting \n"); */
                   7470: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7471:        
1.218     brouard  7472: /* } */
1.217     brouard  7473: 
1.126     brouard  7474: /************** Forecasting *****not tested NB*************/
1.227     brouard  7475: /* 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  7476:   
1.227     brouard  7477: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7478: /*   int *popage; */
                   7479: /*   double calagedatem, agelim, kk1, kk2; */
                   7480: /*   double *popeffectif,*popcount; */
                   7481: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7482: /*   /\* double ***mobaverage; *\/ */
                   7483: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7484: 
1.227     brouard  7485: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7486: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7487: /*   agelim=AGESUP; */
                   7488: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7489:   
1.227     brouard  7490: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7491:   
                   7492:   
1.227     brouard  7493: /*   strcpy(filerespop,"POP_");  */
                   7494: /*   strcat(filerespop,fileresu); */
                   7495: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7496: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7497: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7498: /*   } */
                   7499: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7500: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7501: 
1.227     brouard  7502: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7503: 
1.227     brouard  7504: /*   /\* if (mobilav!=0) { *\/ */
                   7505: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7506: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7507: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7508: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7509: /*   /\*   } *\/ */
                   7510: /*   /\* } *\/ */
1.126     brouard  7511: 
1.227     brouard  7512: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7513: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7514:   
1.227     brouard  7515: /*   agelim=AGESUP; */
1.126     brouard  7516:   
1.227     brouard  7517: /*   hstepm=1; */
                   7518: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7519:        
1.227     brouard  7520: /*   if (popforecast==1) { */
                   7521: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7522: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7523: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7524: /*     }  */
                   7525: /*     popage=ivector(0,AGESUP); */
                   7526: /*     popeffectif=vector(0,AGESUP); */
                   7527: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7528:     
1.227     brouard  7529: /*     i=1;    */
                   7530: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7531:     
1.227     brouard  7532: /*     imx=i; */
                   7533: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7534: /*   } */
1.218     brouard  7535:   
1.227     brouard  7536: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7537: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7538: /*       k=k+1; */
                   7539: /*       fprintf(ficrespop,"\n#******"); */
                   7540: /*       for(j=1;j<=cptcoveff;j++) { */
                   7541: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7542: /*       } */
                   7543: /*       fprintf(ficrespop,"******\n"); */
                   7544: /*       fprintf(ficrespop,"# Age"); */
                   7545: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7546: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7547:       
1.227     brouard  7548: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7549: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7550:        
1.227     brouard  7551: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7552: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7553: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7554:          
1.227     brouard  7555: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7556: /*       oldm=oldms;savm=savms; */
                   7557: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7558:          
1.227     brouard  7559: /*       for (h=0; h<=nhstepm; h++){ */
                   7560: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7561: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7562: /*         }  */
                   7563: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7564: /*           kk1=0.;kk2=0; */
                   7565: /*           for(i=1; i<=nlstate;i++) {               */
                   7566: /*             if (mobilav==1)  */
                   7567: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7568: /*             else { */
                   7569: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7570: /*             } */
                   7571: /*           } */
                   7572: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7573: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7574: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7575: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7576: /*           } */
                   7577: /*         } */
                   7578: /*         for(i=1; i<=nlstate;i++){ */
                   7579: /*           kk1=0.; */
                   7580: /*           for(j=1; j<=nlstate;j++){ */
                   7581: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7582: /*           } */
                   7583: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7584: /*         } */
1.218     brouard  7585:            
1.227     brouard  7586: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7587: /*           for(j=1; j<=nlstate;j++)  */
                   7588: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7589: /*       } */
                   7590: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7591: /*     } */
                   7592: /*       } */
1.218     brouard  7593:       
1.227     brouard  7594: /*       /\******\/ */
1.218     brouard  7595:       
1.227     brouard  7596: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7597: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7598: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7599: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7600: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7601:          
1.227     brouard  7602: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7603: /*       oldm=oldms;savm=savms; */
                   7604: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7605: /*       for (h=0; h<=nhstepm; h++){ */
                   7606: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7607: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7608: /*         }  */
                   7609: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7610: /*           kk1=0.;kk2=0; */
                   7611: /*           for(i=1; i<=nlstate;i++) {               */
                   7612: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7613: /*           } */
                   7614: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7615: /*         } */
                   7616: /*       } */
                   7617: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7618: /*     } */
                   7619: /*       } */
                   7620: /*     }  */
                   7621: /*   } */
1.218     brouard  7622:   
1.227     brouard  7623: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7624:   
1.227     brouard  7625: /*   if (popforecast==1) { */
                   7626: /*     free_ivector(popage,0,AGESUP); */
                   7627: /*     free_vector(popeffectif,0,AGESUP); */
                   7628: /*     free_vector(popcount,0,AGESUP); */
                   7629: /*   } */
                   7630: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7631: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7632: /*   fclose(ficrespop); */
                   7633: /* } /\* End of popforecast *\/ */
1.218     brouard  7634:  
1.126     brouard  7635: int fileappend(FILE *fichier, char *optionfich)
                   7636: {
                   7637:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7638:     printf("Problem with file: %s\n", optionfich);
                   7639:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7640:     return (0);
                   7641:   }
                   7642:   fflush(fichier);
                   7643:   return (1);
                   7644: }
                   7645: 
                   7646: 
                   7647: /**************** function prwizard **********************/
                   7648: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7649: {
                   7650: 
                   7651:   /* Wizard to print covariance matrix template */
                   7652: 
1.164     brouard  7653:   char ca[32], cb[32];
                   7654:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7655:   int numlinepar;
                   7656: 
                   7657:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7658:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7659:   for(i=1; i <=nlstate; i++){
                   7660:     jj=0;
                   7661:     for(j=1; j <=nlstate+ndeath; j++){
                   7662:       if(j==i) continue;
                   7663:       jj++;
                   7664:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7665:       printf("%1d%1d",i,j);
                   7666:       fprintf(ficparo,"%1d%1d",i,j);
                   7667:       for(k=1; k<=ncovmodel;k++){
                   7668:        /*        printf(" %lf",param[i][j][k]); */
                   7669:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7670:        printf(" 0.");
                   7671:        fprintf(ficparo," 0.");
                   7672:       }
                   7673:       printf("\n");
                   7674:       fprintf(ficparo,"\n");
                   7675:     }
                   7676:   }
                   7677:   printf("# Scales (for hessian or gradient estimation)\n");
                   7678:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7679:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7680:   for(i=1; i <=nlstate; i++){
                   7681:     jj=0;
                   7682:     for(j=1; j <=nlstate+ndeath; j++){
                   7683:       if(j==i) continue;
                   7684:       jj++;
                   7685:       fprintf(ficparo,"%1d%1d",i,j);
                   7686:       printf("%1d%1d",i,j);
                   7687:       fflush(stdout);
                   7688:       for(k=1; k<=ncovmodel;k++){
                   7689:        /*      printf(" %le",delti3[i][j][k]); */
                   7690:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7691:        printf(" 0.");
                   7692:        fprintf(ficparo," 0.");
                   7693:       }
                   7694:       numlinepar++;
                   7695:       printf("\n");
                   7696:       fprintf(ficparo,"\n");
                   7697:     }
                   7698:   }
                   7699:   printf("# Covariance matrix\n");
                   7700: /* # 121 Var(a12)\n\ */
                   7701: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7702: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7703: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7704: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7705: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7706: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7707: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7708:   fflush(stdout);
                   7709:   fprintf(ficparo,"# Covariance matrix\n");
                   7710:   /* # 121 Var(a12)\n\ */
                   7711:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7712:   /* #   ...\n\ */
                   7713:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7714:   
                   7715:   for(itimes=1;itimes<=2;itimes++){
                   7716:     jj=0;
                   7717:     for(i=1; i <=nlstate; i++){
                   7718:       for(j=1; j <=nlstate+ndeath; j++){
                   7719:        if(j==i) continue;
                   7720:        for(k=1; k<=ncovmodel;k++){
                   7721:          jj++;
                   7722:          ca[0]= k+'a'-1;ca[1]='\0';
                   7723:          if(itimes==1){
                   7724:            printf("#%1d%1d%d",i,j,k);
                   7725:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7726:          }else{
                   7727:            printf("%1d%1d%d",i,j,k);
                   7728:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7729:            /*  printf(" %.5le",matcov[i][j]); */
                   7730:          }
                   7731:          ll=0;
                   7732:          for(li=1;li <=nlstate; li++){
                   7733:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7734:              if(lj==li) continue;
                   7735:              for(lk=1;lk<=ncovmodel;lk++){
                   7736:                ll++;
                   7737:                if(ll<=jj){
                   7738:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7739:                  if(ll<jj){
                   7740:                    if(itimes==1){
                   7741:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7742:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7743:                    }else{
                   7744:                      printf(" 0.");
                   7745:                      fprintf(ficparo," 0.");
                   7746:                    }
                   7747:                  }else{
                   7748:                    if(itimes==1){
                   7749:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7750:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7751:                    }else{
                   7752:                      printf(" 0.");
                   7753:                      fprintf(ficparo," 0.");
                   7754:                    }
                   7755:                  }
                   7756:                }
                   7757:              } /* end lk */
                   7758:            } /* end lj */
                   7759:          } /* end li */
                   7760:          printf("\n");
                   7761:          fprintf(ficparo,"\n");
                   7762:          numlinepar++;
                   7763:        } /* end k*/
                   7764:       } /*end j */
                   7765:     } /* end i */
                   7766:   } /* end itimes */
                   7767: 
                   7768: } /* end of prwizard */
                   7769: /******************* Gompertz Likelihood ******************************/
                   7770: double gompertz(double x[])
                   7771: { 
                   7772:   double A,B,L=0.0,sump=0.,num=0.;
                   7773:   int i,n=0; /* n is the size of the sample */
                   7774: 
1.220     brouard  7775:   for (i=1;i<=imx ; i++) {
1.126     brouard  7776:     sump=sump+weight[i];
                   7777:     /*    sump=sump+1;*/
                   7778:     num=num+1;
                   7779:   }
                   7780:  
                   7781:  
                   7782:   /* for (i=0; i<=imx; i++) 
                   7783:      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]);*/
                   7784: 
                   7785:   for (i=1;i<=imx ; i++)
                   7786:     {
                   7787:       if (cens[i] == 1 && wav[i]>1)
                   7788:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7789:       
                   7790:       if (cens[i] == 0 && wav[i]>1)
                   7791:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7792:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7793:       
                   7794:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7795:       if (wav[i] > 1 ) { /* ??? */
                   7796:        L=L+A*weight[i];
                   7797:        /*      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]);*/
                   7798:       }
                   7799:     }
                   7800: 
                   7801:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7802:  
                   7803:   return -2*L*num/sump;
                   7804: }
                   7805: 
1.136     brouard  7806: #ifdef GSL
                   7807: /******************* Gompertz_f Likelihood ******************************/
                   7808: double gompertz_f(const gsl_vector *v, void *params)
                   7809: { 
                   7810:   double A,B,LL=0.0,sump=0.,num=0.;
                   7811:   double *x= (double *) v->data;
                   7812:   int i,n=0; /* n is the size of the sample */
                   7813: 
                   7814:   for (i=0;i<=imx-1 ; i++) {
                   7815:     sump=sump+weight[i];
                   7816:     /*    sump=sump+1;*/
                   7817:     num=num+1;
                   7818:   }
                   7819:  
                   7820:  
                   7821:   /* for (i=0; i<=imx; i++) 
                   7822:      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]);*/
                   7823:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7824:   for (i=1;i<=imx ; i++)
                   7825:     {
                   7826:       if (cens[i] == 1 && wav[i]>1)
                   7827:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7828:       
                   7829:       if (cens[i] == 0 && wav[i]>1)
                   7830:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7831:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7832:       
                   7833:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7834:       if (wav[i] > 1 ) { /* ??? */
                   7835:        LL=LL+A*weight[i];
                   7836:        /*      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]);*/
                   7837:       }
                   7838:     }
                   7839: 
                   7840:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7841:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7842:  
                   7843:   return -2*LL*num/sump;
                   7844: }
                   7845: #endif
                   7846: 
1.126     brouard  7847: /******************* Printing html file ***********/
1.201     brouard  7848: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7849:                  int lastpass, int stepm, int weightopt, char model[],\
                   7850:                  int imx,  double p[],double **matcov,double agemortsup){
                   7851:   int i,k;
                   7852: 
                   7853:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7854:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7855:   for (i=1;i<=2;i++) 
                   7856:     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  7857:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7858:   fprintf(fichtm,"</ul>");
                   7859: 
                   7860: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7861: 
                   7862:  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>");
                   7863: 
                   7864:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7865:    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]);
                   7866: 
                   7867:  
                   7868:   fflush(fichtm);
                   7869: }
                   7870: 
                   7871: /******************* Gnuplot file **************/
1.201     brouard  7872: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7873: 
                   7874:   char dirfileres[132],optfileres[132];
1.164     brouard  7875: 
1.126     brouard  7876:   int ng;
                   7877: 
                   7878: 
                   7879:   /*#ifdef windows */
                   7880:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7881:     /*#endif */
                   7882: 
                   7883: 
                   7884:   strcpy(dirfileres,optionfilefiname);
                   7885:   strcpy(optfileres,"vpl");
1.199     brouard  7886:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7887:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7888:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7889:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7890:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7891: 
                   7892: } 
                   7893: 
1.136     brouard  7894: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7895: {
1.126     brouard  7896: 
1.136     brouard  7897:   /*-------- data file ----------*/
                   7898:   FILE *fic;
                   7899:   char dummy[]="                         ";
1.240     brouard  7900:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  7901:   int lstra;
1.136     brouard  7902:   int linei, month, year,iout;
                   7903:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7904:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7905:   char *stratrunc;
1.223     brouard  7906: 
1.240     brouard  7907:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   7908:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  7909: 
1.240     brouard  7910:   for(v=1; v <=ncovcol;v++){
                   7911:     DummyV[v]=0;
                   7912:     FixedV[v]=0;
                   7913:   }
                   7914:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   7915:     DummyV[v]=1;
                   7916:     FixedV[v]=0;
                   7917:   }
                   7918:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   7919:     DummyV[v]=0;
                   7920:     FixedV[v]=1;
                   7921:   }
                   7922:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7923:     DummyV[v]=1;
                   7924:     FixedV[v]=1;
                   7925:   }
                   7926:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7927:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   7928:     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]);
                   7929:   }
1.126     brouard  7930: 
1.136     brouard  7931:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7932:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7933:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7934:   }
1.126     brouard  7935: 
1.136     brouard  7936:   i=1;
                   7937:   linei=0;
                   7938:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7939:     linei=linei+1;
                   7940:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7941:       if(line[j] == '\t')
                   7942:        line[j] = ' ';
                   7943:     }
                   7944:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7945:       ;
                   7946:     };
                   7947:     line[j+1]=0;  /* Trims blanks at end of line */
                   7948:     if(line[0]=='#'){
                   7949:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7950:       printf("Comment line\n%s\n",line);
                   7951:       continue;
                   7952:     }
                   7953:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7954:     strcpy(line, linetmp);
1.223     brouard  7955:     
                   7956:     /* Loops on waves */
                   7957:     for (j=maxwav;j>=1;j--){
                   7958:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  7959:        cutv(stra, strb, line, ' '); 
                   7960:        if(strb[0]=='.') { /* Missing value */
                   7961:          lval=-1;
                   7962:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   7963:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   7964:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   7965:            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);
                   7966:            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);
                   7967:            return 1;
                   7968:          }
                   7969:        }else{
                   7970:          errno=0;
                   7971:          /* what_kind_of_number(strb); */
                   7972:          dval=strtod(strb,&endptr); 
                   7973:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7974:          /* if(strb != endptr && *endptr == '\0') */
                   7975:          /*    dval=dlval; */
                   7976:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7977:          if( strb[0]=='\0' || (*endptr != '\0')){
                   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. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
                   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. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
                   7980:            return 1;
                   7981:          }
                   7982:          cotqvar[j][iv][i]=dval; 
                   7983:          cotvar[j][ntv+iv][i]=dval; 
                   7984:        }
                   7985:        strcpy(line,stra);
1.223     brouard  7986:       }/* end loop ntqv */
1.225     brouard  7987:       
1.223     brouard  7988:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  7989:        cutv(stra, strb, line, ' '); 
                   7990:        if(strb[0]=='.') { /* Missing value */
                   7991:          lval=-1;
                   7992:        }else{
                   7993:          errno=0;
                   7994:          lval=strtol(strb,&endptr,10); 
                   7995:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7996:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7997:            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);
                   7998:            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);
                   7999:            return 1;
                   8000:          }
                   8001:        }
                   8002:        if(lval <-1 || lval >1){
                   8003:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8004:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8005:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8006:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8007:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8008:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8009:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8010:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8011:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8012:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8013:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8014:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8015:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8016:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8017:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8018:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8019:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8020:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8021:          return 1;
                   8022:        }
                   8023:        cotvar[j][iv][i]=(double)(lval);
                   8024:        strcpy(line,stra);
1.223     brouard  8025:       }/* end loop ntv */
1.225     brouard  8026:       
1.223     brouard  8027:       /* Statuses  at wave */
1.137     brouard  8028:       cutv(stra, strb, line, ' '); 
1.223     brouard  8029:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8030:        lval=-1;
1.136     brouard  8031:       }else{
1.238     brouard  8032:        errno=0;
                   8033:        lval=strtol(strb,&endptr,10); 
                   8034:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8035:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8036:          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);
                   8037:          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);
                   8038:          return 1;
                   8039:        }
1.136     brouard  8040:       }
1.225     brouard  8041:       
1.136     brouard  8042:       s[j][i]=lval;
1.225     brouard  8043:       
1.223     brouard  8044:       /* Date of Interview */
1.136     brouard  8045:       strcpy(line,stra);
                   8046:       cutv(stra, strb,line,' ');
1.169     brouard  8047:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8048:       }
1.169     brouard  8049:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8050:        month=99;
                   8051:        year=9999;
1.136     brouard  8052:       }else{
1.225     brouard  8053:        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);
                   8054:        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);
                   8055:        return 1;
1.136     brouard  8056:       }
                   8057:       anint[j][i]= (double) year; 
                   8058:       mint[j][i]= (double)month; 
                   8059:       strcpy(line,stra);
1.223     brouard  8060:     } /* End loop on waves */
1.225     brouard  8061:     
1.223     brouard  8062:     /* Date of death */
1.136     brouard  8063:     cutv(stra, strb,line,' '); 
1.169     brouard  8064:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8065:     }
1.169     brouard  8066:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8067:       month=99;
                   8068:       year=9999;
                   8069:     }else{
1.141     brouard  8070:       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  8071:       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);
                   8072:       return 1;
1.136     brouard  8073:     }
                   8074:     andc[i]=(double) year; 
                   8075:     moisdc[i]=(double) month; 
                   8076:     strcpy(line,stra);
                   8077:     
1.223     brouard  8078:     /* Date of birth */
1.136     brouard  8079:     cutv(stra, strb,line,' '); 
1.169     brouard  8080:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8081:     }
1.169     brouard  8082:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8083:       month=99;
                   8084:       year=9999;
                   8085:     }else{
1.141     brouard  8086:       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);
                   8087:       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  8088:       return 1;
1.136     brouard  8089:     }
                   8090:     if (year==9999) {
1.141     brouard  8091:       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);
                   8092:       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  8093:       return 1;
                   8094:       
1.136     brouard  8095:     }
                   8096:     annais[i]=(double)(year);
                   8097:     moisnais[i]=(double)(month); 
                   8098:     strcpy(line,stra);
1.225     brouard  8099:     
1.223     brouard  8100:     /* Sample weight */
1.136     brouard  8101:     cutv(stra, strb,line,' '); 
                   8102:     errno=0;
                   8103:     dval=strtod(strb,&endptr); 
                   8104:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8105:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8106:       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  8107:       fflush(ficlog);
                   8108:       return 1;
                   8109:     }
                   8110:     weight[i]=dval; 
                   8111:     strcpy(line,stra);
1.225     brouard  8112:     
1.223     brouard  8113:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8114:       cutv(stra, strb, line, ' '); 
                   8115:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8116:        lval=-1;
1.223     brouard  8117:       }else{
1.225     brouard  8118:        errno=0;
                   8119:        /* what_kind_of_number(strb); */
                   8120:        dval=strtod(strb,&endptr);
                   8121:        /* if(strb != endptr && *endptr == '\0') */
                   8122:        /*   dval=dlval; */
                   8123:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8124:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8125:          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);
                   8126:          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);
                   8127:          return 1;
                   8128:        }
                   8129:        coqvar[iv][i]=dval; 
1.226     brouard  8130:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8131:       }
                   8132:       strcpy(line,stra);
                   8133:     }/* end loop nqv */
1.136     brouard  8134:     
1.223     brouard  8135:     /* Covariate values */
1.136     brouard  8136:     for (j=ncovcol;j>=1;j--){
                   8137:       cutv(stra, strb,line,' '); 
1.223     brouard  8138:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8139:        lval=-1;
1.136     brouard  8140:       }else{
1.225     brouard  8141:        errno=0;
                   8142:        lval=strtol(strb,&endptr,10); 
                   8143:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8144:          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);
                   8145:          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);
                   8146:          return 1;
                   8147:        }
1.136     brouard  8148:       }
                   8149:       if(lval <-1 || lval >1){
1.225     brouard  8150:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8151:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8152:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8153:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8154:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8155:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8156:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8157:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8158:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8159:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8160:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8161:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8162:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8163:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8164:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8165:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8166:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8167:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8168:        return 1;
1.136     brouard  8169:       }
                   8170:       covar[j][i]=(double)(lval);
                   8171:       strcpy(line,stra);
                   8172:     }  
                   8173:     lstra=strlen(stra);
1.225     brouard  8174:     
1.136     brouard  8175:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8176:       stratrunc = &(stra[lstra-9]);
                   8177:       num[i]=atol(stratrunc);
                   8178:     }
                   8179:     else
                   8180:       num[i]=atol(stra);
                   8181:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8182:       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;}*/
                   8183:     
                   8184:     i=i+1;
                   8185:   } /* End loop reading  data */
1.225     brouard  8186:   
1.136     brouard  8187:   *imax=i-1; /* Number of individuals */
                   8188:   fclose(fic);
1.225     brouard  8189:   
1.136     brouard  8190:   return (0);
1.164     brouard  8191:   /* endread: */
1.225     brouard  8192:   printf("Exiting readdata: ");
                   8193:   fclose(fic);
                   8194:   return (1);
1.223     brouard  8195: }
1.126     brouard  8196: 
1.234     brouard  8197: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8198:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8199:   while (*p2 == ' ')
1.234     brouard  8200:     p2++; 
                   8201:   /* while ((*p1++ = *p2++) !=0) */
                   8202:   /*   ; */
                   8203:   /* do */
                   8204:   /*   while (*p2 == ' ') */
                   8205:   /*     p2++; */
                   8206:   /* while (*p1++ == *p2++); */
                   8207:   *stri=p2; 
1.145     brouard  8208: }
                   8209: 
1.235     brouard  8210: int decoderesult ( char resultline[], int nres)
1.230     brouard  8211: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8212: {
1.235     brouard  8213:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8214:   char resultsav[MAXLINE];
1.234     brouard  8215:   int resultmodel[MAXLINE];
                   8216:   int modelresult[MAXLINE];
1.230     brouard  8217:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8218: 
1.234     brouard  8219:   removefirstspace(&resultline);
1.233     brouard  8220:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8221: 
                   8222:   if (strstr(resultline,"v") !=0){
                   8223:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8224:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8225:     return 1;
                   8226:   }
                   8227:   trimbb(resultsav, resultline);
                   8228:   if (strlen(resultsav) >1){
                   8229:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8230:   }
1.234     brouard  8231:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8232:     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);
                   8233:     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);
                   8234:   }
                   8235:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8236:     if(nbocc(resultsav,'=') >1){
                   8237:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8238:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8239:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8240:     }else
                   8241:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8242:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8243:     
1.230     brouard  8244:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8245:     Tvarsel[k]=atoi(strc);
                   8246:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8247:     /* cptcovsel++;     */
                   8248:     if (nbocc(stra,'=') >0)
                   8249:       strcpy(resultsav,stra); /* and analyzes it */
                   8250:   }
1.235     brouard  8251:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8252:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8253:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8254:       match=0;
1.236     brouard  8255:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8256:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8257:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8258:          match=1;
                   8259:          break;
                   8260:        }
                   8261:       }
                   8262:       if(match == 0){
                   8263:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8264:       }
                   8265:     }
                   8266:   }
1.235     brouard  8267:   /* Checking for missing or useless values in comparison of current model needs */
                   8268:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8269:     match=0;
1.235     brouard  8270:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8271:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8272:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8273:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8274:          ++match;
                   8275:        }
                   8276:       }
                   8277:     }
                   8278:     if(match == 0){
                   8279:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8280:     }else if(match > 1){
                   8281:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8282:     }
                   8283:   }
1.235     brouard  8284:       
1.234     brouard  8285:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8286:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8287:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8288:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8289:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8290:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8291:   /*    1 0 0 0 */
                   8292:   /*    2 1 0 0 */
                   8293:   /*    3 0 1 0 */ 
                   8294:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8295:   /*    5 0 0 1 */
                   8296:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8297:   /*    7 0 1 1 */
                   8298:   /*    8 1 1 1 */
1.237     brouard  8299:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8300:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8301:   /* V5*age V5 known which value for nres?  */
                   8302:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8303:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8304:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8305:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8306:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8307:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8308:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8309:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8310:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8311:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8312:       k4++;;
                   8313:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8314:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8315:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8316:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8317:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8318:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8319:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8320:       k4q++;;
                   8321:     }
                   8322:   }
1.234     brouard  8323:   
1.235     brouard  8324:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8325:   return (0);
                   8326: }
1.235     brouard  8327: 
1.230     brouard  8328: int decodemodel( char model[], int lastobs)
                   8329:  /**< This routine decodes the model and returns:
1.224     brouard  8330:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8331:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8332:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8333:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8334:        * - cptcovage number of covariates with age*products =2
                   8335:        * - cptcovs number of simple covariates
                   8336:        * - 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
                   8337:        *     which is a new column after the 9 (ncovcol) variables. 
                   8338:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8339:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8340:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8341:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8342:        */
1.136     brouard  8343: {
1.238     brouard  8344:   int i, j, k, ks, v;
1.227     brouard  8345:   int  j1, k1, k2, k3, k4;
1.136     brouard  8346:   char modelsav[80];
1.145     brouard  8347:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8348:   char *strpt;
1.136     brouard  8349: 
1.145     brouard  8350:   /*removespace(model);*/
1.136     brouard  8351:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8352:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8353:     if (strstr(model,"AGE") !=0){
1.192     brouard  8354:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8355:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8356:       return 1;
                   8357:     }
1.141     brouard  8358:     if (strstr(model,"v") !=0){
                   8359:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8360:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8361:       return 1;
                   8362:     }
1.187     brouard  8363:     strcpy(modelsav,model); 
                   8364:     if ((strpt=strstr(model,"age*age")) !=0){
                   8365:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8366:       if(strpt != model){
1.234     brouard  8367:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8368:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8369:  corresponding column of parameters.\n",model);
1.234     brouard  8370:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8371:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8372:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8373:        return 1;
1.225     brouard  8374:       }
1.187     brouard  8375:       nagesqr=1;
                   8376:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8377:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8378:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8379:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8380:       else 
1.234     brouard  8381:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8382:     }else
                   8383:       nagesqr=0;
                   8384:     if (strlen(modelsav) >1){
                   8385:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8386:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8387:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8388:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8389:                     * cst, age and age*age 
                   8390:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8391:       /* including age products which are counted in cptcovage.
                   8392:        * but the covariates which are products must be treated 
                   8393:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8394:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8395:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8396:       
                   8397:       
1.187     brouard  8398:       /*   Design
                   8399:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8400:        *  <          ncovcol=8                >
                   8401:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8402:        *   k=  1    2      3       4     5       6      7        8
                   8403:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8404:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8405:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8406:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8407:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8408:        *  Tage[++cptcovage]=k
                   8409:        *       if products, new covar are created after ncovcol with k1
                   8410:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8411:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8412:        *  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
                   8413:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8414:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8415:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8416:        *  <          ncovcol=8                >
                   8417:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8418:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8419:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8420:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8421:        * p Tprod[1]@2={                         6, 5}
                   8422:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8423:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8424:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8425:        *How to reorganize?
                   8426:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8427:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8428:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8429:        * Struct []
                   8430:        */
1.225     brouard  8431:       
1.187     brouard  8432:       /* This loop fills the array Tvar from the string 'model'.*/
                   8433:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8434:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8435:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8436:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8437:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8438:       /*       k=1 Tvar[1]=2 (from V2) */
                   8439:       /*       k=5 Tvar[5] */
                   8440:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8441:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8442:       /*       } */
1.198     brouard  8443:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8444:       /*
                   8445:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8446:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8447:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8448:       }
1.187     brouard  8449:       cptcovage=0;
                   8450:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8451:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8452:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8453:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8454:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8455:        /*scanf("%d",i);*/
                   8456:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8457:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8458:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8459:            /* covar is not filled and then is empty */
                   8460:            cptcovprod--;
                   8461:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8462:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8463:            Typevar[k]=1;  /* 1 for age product */
                   8464:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8465:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8466:            /*printf("stre=%s ", stre);*/
                   8467:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8468:            cptcovprod--;
                   8469:            cutl(stre,strb,strc,'V');
                   8470:            Tvar[k]=atoi(stre);
                   8471:            Typevar[k]=1;  /* 1 for age product */
                   8472:            cptcovage++;
                   8473:            Tage[cptcovage]=k;
                   8474:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8475:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8476:            cptcovn++;
                   8477:            cptcovprodnoage++;k1++;
                   8478:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8479:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8480:                                                because this model-covariate is a construction we invent a new column
                   8481:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8482:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8483:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8484:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8485:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8486:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8487:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8488:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8489:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8490:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8491:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8492:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8493:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8494:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8495:            for (i=1; i<=lastobs;i++){
                   8496:              /* Computes the new covariate which is a product of
                   8497:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8498:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8499:            }
                   8500:          } /* End age is not in the model */
                   8501:        } /* End if model includes a product */
                   8502:        else { /* no more sum */
                   8503:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8504:          /*  scanf("%d",i);*/
                   8505:          cutl(strd,strc,strb,'V');
                   8506:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8507:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8508:          Tvar[k]=atoi(strd);
                   8509:          Typevar[k]=0;  /* 0 for simple covariates */
                   8510:        }
                   8511:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8512:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8513:                                  scanf("%d",i);*/
1.187     brouard  8514:       } /* end of loop + on total covariates */
                   8515:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8516:   } /* end if strlen(model == 0) */
1.136     brouard  8517:   
                   8518:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8519:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8520:   
1.136     brouard  8521:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8522:      printf("cptcovprod=%d ", cptcovprod);
                   8523:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8524:      scanf("%d ",i);*/
                   8525: 
                   8526: 
1.230     brouard  8527: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8528:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8529: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8530:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8531:    k =           1    2   3     4       5       6      7      8        9
                   8532:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8533:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8534:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8535:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8536:          Tmodelind[combination of covar]=k;
1.225     brouard  8537: */  
                   8538: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8539:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8540:   /* 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  8541:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8542:   printf("Model=%s\n\
                   8543: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8544: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8545: 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);
                   8546:   fprintf(ficlog,"Model=%s\n\
                   8547: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8548: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8549: 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  8550:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8551:   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 */
                   8552:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8553:       Fixed[k]= 0;
                   8554:       Dummy[k]= 0;
1.225     brouard  8555:       ncoveff++;
1.232     brouard  8556:       ncovf++;
1.234     brouard  8557:       nsd++;
                   8558:       modell[k].maintype= FTYPE;
                   8559:       TvarsD[nsd]=Tvar[k];
                   8560:       TvarsDind[nsd]=k;
                   8561:       TvarF[ncovf]=Tvar[k];
                   8562:       TvarFind[ncovf]=k;
                   8563:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8564:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8565:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8566:       Fixed[k]= 0;
                   8567:       Dummy[k]= 0;
                   8568:       ncoveff++;
                   8569:       ncovf++;
                   8570:       modell[k].maintype= FTYPE;
                   8571:       TvarF[ncovf]=Tvar[k];
                   8572:       TvarFind[ncovf]=k;
1.230     brouard  8573:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8574:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8575:     }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  8576:       Fixed[k]= 0;
                   8577:       Dummy[k]= 1;
1.230     brouard  8578:       nqfveff++;
1.234     brouard  8579:       modell[k].maintype= FTYPE;
                   8580:       modell[k].subtype= FQ;
                   8581:       nsq++;
                   8582:       TvarsQ[nsq]=Tvar[k];
                   8583:       TvarsQind[nsq]=k;
1.232     brouard  8584:       ncovf++;
1.234     brouard  8585:       TvarF[ncovf]=Tvar[k];
                   8586:       TvarFind[ncovf]=k;
1.231     brouard  8587:       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  8588:       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  8589:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8590:       Fixed[k]= 1;
                   8591:       Dummy[k]= 0;
1.225     brouard  8592:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8593:       modell[k].maintype= VTYPE;
                   8594:       modell[k].subtype= VD;
                   8595:       nsd++;
                   8596:       TvarsD[nsd]=Tvar[k];
                   8597:       TvarsDind[nsd]=k;
                   8598:       ncovv++; /* Only simple time varying variables */
                   8599:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8600:       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  8601:       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 */
                   8602:       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  8603:       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);
                   8604:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8605:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8606:       Fixed[k]= 1;
                   8607:       Dummy[k]= 1;
                   8608:       nqtveff++;
                   8609:       modell[k].maintype= VTYPE;
                   8610:       modell[k].subtype= VQ;
                   8611:       ncovv++; /* Only simple time varying variables */
                   8612:       nsq++;
                   8613:       TvarsQ[nsq]=Tvar[k];
                   8614:       TvarsQind[nsq]=k;
                   8615:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8616:       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  8617:       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 */
                   8618:       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  8619:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8620:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8621:       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  8622:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8623:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8624:       ncova++;
                   8625:       TvarA[ncova]=Tvar[k];
                   8626:       TvarAind[ncova]=k;
1.231     brouard  8627:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8628:        Fixed[k]= 2;
                   8629:        Dummy[k]= 2;
                   8630:        modell[k].maintype= ATYPE;
                   8631:        modell[k].subtype= APFD;
                   8632:        /* ncoveff++; */
1.227     brouard  8633:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8634:        Fixed[k]= 2;
                   8635:        Dummy[k]= 3;
                   8636:        modell[k].maintype= ATYPE;
                   8637:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8638:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8639:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8640:        Fixed[k]= 3;
                   8641:        Dummy[k]= 2;
                   8642:        modell[k].maintype= ATYPE;
                   8643:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8644:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8645:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8646:        Fixed[k]= 3;
                   8647:        Dummy[k]= 3;
                   8648:        modell[k].maintype= ATYPE;
                   8649:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8650:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8651:       }
                   8652:     }else if (Typevar[k] == 2) {  /* product without age */
                   8653:       k1=Tposprod[k];
                   8654:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8655:        if(Tvard[k1][2] <=ncovcol){
                   8656:          Fixed[k]= 1;
                   8657:          Dummy[k]= 0;
                   8658:          modell[k].maintype= FTYPE;
                   8659:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8660:          ncovf++; /* Fixed variables without age */
                   8661:          TvarF[ncovf]=Tvar[k];
                   8662:          TvarFind[ncovf]=k;
                   8663:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8664:          Fixed[k]= 0;  /* or 2 ?*/
                   8665:          Dummy[k]= 1;
                   8666:          modell[k].maintype= FTYPE;
                   8667:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8668:          ncovf++; /* Varying variables without age */
                   8669:          TvarF[ncovf]=Tvar[k];
                   8670:          TvarFind[ncovf]=k;
                   8671:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8672:          Fixed[k]= 1;
                   8673:          Dummy[k]= 0;
                   8674:          modell[k].maintype= VTYPE;
                   8675:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8676:          ncovv++; /* Varying variables without age */
                   8677:          TvarV[ncovv]=Tvar[k];
                   8678:          TvarVind[ncovv]=k;
                   8679:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8680:          Fixed[k]= 1;
                   8681:          Dummy[k]= 1;
                   8682:          modell[k].maintype= VTYPE;
                   8683:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8684:          ncovv++; /* Varying variables without age */
                   8685:          TvarV[ncovv]=Tvar[k];
                   8686:          TvarVind[ncovv]=k;
                   8687:        }
1.227     brouard  8688:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8689:        if(Tvard[k1][2] <=ncovcol){
                   8690:          Fixed[k]= 0;  /* or 2 ?*/
                   8691:          Dummy[k]= 1;
                   8692:          modell[k].maintype= FTYPE;
                   8693:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8694:          ncovf++; /* Fixed variables without age */
                   8695:          TvarF[ncovf]=Tvar[k];
                   8696:          TvarFind[ncovf]=k;
                   8697:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8698:          Fixed[k]= 1;
                   8699:          Dummy[k]= 1;
                   8700:          modell[k].maintype= VTYPE;
                   8701:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8702:          ncovv++; /* Varying variables without age */
                   8703:          TvarV[ncovv]=Tvar[k];
                   8704:          TvarVind[ncovv]=k;
                   8705:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8706:          Fixed[k]= 1;
                   8707:          Dummy[k]= 1;
                   8708:          modell[k].maintype= VTYPE;
                   8709:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8710:          ncovv++; /* Varying variables without age */
                   8711:          TvarV[ncovv]=Tvar[k];
                   8712:          TvarVind[ncovv]=k;
                   8713:          ncovv++; /* Varying variables without age */
                   8714:          TvarV[ncovv]=Tvar[k];
                   8715:          TvarVind[ncovv]=k;
                   8716:        }
1.227     brouard  8717:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8718:        if(Tvard[k1][2] <=ncovcol){
                   8719:          Fixed[k]= 1;
                   8720:          Dummy[k]= 1;
                   8721:          modell[k].maintype= VTYPE;
                   8722:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8723:          ncovv++; /* Varying variables without age */
                   8724:          TvarV[ncovv]=Tvar[k];
                   8725:          TvarVind[ncovv]=k;
                   8726:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8727:          Fixed[k]= 1;
                   8728:          Dummy[k]= 1;
                   8729:          modell[k].maintype= VTYPE;
                   8730:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8731:          ncovv++; /* Varying variables without age */
                   8732:          TvarV[ncovv]=Tvar[k];
                   8733:          TvarVind[ncovv]=k;
                   8734:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8735:          Fixed[k]= 1;
                   8736:          Dummy[k]= 0;
                   8737:          modell[k].maintype= VTYPE;
                   8738:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8739:          ncovv++; /* Varying variables without age */
                   8740:          TvarV[ncovv]=Tvar[k];
                   8741:          TvarVind[ncovv]=k;
                   8742:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8743:          Fixed[k]= 1;
                   8744:          Dummy[k]= 1;
                   8745:          modell[k].maintype= VTYPE;
                   8746:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8747:          ncovv++; /* Varying variables without age */
                   8748:          TvarV[ncovv]=Tvar[k];
                   8749:          TvarVind[ncovv]=k;
                   8750:        }
1.227     brouard  8751:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8752:        if(Tvard[k1][2] <=ncovcol){
                   8753:          Fixed[k]= 1;
                   8754:          Dummy[k]= 1;
                   8755:          modell[k].maintype= VTYPE;
                   8756:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8757:          ncovv++; /* Varying variables without age */
                   8758:          TvarV[ncovv]=Tvar[k];
                   8759:          TvarVind[ncovv]=k;
                   8760:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8761:          Fixed[k]= 1;
                   8762:          Dummy[k]= 1;
                   8763:          modell[k].maintype= VTYPE;
                   8764:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8765:          ncovv++; /* Varying variables without age */
                   8766:          TvarV[ncovv]=Tvar[k];
                   8767:          TvarVind[ncovv]=k;
                   8768:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8769:          Fixed[k]= 1;
                   8770:          Dummy[k]= 1;
                   8771:          modell[k].maintype= VTYPE;
                   8772:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8773:          ncovv++; /* Varying variables without age */
                   8774:          TvarV[ncovv]=Tvar[k];
                   8775:          TvarVind[ncovv]=k;
                   8776:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8777:          Fixed[k]= 1;
                   8778:          Dummy[k]= 1;
                   8779:          modell[k].maintype= VTYPE;
                   8780:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8781:          ncovv++; /* Varying variables without age */
                   8782:          TvarV[ncovv]=Tvar[k];
                   8783:          TvarVind[ncovv]=k;
                   8784:        }
1.227     brouard  8785:       }else{
1.240     brouard  8786:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8787:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8788:       } /*end k1*/
1.225     brouard  8789:     }else{
1.226     brouard  8790:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8791:       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  8792:     }
1.227     brouard  8793:     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  8794:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8795:     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]);
                   8796:   }
                   8797:   /* Searching for doublons in the model */
                   8798:   for(k1=1; k1<= cptcovt;k1++){
                   8799:     for(k2=1; k2 <k1;k2++){
                   8800:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8801:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8802:          if(Tvar[k1]==Tvar[k2]){
                   8803:            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]]);
                   8804:            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);
                   8805:            return(1);
                   8806:          }
                   8807:        }else if (Typevar[k1] ==2){
                   8808:          k3=Tposprod[k1];
                   8809:          k4=Tposprod[k2];
                   8810:          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])) ){
                   8811:            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]]);
                   8812:            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);
                   8813:            return(1);
                   8814:          }
                   8815:        }
1.227     brouard  8816:       }
                   8817:     }
1.225     brouard  8818:   }
                   8819:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8820:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8821:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8822:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8823:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8824:   /*endread:*/
1.225     brouard  8825:   printf("Exiting decodemodel: ");
                   8826:   return (1);
1.136     brouard  8827: }
                   8828: 
1.169     brouard  8829: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8830: {
                   8831:   int i, m;
1.218     brouard  8832:   int firstone=0;
                   8833:   
1.136     brouard  8834:   for (i=1; i<=imx; i++) {
                   8835:     for(m=2; (m<= maxwav); m++) {
                   8836:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8837:        anint[m][i]=9999;
1.216     brouard  8838:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8839:          s[m][i]=-1;
1.136     brouard  8840:       }
                   8841:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8842:        *nberr = *nberr + 1;
1.218     brouard  8843:        if(firstone == 0){
                   8844:          firstone=1;
                   8845:        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);
                   8846:        }
                   8847:        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  8848:        s[m][i]=-1;
                   8849:       }
                   8850:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8851:        (*nberr)++;
1.136     brouard  8852:        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]); 
                   8853:        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]); 
                   8854:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8855:       }
                   8856:     }
                   8857:   }
                   8858: 
                   8859:   for (i=1; i<=imx; i++)  {
                   8860:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8861:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8862:       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  8863:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8864:          if(agedc[i]>0){
                   8865:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8866:              agev[m][i]=agedc[i];
1.214     brouard  8867:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8868:            }else {
1.136     brouard  8869:              if ((int)andc[i]!=9999){
                   8870:                nbwarn++;
                   8871:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8872:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8873:                agev[m][i]=-1;
                   8874:              }
                   8875:            }
1.169     brouard  8876:          } /* agedc > 0 */
1.214     brouard  8877:        } /* end if */
1.136     brouard  8878:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8879:                                 years but with the precision of a month */
                   8880:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8881:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8882:            agev[m][i]=1;
                   8883:          else if(agev[m][i] < *agemin){ 
                   8884:            *agemin=agev[m][i];
                   8885:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8886:          }
                   8887:          else if(agev[m][i] >*agemax){
                   8888:            *agemax=agev[m][i];
1.156     brouard  8889:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8890:          }
                   8891:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8892:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8893:        } /* en if 9*/
1.136     brouard  8894:        else { /* =9 */
1.214     brouard  8895:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8896:          agev[m][i]=1;
                   8897:          s[m][i]=-1;
                   8898:        }
                   8899:       }
1.214     brouard  8900:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8901:        agev[m][i]=1;
1.214     brouard  8902:       else{
                   8903:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8904:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8905:        agev[m][i]=0;
                   8906:       }
                   8907:     } /* End for lastpass */
                   8908:   }
1.136     brouard  8909:     
                   8910:   for (i=1; i<=imx; i++)  {
                   8911:     for(m=firstpass; (m<=lastpass); m++){
                   8912:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8913:        (*nberr)++;
1.136     brouard  8914:        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);     
                   8915:        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);     
                   8916:        return 1;
                   8917:       }
                   8918:     }
                   8919:   }
                   8920: 
                   8921:   /*for (i=1; i<=imx; i++){
                   8922:   for (m=firstpass; (m<lastpass); m++){
                   8923:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8924: }
                   8925: 
                   8926: }*/
                   8927: 
                   8928: 
1.139     brouard  8929:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8930:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8931: 
                   8932:   return (0);
1.164     brouard  8933:  /* endread:*/
1.136     brouard  8934:     printf("Exiting calandcheckages: ");
                   8935:     return (1);
                   8936: }
                   8937: 
1.172     brouard  8938: #if defined(_MSC_VER)
                   8939: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8940: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8941: //#include "stdafx.h"
                   8942: //#include <stdio.h>
                   8943: //#include <tchar.h>
                   8944: //#include <windows.h>
                   8945: //#include <iostream>
                   8946: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8947: 
                   8948: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8949: 
                   8950: BOOL IsWow64()
                   8951: {
                   8952:        BOOL bIsWow64 = FALSE;
                   8953: 
                   8954:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8955:        //  (HANDLE, PBOOL);
                   8956: 
                   8957:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8958: 
                   8959:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8960:        const char funcName[] = "IsWow64Process";
                   8961:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8962:                GetProcAddress(module, funcName);
                   8963: 
                   8964:        if (NULL != fnIsWow64Process)
                   8965:        {
                   8966:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8967:                        &bIsWow64))
                   8968:                        //throw std::exception("Unknown error");
                   8969:                        printf("Unknown error\n");
                   8970:        }
                   8971:        return bIsWow64 != FALSE;
                   8972: }
                   8973: #endif
1.177     brouard  8974: 
1.191     brouard  8975: void syscompilerinfo(int logged)
1.167     brouard  8976:  {
                   8977:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8978:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8979:    /* /GS /W3 /Gy
                   8980:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8981:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8982:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8983:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8984:    */ 
                   8985:    /* 64 bits */
1.185     brouard  8986:    /*
                   8987:      /GS /W3 /Gy
                   8988:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8989:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8990:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8991:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8992:    /* Optimization are useless and O3 is slower than O2 */
                   8993:    /*
                   8994:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8995:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8996:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8997:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8998:    */
1.186     brouard  8999:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  9000:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   9001:       /PDB:"visual studio
                   9002:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   9003:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   9004:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   9005:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   9006:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   9007:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   9008:       uiAccess='false'"
                   9009:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   9010:       /NOLOGO /TLBID:1
                   9011:    */
1.177     brouard  9012: #if defined __INTEL_COMPILER
1.178     brouard  9013: #if defined(__GNUC__)
                   9014:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9015: #endif
1.177     brouard  9016: #elif defined(__GNUC__) 
1.179     brouard  9017: #ifndef  __APPLE__
1.174     brouard  9018: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9019: #endif
1.177     brouard  9020:    struct utsname sysInfo;
1.178     brouard  9021:    int cross = CROSS;
                   9022:    if (cross){
                   9023:           printf("Cross-");
1.191     brouard  9024:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9025:    }
1.174     brouard  9026: #endif
                   9027: 
1.171     brouard  9028: #include <stdint.h>
1.178     brouard  9029: 
1.191     brouard  9030:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9031: #if defined(__clang__)
1.191     brouard  9032:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9033: #endif
                   9034: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9035:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9036: #endif
                   9037: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9038:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9039: #endif
                   9040: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9041:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9042: #endif
                   9043: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9044:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9045: #endif
                   9046: #if defined(_MSC_VER)
1.191     brouard  9047:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9048: #endif
                   9049: #if defined(__PGI)
1.191     brouard  9050:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9051: #endif
                   9052: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9053:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9054: #endif
1.191     brouard  9055:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9056:    
1.167     brouard  9057: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9058: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9059:     // Windows (x64 and x86)
1.191     brouard  9060:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9061: #elif __unix__ // all unices, not all compilers
                   9062:     // Unix
1.191     brouard  9063:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9064: #elif __linux__
                   9065:     // linux
1.191     brouard  9066:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9067: #elif __APPLE__
1.174     brouard  9068:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9069:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9070: #endif
                   9071: 
                   9072: /*  __MINGW32__          */
                   9073: /*  __CYGWIN__  */
                   9074: /* __MINGW64__  */
                   9075: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9076: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9077: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9078: /* _WIN64  // Defined for applications for Win64. */
                   9079: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9080: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9081: 
1.167     brouard  9082: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9083:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9084: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9085:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9086: #else
1.191     brouard  9087:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9088: #endif
                   9089: 
1.169     brouard  9090: #if defined(__GNUC__)
                   9091: # if defined(__GNUC_PATCHLEVEL__)
                   9092: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9093:                             + __GNUC_MINOR__ * 100 \
                   9094:                             + __GNUC_PATCHLEVEL__)
                   9095: # else
                   9096: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9097:                             + __GNUC_MINOR__ * 100)
                   9098: # endif
1.174     brouard  9099:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9100:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9101: 
                   9102:    if (uname(&sysInfo) != -1) {
                   9103:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9104:         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  9105:    }
                   9106:    else
                   9107:       perror("uname() error");
1.179     brouard  9108:    //#ifndef __INTEL_COMPILER 
                   9109: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9110:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9111:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9112: #endif
1.169     brouard  9113: #endif
1.172     brouard  9114: 
                   9115:    //   void main()
                   9116:    //   {
1.169     brouard  9117: #if defined(_MSC_VER)
1.174     brouard  9118:    if (IsWow64()){
1.191     brouard  9119:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9120:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9121:    }
                   9122:    else{
1.191     brouard  9123:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9124:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9125:    }
1.172     brouard  9126:    //     printf("\nPress Enter to continue...");
                   9127:    //     getchar();
                   9128:    //   }
                   9129: 
1.169     brouard  9130: #endif
                   9131:    
1.167     brouard  9132: 
1.219     brouard  9133: }
1.136     brouard  9134: 
1.219     brouard  9135: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9136:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9137:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9138:   /* double ftolpl = 1.e-10; */
1.180     brouard  9139:   double age, agebase, agelim;
1.203     brouard  9140:   double tot;
1.180     brouard  9141: 
1.202     brouard  9142:   strcpy(filerespl,"PL_");
                   9143:   strcat(filerespl,fileresu);
                   9144:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9145:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9146:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9147:   }
1.227     brouard  9148:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9149:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9150:   pstamp(ficrespl);
1.203     brouard  9151:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9152:   fprintf(ficrespl,"#Age ");
                   9153:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9154:   fprintf(ficrespl,"\n");
1.180     brouard  9155:   
1.219     brouard  9156:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9157: 
1.219     brouard  9158:   agebase=ageminpar;
                   9159:   agelim=agemaxpar;
1.180     brouard  9160: 
1.227     brouard  9161:   /* i1=pow(2,ncoveff); */
1.234     brouard  9162:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9163:   if (cptcovn < 1){i1=1;}
1.180     brouard  9164: 
1.238     brouard  9165:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9166:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9167:       if(TKresult[nres]!= k)
                   9168:        continue;
1.235     brouard  9169: 
1.238     brouard  9170:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9171:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9172:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9173:       /* k=k+1; */
                   9174:       /* to clean */
                   9175:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9176:       fprintf(ficrespl,"#******");
                   9177:       printf("#******");
                   9178:       fprintf(ficlog,"#******");
                   9179:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9180:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9181:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9182:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9183:       }
                   9184:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9185:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9186:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9187:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9188:       }
                   9189:       fprintf(ficrespl,"******\n");
                   9190:       printf("******\n");
                   9191:       fprintf(ficlog,"******\n");
                   9192:       if(invalidvarcomb[k]){
                   9193:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9194:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9195:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9196:        continue;
                   9197:       }
1.219     brouard  9198: 
1.238     brouard  9199:       fprintf(ficrespl,"#Age ");
                   9200:       for(j=1;j<=cptcoveff;j++) {
                   9201:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9202:       }
                   9203:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9204:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9205:     
1.238     brouard  9206:       for (age=agebase; age<=agelim; age++){
                   9207:        /* for (age=agebase; age<=agebase; age++){ */
                   9208:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9209:        fprintf(ficrespl,"%.0f ",age );
                   9210:        for(j=1;j<=cptcoveff;j++)
                   9211:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9212:        tot=0.;
                   9213:        for(i=1; i<=nlstate;i++){
                   9214:          tot +=  prlim[i][i];
                   9215:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9216:        }
                   9217:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9218:       } /* Age */
                   9219:       /* was end of cptcod */
                   9220:     } /* cptcov */
                   9221:   } /* nres */
1.219     brouard  9222:   return 0;
1.180     brouard  9223: }
                   9224: 
1.218     brouard  9225: 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){
                   9226:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9227:        
                   9228:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9229:    * at any age between ageminpar and agemaxpar
                   9230:         */
1.235     brouard  9231:   int i, j, k, i1, nres=0 ;
1.217     brouard  9232:   /* double ftolpl = 1.e-10; */
                   9233:   double age, agebase, agelim;
                   9234:   double tot;
1.218     brouard  9235:   /* double ***mobaverage; */
                   9236:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9237: 
                   9238:   strcpy(fileresplb,"PLB_");
                   9239:   strcat(fileresplb,fileresu);
                   9240:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9241:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9242:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9243:   }
                   9244:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9245:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9246:   pstamp(ficresplb);
                   9247:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9248:   fprintf(ficresplb,"#Age ");
                   9249:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9250:   fprintf(ficresplb,"\n");
                   9251:   
1.218     brouard  9252:   
                   9253:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9254:   
                   9255:   agebase=ageminpar;
                   9256:   agelim=agemaxpar;
                   9257:   
                   9258:   
1.227     brouard  9259:   i1=pow(2,cptcoveff);
1.218     brouard  9260:   if (cptcovn < 1){i1=1;}
1.227     brouard  9261:   
1.238     brouard  9262:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9263:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9264:       if(TKresult[nres]!= k)
                   9265:        continue;
                   9266:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9267:       fprintf(ficresplb,"#******");
                   9268:       printf("#******");
                   9269:       fprintf(ficlog,"#******");
                   9270:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9271:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9272:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9273:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9274:       }
                   9275:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9276:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9277:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9278:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9279:       }
                   9280:       fprintf(ficresplb,"******\n");
                   9281:       printf("******\n");
                   9282:       fprintf(ficlog,"******\n");
                   9283:       if(invalidvarcomb[k]){
                   9284:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9285:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9286:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9287:        continue;
                   9288:       }
1.218     brouard  9289:     
1.238     brouard  9290:       fprintf(ficresplb,"#Age ");
                   9291:       for(j=1;j<=cptcoveff;j++) {
                   9292:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9293:       }
                   9294:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9295:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9296:     
                   9297:     
1.238     brouard  9298:       for (age=agebase; age<=agelim; age++){
                   9299:        /* for (age=agebase; age<=agebase; age++){ */
                   9300:        if(mobilavproj > 0){
                   9301:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9302:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9303:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9304:        }else if (mobilavproj == 0){
                   9305:          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);
                   9306:          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);
                   9307:          exit(1);
                   9308:        }else{
                   9309:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9310:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9311:        }
                   9312:        fprintf(ficresplb,"%.0f ",age );
                   9313:        for(j=1;j<=cptcoveff;j++)
                   9314:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9315:        tot=0.;
                   9316:        for(i=1; i<=nlstate;i++){
                   9317:          tot +=  bprlim[i][i];
                   9318:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9319:        }
                   9320:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9321:       } /* Age */
                   9322:       /* was end of cptcod */
                   9323:     } /* end of any combination */
                   9324:   } /* end of nres */  
1.218     brouard  9325:   /* hBijx(p, bage, fage); */
                   9326:   /* fclose(ficrespijb); */
                   9327:   
                   9328:   return 0;
1.217     brouard  9329: }
1.218     brouard  9330:  
1.180     brouard  9331: int hPijx(double *p, int bage, int fage){
                   9332:     /*------------- h Pij x at various ages ------------*/
                   9333: 
                   9334:   int stepsize;
                   9335:   int agelim;
                   9336:   int hstepm;
                   9337:   int nhstepm;
1.235     brouard  9338:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9339: 
                   9340:   double agedeb;
                   9341:   double ***p3mat;
                   9342: 
1.201     brouard  9343:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9344:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9345:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9346:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9347:     }
                   9348:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9349:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9350:   
                   9351:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9352:     /*if (stepm<=24) stepsize=2;*/
                   9353: 
                   9354:     agelim=AGESUP;
                   9355:     hstepm=stepsize*YEARM; /* Every year of age */
                   9356:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9357:                
1.180     brouard  9358:     /* hstepm=1;   aff par mois*/
                   9359:     pstamp(ficrespij);
                   9360:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9361:     i1= pow(2,cptcoveff);
1.218     brouard  9362:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9363:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9364:                /*      k=k+1;  */
1.235     brouard  9365:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9366:     for(k=1; k<=i1;k++){
                   9367:       if(TKresult[nres]!= k)
                   9368:        continue;
1.183     brouard  9369:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9370:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9371:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9372:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9373:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9374:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9375:       }
1.183     brouard  9376:       fprintf(ficrespij,"******\n");
                   9377:       
                   9378:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9379:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9380:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9381:        
                   9382:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9383:        
1.183     brouard  9384:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9385:        oldm=oldms;savm=savms;
1.235     brouard  9386:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9387:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9388:        for(i=1; i<=nlstate;i++)
                   9389:          for(j=1; j<=nlstate+ndeath;j++)
                   9390:            fprintf(ficrespij," %1d-%1d",i,j);
                   9391:        fprintf(ficrespij,"\n");
                   9392:        for (h=0; h<=nhstepm; h++){
                   9393:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9394:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9395:          for(i=1; i<=nlstate;i++)
                   9396:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9397:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9398:          fprintf(ficrespij,"\n");
                   9399:        }
1.183     brouard  9400:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9401:        fprintf(ficrespij,"\n");
                   9402:       }
1.180     brouard  9403:       /*}*/
                   9404:     }
1.218     brouard  9405:     return 0;
1.180     brouard  9406: }
1.218     brouard  9407:  
                   9408:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9409:     /*------------- h Bij x at various ages ------------*/
                   9410: 
                   9411:   int stepsize;
1.218     brouard  9412:   /* int agelim; */
                   9413:        int ageminl;
1.217     brouard  9414:   int hstepm;
                   9415:   int nhstepm;
1.238     brouard  9416:   int h, i, i1, j, k, nres;
1.218     brouard  9417:        
1.217     brouard  9418:   double agedeb;
                   9419:   double ***p3mat;
1.218     brouard  9420:        
                   9421:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9422:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9423:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9424:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9425:   }
                   9426:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9427:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9428:   
                   9429:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9430:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9431:   
1.218     brouard  9432:   /* agelim=AGESUP; */
                   9433:   ageminl=30;
                   9434:   hstepm=stepsize*YEARM; /* Every year of age */
                   9435:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9436:   
                   9437:   /* hstepm=1;   aff par mois*/
                   9438:   pstamp(ficrespijb);
                   9439:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9440:   i1= pow(2,cptcoveff);
1.218     brouard  9441:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9442:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9443:   /*   k=k+1;  */
1.238     brouard  9444:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9445:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9446:       if(TKresult[nres]!= k)
                   9447:        continue;
                   9448:       fprintf(ficrespijb,"\n#****** ");
                   9449:       for(j=1;j<=cptcoveff;j++)
                   9450:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9451:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9452:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9453:       }
                   9454:       fprintf(ficrespijb,"******\n");
                   9455:       if(invalidvarcomb[k]){
                   9456:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9457:        continue;
                   9458:       }
                   9459:       
                   9460:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9461:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9462:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9463:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9464:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9465:        
                   9466:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9467:        
                   9468:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9469:        /* oldm=oldms;savm=savms; */
                   9470:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9471:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9472:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9473:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9474:        for(i=1; i<=nlstate;i++)
                   9475:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9476:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9477:        fprintf(ficrespijb,"\n");
1.238     brouard  9478:        for (h=0; h<=nhstepm; h++){
                   9479:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9480:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9481:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9482:          for(i=1; i<=nlstate;i++)
                   9483:            for(j=1; j<=nlstate+ndeath;j++)
                   9484:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9485:          fprintf(ficrespijb,"\n");
                   9486:        }
                   9487:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9488:        fprintf(ficrespijb,"\n");
                   9489:       } /* end age deb */
                   9490:     } /* end combination */
                   9491:   } /* end nres */
1.218     brouard  9492:   return 0;
                   9493:  } /*  hBijx */
1.217     brouard  9494: 
1.180     brouard  9495: 
1.136     brouard  9496: /***********************************************/
                   9497: /**************** Main Program *****************/
                   9498: /***********************************************/
                   9499: 
                   9500: int main(int argc, char *argv[])
                   9501: {
                   9502: #ifdef GSL
                   9503:   const gsl_multimin_fminimizer_type *T;
                   9504:   size_t iteri = 0, it;
                   9505:   int rval = GSL_CONTINUE;
                   9506:   int status = GSL_SUCCESS;
                   9507:   double ssval;
                   9508: #endif
                   9509:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9510:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9511:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9512:   int jj, ll, li, lj, lk;
1.136     brouard  9513:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9514:   int num_filled;
1.136     brouard  9515:   int itimes;
                   9516:   int NDIM=2;
                   9517:   int vpopbased=0;
1.235     brouard  9518:   int nres=0;
1.136     brouard  9519: 
1.164     brouard  9520:   char ca[32], cb[32];
1.136     brouard  9521:   /*  FILE *fichtm; *//* Html File */
                   9522:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9523:   struct stat info;
1.191     brouard  9524:   double agedeb=0.;
1.194     brouard  9525: 
                   9526:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9527:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9528: 
1.165     brouard  9529:   double fret;
1.191     brouard  9530:   double dum=0.; /* Dummy variable */
1.136     brouard  9531:   double ***p3mat;
1.218     brouard  9532:   /* double ***mobaverage; */
1.164     brouard  9533: 
                   9534:   char line[MAXLINE];
1.197     brouard  9535:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9536: 
1.234     brouard  9537:   char  modeltemp[MAXLINE];
1.230     brouard  9538:   char resultline[MAXLINE];
                   9539:   
1.136     brouard  9540:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9541:   char *tok, *val; /* pathtot */
1.136     brouard  9542:   int firstobs=1, lastobs=10;
1.195     brouard  9543:   int c,  h , cpt, c2;
1.191     brouard  9544:   int jl=0;
                   9545:   int i1, j1, jk, stepsize=0;
1.194     brouard  9546:   int count=0;
                   9547: 
1.164     brouard  9548:   int *tab; 
1.136     brouard  9549:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9550:   int backcast=0;
1.136     brouard  9551:   int mobilav=0,popforecast=0;
1.191     brouard  9552:   int hstepm=0, nhstepm=0;
1.136     brouard  9553:   int agemortsup;
                   9554:   float  sumlpop=0.;
                   9555:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9556:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9557: 
1.191     brouard  9558:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9559:   double ftolpl=FTOL;
                   9560:   double **prlim;
1.217     brouard  9561:   double **bprlim;
1.136     brouard  9562:   double ***param; /* Matrix of parameters */
                   9563:   double  *p;
                   9564:   double **matcov; /* Matrix of covariance */
1.203     brouard  9565:   double **hess; /* Hessian matrix */
1.136     brouard  9566:   double ***delti3; /* Scale */
                   9567:   double *delti; /* Scale */
                   9568:   double ***eij, ***vareij;
                   9569:   double **varpl; /* Variances of prevalence limits by age */
                   9570:   double *epj, vepp;
1.164     brouard  9571: 
1.136     brouard  9572:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9573:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9574: 
1.136     brouard  9575:   double **ximort;
1.145     brouard  9576:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9577:   int *dcwave;
                   9578: 
1.164     brouard  9579:   char z[1]="c";
1.136     brouard  9580: 
                   9581:   /*char  *strt;*/
                   9582:   char strtend[80];
1.126     brouard  9583: 
1.164     brouard  9584: 
1.126     brouard  9585: /*   setlocale (LC_ALL, ""); */
                   9586: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9587: /*   textdomain (PACKAGE); */
                   9588: /*   setlocale (LC_CTYPE, ""); */
                   9589: /*   setlocale (LC_MESSAGES, ""); */
                   9590: 
                   9591:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9592:   rstart_time = time(NULL);  
                   9593:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9594:   start_time = *localtime(&rstart_time);
1.126     brouard  9595:   curr_time=start_time;
1.157     brouard  9596:   /*tml = *localtime(&start_time.tm_sec);*/
                   9597:   /* strcpy(strstart,asctime(&tml)); */
                   9598:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9599: 
                   9600: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9601: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9602: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9603: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9604: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9605: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9606: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9607: /*   strt=asctime(&tmg); */
                   9608: /*   printf("Time(after) =%s",strstart);  */
                   9609: /*  (void) time (&time_value);
                   9610: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9611: *  tm = *localtime(&time_value);
                   9612: *  strstart=asctime(&tm);
                   9613: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9614: */
                   9615: 
                   9616:   nberr=0; /* Number of errors and warnings */
                   9617:   nbwarn=0;
1.184     brouard  9618: #ifdef WIN32
                   9619:   _getcwd(pathcd, size);
                   9620: #else
1.126     brouard  9621:   getcwd(pathcd, size);
1.184     brouard  9622: #endif
1.191     brouard  9623:   syscompilerinfo(0);
1.196     brouard  9624:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9625:   if(argc <=1){
                   9626:     printf("\nEnter the parameter file name: ");
1.205     brouard  9627:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9628:       printf("ERROR Empty parameter file name\n");
                   9629:       goto end;
                   9630:     }
1.126     brouard  9631:     i=strlen(pathr);
                   9632:     if(pathr[i-1]=='\n')
                   9633:       pathr[i-1]='\0';
1.156     brouard  9634:     i=strlen(pathr);
1.205     brouard  9635:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9636:       pathr[i-1]='\0';
1.205     brouard  9637:     }
                   9638:     i=strlen(pathr);
                   9639:     if( i==0 ){
                   9640:       printf("ERROR Empty parameter file name\n");
                   9641:       goto end;
                   9642:     }
                   9643:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9644:       printf("Pathr |%s|\n",pathr);
                   9645:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9646:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9647:       strcpy (pathtot, val);
                   9648:       if(pathr[0] == '\0') break; /* Dirty */
                   9649:     }
                   9650:   }
                   9651:   else{
                   9652:     strcpy(pathtot,argv[1]);
                   9653:   }
                   9654:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9655:   /*cygwin_split_path(pathtot,path,optionfile);
                   9656:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9657:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9658: 
                   9659:   /* Split argv[0], imach program to get pathimach */
                   9660:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9661:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9662:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9663:  /*   strcpy(pathimach,argv[0]); */
                   9664:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9665:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9666:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9667: #ifdef WIN32
                   9668:   _chdir(path); /* Can be a relative path */
                   9669:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9670: #else
1.126     brouard  9671:   chdir(path); /* Can be a relative path */
1.184     brouard  9672:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9673: #endif
                   9674:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9675:   strcpy(command,"mkdir ");
                   9676:   strcat(command,optionfilefiname);
                   9677:   if((outcmd=system(command)) != 0){
1.169     brouard  9678:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9679:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9680:     /* fclose(ficlog); */
                   9681: /*     exit(1); */
                   9682:   }
                   9683: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9684: /*     perror("mkdir"); */
                   9685: /*   } */
                   9686: 
                   9687:   /*-------- arguments in the command line --------*/
                   9688: 
1.186     brouard  9689:   /* Main Log file */
1.126     brouard  9690:   strcat(filelog, optionfilefiname);
                   9691:   strcat(filelog,".log");    /* */
                   9692:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9693:     printf("Problem with logfile %s\n",filelog);
                   9694:     goto end;
                   9695:   }
                   9696:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9697:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9698:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9699:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9700:  path=%s \n\
                   9701:  optionfile=%s\n\
                   9702:  optionfilext=%s\n\
1.156     brouard  9703:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9704: 
1.197     brouard  9705:   syscompilerinfo(1);
1.167     brouard  9706: 
1.126     brouard  9707:   printf("Local time (at start):%s",strstart);
                   9708:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9709:   fflush(ficlog);
                   9710: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9711: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9712: 
                   9713:   /* */
                   9714:   strcpy(fileres,"r");
                   9715:   strcat(fileres, optionfilefiname);
1.201     brouard  9716:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9717:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9718:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9719: 
1.186     brouard  9720:   /* Main ---------arguments file --------*/
1.126     brouard  9721: 
                   9722:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9723:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9724:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9725:     fflush(ficlog);
1.149     brouard  9726:     /* goto end; */
                   9727:     exit(70); 
1.126     brouard  9728:   }
                   9729: 
                   9730: 
                   9731: 
                   9732:   strcpy(filereso,"o");
1.201     brouard  9733:   strcat(filereso,fileresu);
1.126     brouard  9734:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9735:     printf("Problem with Output resultfile: %s\n", filereso);
                   9736:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9737:     fflush(ficlog);
                   9738:     goto end;
                   9739:   }
                   9740: 
                   9741:   /* Reads comments: lines beginning with '#' */
                   9742:   numlinepar=0;
1.197     brouard  9743: 
                   9744:     /* First parameter line */
                   9745:   while(fgets(line, MAXLINE, ficpar)) {
                   9746:     /* If line starts with a # it is a comment */
                   9747:     if (line[0] == '#') {
                   9748:       numlinepar++;
                   9749:       fputs(line,stdout);
                   9750:       fputs(line,ficparo);
                   9751:       fputs(line,ficlog);
                   9752:       continue;
                   9753:     }else
                   9754:       break;
                   9755:   }
                   9756:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9757:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9758:     if (num_filled != 5) {
                   9759:       printf("Should be 5 parameters\n");
                   9760:     }
1.126     brouard  9761:     numlinepar++;
1.197     brouard  9762:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9763:   }
                   9764:   /* Second parameter line */
                   9765:   while(fgets(line, MAXLINE, ficpar)) {
                   9766:     /* If line starts with a # it is a comment */
                   9767:     if (line[0] == '#') {
                   9768:       numlinepar++;
                   9769:       fputs(line,stdout);
                   9770:       fputs(line,ficparo);
                   9771:       fputs(line,ficlog);
                   9772:       continue;
                   9773:     }else
                   9774:       break;
                   9775:   }
1.223     brouard  9776:   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", \
                   9777:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9778:     if (num_filled != 11) {
                   9779:       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  9780:       printf("but line=%s\n",line);
1.197     brouard  9781:     }
1.223     brouard  9782:     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  9783:   }
1.203     brouard  9784:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9785:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9786:   /* Third parameter line */
                   9787:   while(fgets(line, MAXLINE, ficpar)) {
                   9788:     /* If line starts with a # it is a comment */
                   9789:     if (line[0] == '#') {
                   9790:       numlinepar++;
                   9791:       fputs(line,stdout);
                   9792:       fputs(line,ficparo);
                   9793:       fputs(line,ficlog);
                   9794:       continue;
                   9795:     }else
                   9796:       break;
                   9797:   }
1.201     brouard  9798:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9799:     if (num_filled == 0)
                   9800:             model[0]='\0';
                   9801:     else if (num_filled != 1){
1.197     brouard  9802:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9803:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9804:       model[0]='\0';
                   9805:       goto end;
                   9806:     }
                   9807:     else{
                   9808:       if (model[0]=='+'){
                   9809:        for(i=1; i<=strlen(model);i++)
                   9810:          modeltemp[i-1]=model[i];
1.201     brouard  9811:        strcpy(model,modeltemp); 
1.197     brouard  9812:       }
                   9813:     }
1.199     brouard  9814:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9815:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9816:   }
                   9817:   /* 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); */
                   9818:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9819:   /* 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  9820:   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);
                   9821:   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  9822:   fflush(ficlog);
1.190     brouard  9823:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9824:   if(model[0]=='#'){
1.187     brouard  9825:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9826:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9827:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9828:     if(mle != -1){
                   9829:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9830:       exit(1);
                   9831:     }
                   9832:   }
1.126     brouard  9833:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9834:     ungetc(c,ficpar);
                   9835:     fgets(line, MAXLINE, ficpar);
                   9836:     numlinepar++;
1.195     brouard  9837:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9838:       z[0]=line[1];
                   9839:     }
                   9840:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9841:     fputs(line, stdout);
                   9842:     //puts(line);
1.126     brouard  9843:     fputs(line,ficparo);
                   9844:     fputs(line,ficlog);
                   9845:   }
                   9846:   ungetc(c,ficpar);
                   9847: 
                   9848:    
1.145     brouard  9849:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9850:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9851:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9852:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9853:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9854:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9855:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9856:   */
                   9857:   if (strlen(model)>1) 
1.187     brouard  9858:     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  9859:   else
1.187     brouard  9860:     ncovmodel=2; /* Constant and age */
1.133     brouard  9861:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9862:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9863:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9864:     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);
                   9865:     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);
                   9866:     fflush(stdout);
                   9867:     fclose (ficlog);
                   9868:     goto end;
                   9869:   }
1.126     brouard  9870:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9871:   delti=delti3[1][1];
                   9872:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9873:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9874:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9875:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9876:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9877:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9878:     fclose (ficparo);
                   9879:     fclose (ficlog);
                   9880:     goto end;
                   9881:     exit(0);
1.220     brouard  9882:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9883:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9884:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9885:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9886:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9887:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9888:     hess=matrix(1,npar,1,npar);
1.220     brouard  9889:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9890:     /* Read guessed parameters */
1.126     brouard  9891:     /* Reads comments: lines beginning with '#' */
                   9892:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9893:       ungetc(c,ficpar);
                   9894:       fgets(line, MAXLINE, ficpar);
                   9895:       numlinepar++;
1.141     brouard  9896:       fputs(line,stdout);
1.126     brouard  9897:       fputs(line,ficparo);
                   9898:       fputs(line,ficlog);
                   9899:     }
                   9900:     ungetc(c,ficpar);
                   9901:     
                   9902:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9903:     for(i=1; i <=nlstate; i++){
1.234     brouard  9904:       j=0;
1.126     brouard  9905:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9906:        if(jj==i) continue;
                   9907:        j++;
                   9908:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9909:        if ((i1 != i) || (j1 != jj)){
                   9910:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9911: It might be a problem of design; if ncovcol and the model are correct\n \
                   9912: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9913:          exit(1);
                   9914:        }
                   9915:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9916:        if(mle==1)
                   9917:          printf("%1d%1d",i,jj);
                   9918:        fprintf(ficlog,"%1d%1d",i,jj);
                   9919:        for(k=1; k<=ncovmodel;k++){
                   9920:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9921:          if(mle==1){
                   9922:            printf(" %lf",param[i][j][k]);
                   9923:            fprintf(ficlog," %lf",param[i][j][k]);
                   9924:          }
                   9925:          else
                   9926:            fprintf(ficlog," %lf",param[i][j][k]);
                   9927:          fprintf(ficparo," %lf",param[i][j][k]);
                   9928:        }
                   9929:        fscanf(ficpar,"\n");
                   9930:        numlinepar++;
                   9931:        if(mle==1)
                   9932:          printf("\n");
                   9933:        fprintf(ficlog,"\n");
                   9934:        fprintf(ficparo,"\n");
1.126     brouard  9935:       }
                   9936:     }  
                   9937:     fflush(ficlog);
1.234     brouard  9938:     
1.145     brouard  9939:     /* Reads scales values */
1.126     brouard  9940:     p=param[1][1];
                   9941:     
                   9942:     /* Reads comments: lines beginning with '#' */
                   9943:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9944:       ungetc(c,ficpar);
                   9945:       fgets(line, MAXLINE, ficpar);
                   9946:       numlinepar++;
1.141     brouard  9947:       fputs(line,stdout);
1.126     brouard  9948:       fputs(line,ficparo);
                   9949:       fputs(line,ficlog);
                   9950:     }
                   9951:     ungetc(c,ficpar);
                   9952: 
                   9953:     for(i=1; i <=nlstate; i++){
                   9954:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9955:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9956:        if ( (i1-i) * (j1-j) != 0){
                   9957:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9958:          exit(1);
                   9959:        }
                   9960:        printf("%1d%1d",i,j);
                   9961:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9962:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9963:        for(k=1; k<=ncovmodel;k++){
                   9964:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9965:          printf(" %le",delti3[i][j][k]);
                   9966:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9967:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9968:        }
                   9969:        fscanf(ficpar,"\n");
                   9970:        numlinepar++;
                   9971:        printf("\n");
                   9972:        fprintf(ficparo,"\n");
                   9973:        fprintf(ficlog,"\n");
1.126     brouard  9974:       }
                   9975:     }
                   9976:     fflush(ficlog);
1.234     brouard  9977:     
1.145     brouard  9978:     /* Reads covariance matrix */
1.126     brouard  9979:     delti=delti3[1][1];
1.220     brouard  9980:                
                   9981:                
1.126     brouard  9982:     /* 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  9983:                
1.126     brouard  9984:     /* Reads comments: lines beginning with '#' */
                   9985:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9986:       ungetc(c,ficpar);
                   9987:       fgets(line, MAXLINE, ficpar);
                   9988:       numlinepar++;
1.141     brouard  9989:       fputs(line,stdout);
1.126     brouard  9990:       fputs(line,ficparo);
                   9991:       fputs(line,ficlog);
                   9992:     }
                   9993:     ungetc(c,ficpar);
1.220     brouard  9994:                
1.126     brouard  9995:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9996:     hess=matrix(1,npar,1,npar);
1.131     brouard  9997:     for(i=1; i <=npar; i++)
                   9998:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9999:                
1.194     brouard  10000:     /* Scans npar lines */
1.126     brouard  10001:     for(i=1; i <=npar; i++){
1.226     brouard  10002:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  10003:       if(count != 3){
1.226     brouard  10004:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10005: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10006: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10007:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10008: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10009: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10010:        exit(1);
1.220     brouard  10011:       }else{
1.226     brouard  10012:        if(mle==1)
                   10013:          printf("%1d%1d%d",i1,j1,jk);
                   10014:       }
                   10015:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10016:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10017:       for(j=1; j <=i; j++){
1.226     brouard  10018:        fscanf(ficpar," %le",&matcov[i][j]);
                   10019:        if(mle==1){
                   10020:          printf(" %.5le",matcov[i][j]);
                   10021:        }
                   10022:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10023:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10024:       }
                   10025:       fscanf(ficpar,"\n");
                   10026:       numlinepar++;
                   10027:       if(mle==1)
1.220     brouard  10028:                                printf("\n");
1.126     brouard  10029:       fprintf(ficlog,"\n");
                   10030:       fprintf(ficparo,"\n");
                   10031:     }
1.194     brouard  10032:     /* End of read covariance matrix npar lines */
1.126     brouard  10033:     for(i=1; i <=npar; i++)
                   10034:       for(j=i+1;j<=npar;j++)
1.226     brouard  10035:        matcov[i][j]=matcov[j][i];
1.126     brouard  10036:     
                   10037:     if(mle==1)
                   10038:       printf("\n");
                   10039:     fprintf(ficlog,"\n");
                   10040:     
                   10041:     fflush(ficlog);
                   10042:     
                   10043:     /*-------- Rewriting parameter file ----------*/
                   10044:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10045:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10046:     strcat(rfileres,".");    /* */
                   10047:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10048:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10049:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10050:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10051:     }
                   10052:     fprintf(ficres,"#%s\n",version);
                   10053:   }    /* End of mle != -3 */
1.218     brouard  10054:   
1.186     brouard  10055:   /*  Main data
                   10056:    */
1.126     brouard  10057:   n= lastobs;
                   10058:   num=lvector(1,n);
                   10059:   moisnais=vector(1,n);
                   10060:   annais=vector(1,n);
                   10061:   moisdc=vector(1,n);
                   10062:   andc=vector(1,n);
1.220     brouard  10063:   weight=vector(1,n);
1.126     brouard  10064:   agedc=vector(1,n);
                   10065:   cod=ivector(1,n);
1.220     brouard  10066:   for(i=1;i<=n;i++){
1.234     brouard  10067:     num[i]=0;
                   10068:     moisnais[i]=0;
                   10069:     annais[i]=0;
                   10070:     moisdc[i]=0;
                   10071:     andc[i]=0;
                   10072:     agedc[i]=0;
                   10073:     cod[i]=0;
                   10074:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10075:   }
1.126     brouard  10076:   mint=matrix(1,maxwav,1,n);
                   10077:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10078:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10079:   tab=ivector(1,NCOVMAX);
1.144     brouard  10080:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10081:   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  10082: 
1.136     brouard  10083:   /* Reads data from file datafile */
                   10084:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10085:     goto end;
                   10086: 
                   10087:   /* Calculation of the number of parameters from char model */
1.234     brouard  10088:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10089:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10090:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10091:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10092:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10093:   */
                   10094:   
                   10095:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10096:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10097:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10098:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10099:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10100:   TvarF=ivector(1,NCOVMAX); /*  */
                   10101:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10102:   TvarV=ivector(1,NCOVMAX); /*  */
                   10103:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10104:   TvarA=ivector(1,NCOVMAX); /*  */
                   10105:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10106:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10107:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10108:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10109:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10110:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10111:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10112:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10113:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10114: 
1.230     brouard  10115:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10116:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10117:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10118:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10119:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10120:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10121:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10122:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10123:   */
                   10124:   /* For model-covariate k tells which data-covariate to use but
                   10125:     because this model-covariate is a construction we invent a new column
                   10126:     ncovcol + k1
                   10127:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10128:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10129:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10130:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10131:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10132:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10133:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10134:   */
1.145     brouard  10135:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10136:   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  10137:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10138:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10139:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10140:                         4 covariates (3 plus signs)
                   10141:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10142:                      */  
1.230     brouard  10143:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10144:                                * individual dummy, fixed or varying:
                   10145:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10146:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10147:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10148:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10149:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10150:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10151:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10152:                                * individual quantitative, fixed or varying:
                   10153:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10154:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10155:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10156: /* Main decodemodel */
                   10157: 
1.187     brouard  10158: 
1.223     brouard  10159:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10160:     goto end;
                   10161: 
1.137     brouard  10162:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10163:     nbwarn++;
                   10164:     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); 
                   10165:     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); 
                   10166:   }
1.136     brouard  10167:     /*  if(mle==1){*/
1.137     brouard  10168:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10169:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10170:   }
                   10171: 
                   10172:     /*-calculation of age at interview from date of interview and age at death -*/
                   10173:   agev=matrix(1,maxwav,1,imx);
                   10174: 
                   10175:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10176:     goto end;
                   10177: 
1.126     brouard  10178: 
1.136     brouard  10179:   agegomp=(int)agemin;
                   10180:   free_vector(moisnais,1,n);
                   10181:   free_vector(annais,1,n);
1.126     brouard  10182:   /* free_matrix(mint,1,maxwav,1,n);
                   10183:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10184:   /* free_vector(moisdc,1,n); */
                   10185:   /* free_vector(andc,1,n); */
1.145     brouard  10186:   /* */
                   10187:   
1.126     brouard  10188:   wav=ivector(1,imx);
1.214     brouard  10189:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10190:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10191:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10192:   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.*/
                   10193:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10194:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10195:    
                   10196:   /* Concatenates waves */
1.214     brouard  10197:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10198:      Death is a valid wave (if date is known).
                   10199:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10200:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10201:      and mw[mi+1][i]. dh depends on stepm.
                   10202:   */
                   10203: 
1.126     brouard  10204:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  10205:   /* */
                   10206:  
1.215     brouard  10207:   free_vector(moisdc,1,n);
                   10208:   free_vector(andc,1,n);
                   10209: 
1.126     brouard  10210:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10211:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10212:   ncodemax[1]=1;
1.145     brouard  10213:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10214:   cptcoveff=0;
1.220     brouard  10215:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10216:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10217:   }
                   10218:   
                   10219:   ncovcombmax=pow(2,cptcoveff);
                   10220:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10221:   for(i=1;i<ncovcombmax;i++)
                   10222:     invalidvarcomb[i]=0;
                   10223:   
1.211     brouard  10224:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10225:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10226:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10227:   
1.200     brouard  10228:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10229:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10230:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10231:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10232:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10233:    * (currently 0 or 1) in the data.
                   10234:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10235:    * corresponding modality (h,j).
                   10236:    */
                   10237: 
1.145     brouard  10238:   h=0;
                   10239:   /*if (cptcovn > 0) */
1.126     brouard  10240:   m=pow(2,cptcoveff);
                   10241:  
1.144     brouard  10242:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10243:           * For k=4 covariates, h goes from 1 to m=2**k
                   10244:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10245:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10246:           *     h\k   1     2     3     4
1.143     brouard  10247:           *______________________________  
                   10248:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10249:           *     2     2     1     1     1
                   10250:           *     3 i=2 1     2     1     1
                   10251:           *     4     2     2     1     1
                   10252:           *     5 i=3 1 i=2 1     2     1
                   10253:           *     6     2     1     2     1
                   10254:           *     7 i=4 1     2     2     1
                   10255:           *     8     2     2     2     1
1.197     brouard  10256:           *     9 i=5 1 i=3 1 i=2 1     2
                   10257:           *    10     2     1     1     2
                   10258:           *    11 i=6 1     2     1     2
                   10259:           *    12     2     2     1     2
                   10260:           *    13 i=7 1 i=4 1     2     2    
                   10261:           *    14     2     1     2     2
                   10262:           *    15 i=8 1     2     2     2
                   10263:           *    16     2     2     2     2
1.143     brouard  10264:           */
1.212     brouard  10265:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10266:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10267:      * and the value of each covariate?
                   10268:      * V1=1, V2=1, V3=2, V4=1 ?
                   10269:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10270:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10271:      * In order to get the real value in the data, we use nbcode
                   10272:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10273:      * We are keeping this crazy system in order to be able (in the future?) 
                   10274:      * to have more than 2 values (0 or 1) for a covariate.
                   10275:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10276:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10277:      *              bbbbbbbb
                   10278:      *              76543210     
                   10279:      *   h-1        00000101 (6-1=5)
1.219     brouard  10280:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10281:      *           &
                   10282:      *     1        00000001 (1)
1.219     brouard  10283:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10284:      *          +1= 00000001 =1 
1.211     brouard  10285:      *
                   10286:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10287:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10288:      *    >>k'            11
                   10289:      *          &   00000001
                   10290:      *            = 00000001
                   10291:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10292:      * Reverse h=6 and m=16?
                   10293:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10294:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10295:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10296:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10297:      * V3=decodtabm(14,3,2**4)=2
                   10298:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10299:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10300:      *          &1 000000001
                   10301:      *           = 000000001
                   10302:      *         +1= 000000010 =2
                   10303:      *                  2211
                   10304:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10305:      *                  V3=2
1.220     brouard  10306:                 * codtabm and decodtabm are identical
1.211     brouard  10307:      */
                   10308: 
1.145     brouard  10309: 
                   10310:  free_ivector(Ndum,-1,NCOVMAX);
                   10311: 
                   10312: 
1.126     brouard  10313:     
1.186     brouard  10314:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10315:   strcpy(optionfilegnuplot,optionfilefiname);
                   10316:   if(mle==-3)
1.201     brouard  10317:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10318:   strcat(optionfilegnuplot,".gp");
                   10319: 
                   10320:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10321:     printf("Problem with file %s",optionfilegnuplot);
                   10322:   }
                   10323:   else{
1.204     brouard  10324:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10325:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10326:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10327:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10328:   }
                   10329:   /*  fclose(ficgp);*/
1.186     brouard  10330: 
                   10331: 
                   10332:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10333: 
                   10334:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10335:   if(mle==-3)
1.201     brouard  10336:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10337:   strcat(optionfilehtm,".htm");
                   10338:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10339:     printf("Problem with %s \n",optionfilehtm);
                   10340:     exit(0);
1.126     brouard  10341:   }
                   10342: 
                   10343:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10344:   strcat(optionfilehtmcov,"-cov.htm");
                   10345:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10346:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10347:   }
                   10348:   else{
                   10349:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10350: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10351: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10352:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10353:   }
                   10354: 
1.213     brouard  10355:   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  10356: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10357: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10358: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10359: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10360: \n\
                   10361: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10362:  <ul><li><h4>Parameter files</h4>\n\
                   10363:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10364:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10365:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10366:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10367:  - Date and time at start: %s</ul>\n",\
                   10368:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10369:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10370:          fileres,fileres,\
                   10371:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10372:   fflush(fichtm);
                   10373: 
                   10374:   strcpy(pathr,path);
                   10375:   strcat(pathr,optionfilefiname);
1.184     brouard  10376: #ifdef WIN32
                   10377:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10378: #else
1.126     brouard  10379:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10380: #endif
                   10381:          
1.126     brouard  10382:   
1.220     brouard  10383:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10384:                 and for any valid combination of covariates
1.126     brouard  10385:      and prints on file fileres'p'. */
1.227     brouard  10386:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10387:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10388: 
                   10389:   fprintf(fichtm,"\n");
                   10390:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10391: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10392: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10393:          imx,agemin,agemax,jmin,jmax,jmean);
                   10394:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10395:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10396:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10397:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10398:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10399: 
1.126     brouard  10400:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10401:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10402:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10403: 
                   10404:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10405:   /* For mortality only */
1.126     brouard  10406:   if (mle==-3){
1.136     brouard  10407:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10408:                for(i=1;i<=NDIM;i++)
                   10409:                        for(j=1;j<=NDIM;j++)
                   10410:                                ximort[i][j]=0.;
1.186     brouard  10411:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10412:     cens=ivector(1,n);
                   10413:     ageexmed=vector(1,n);
                   10414:     agecens=vector(1,n);
                   10415:     dcwave=ivector(1,n);
1.223     brouard  10416:                
1.126     brouard  10417:     for (i=1; i<=imx; i++){
                   10418:       dcwave[i]=-1;
                   10419:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10420:        if (s[m][i]>nlstate) {
                   10421:          dcwave[i]=m;
                   10422:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10423:          break;
                   10424:        }
1.126     brouard  10425:     }
1.226     brouard  10426:     
1.126     brouard  10427:     for (i=1; i<=imx; i++) {
                   10428:       if (wav[i]>0){
1.226     brouard  10429:        ageexmed[i]=agev[mw[1][i]][i];
                   10430:        j=wav[i];
                   10431:        agecens[i]=1.; 
                   10432:        
                   10433:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10434:          agecens[i]=agev[mw[j][i]][i];
                   10435:          cens[i]= 1;
                   10436:        }else if (ageexmed[i]< 1) 
                   10437:          cens[i]= -1;
                   10438:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10439:          cens[i]=0 ;
1.126     brouard  10440:       }
                   10441:       else cens[i]=-1;
                   10442:     }
                   10443:     
                   10444:     for (i=1;i<=NDIM;i++) {
                   10445:       for (j=1;j<=NDIM;j++)
1.226     brouard  10446:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10447:     }
                   10448:     
1.145     brouard  10449:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10450:     /*printf("%lf %lf", p[1], p[2]);*/
                   10451:     
                   10452:     
1.136     brouard  10453: #ifdef GSL
                   10454:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10455: #else
1.126     brouard  10456:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10457: #endif
1.201     brouard  10458:     strcpy(filerespow,"POW-MORT_"); 
                   10459:     strcat(filerespow,fileresu);
1.126     brouard  10460:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10461:       printf("Problem with resultfile: %s\n", filerespow);
                   10462:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10463:     }
1.136     brouard  10464: #ifdef GSL
                   10465:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10466: #else
1.126     brouard  10467:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10468: #endif
1.126     brouard  10469:     /*  for (i=1;i<=nlstate;i++)
                   10470:        for(j=1;j<=nlstate+ndeath;j++)
                   10471:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10472:     */
                   10473:     fprintf(ficrespow,"\n");
1.136     brouard  10474: #ifdef GSL
                   10475:     /* gsl starts here */ 
                   10476:     T = gsl_multimin_fminimizer_nmsimplex;
                   10477:     gsl_multimin_fminimizer *sfm = NULL;
                   10478:     gsl_vector *ss, *x;
                   10479:     gsl_multimin_function minex_func;
                   10480: 
                   10481:     /* Initial vertex size vector */
                   10482:     ss = gsl_vector_alloc (NDIM);
                   10483:     
                   10484:     if (ss == NULL){
                   10485:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10486:     }
                   10487:     /* Set all step sizes to 1 */
                   10488:     gsl_vector_set_all (ss, 0.001);
                   10489: 
                   10490:     /* Starting point */
1.126     brouard  10491:     
1.136     brouard  10492:     x = gsl_vector_alloc (NDIM);
                   10493:     
                   10494:     if (x == NULL){
                   10495:       gsl_vector_free(ss);
                   10496:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10497:     }
                   10498:   
                   10499:     /* Initialize method and iterate */
                   10500:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10501:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10502:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10503:     gsl_vector_set(x, 0, p[1]);
                   10504:     gsl_vector_set(x, 1, p[2]);
                   10505: 
                   10506:     minex_func.f = &gompertz_f;
                   10507:     minex_func.n = NDIM;
                   10508:     minex_func.params = (void *)&p; /* ??? */
                   10509:     
                   10510:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10511:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10512:     
                   10513:     printf("Iterations beginning .....\n\n");
                   10514:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10515: 
                   10516:     iteri=0;
                   10517:     while (rval == GSL_CONTINUE){
                   10518:       iteri++;
                   10519:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10520:       
                   10521:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10522:       fflush(0);
                   10523:       
                   10524:       if (status) 
                   10525:         break;
                   10526:       
                   10527:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10528:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10529:       
                   10530:       if (rval == GSL_SUCCESS)
                   10531:         printf ("converged to a local maximum at\n");
                   10532:       
                   10533:       printf("%5d ", iteri);
                   10534:       for (it = 0; it < NDIM; it++){
                   10535:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10536:       }
                   10537:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10538:     }
                   10539:     
                   10540:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10541:     
                   10542:     gsl_vector_free(x); /* initial values */
                   10543:     gsl_vector_free(ss); /* inital step size */
                   10544:     for (it=0; it<NDIM; it++){
                   10545:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10546:       fprintf(ficrespow," %.12lf", p[it]);
                   10547:     }
                   10548:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10549: #endif
                   10550: #ifdef POWELL
                   10551:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10552: #endif  
1.126     brouard  10553:     fclose(ficrespow);
                   10554:     
1.203     brouard  10555:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10556: 
                   10557:     for(i=1; i <=NDIM; i++)
                   10558:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10559:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10560:     
                   10561:     printf("\nCovariance matrix\n ");
1.203     brouard  10562:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10563:     for(i=1; i <=NDIM; i++) {
                   10564:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10565:                                printf("%f ",matcov[i][j]);
                   10566:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10567:       }
1.203     brouard  10568:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10569:     }
                   10570:     
                   10571:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10572:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10573:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10574:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10575:     }
1.126     brouard  10576:     lsurv=vector(1,AGESUP);
                   10577:     lpop=vector(1,AGESUP);
                   10578:     tpop=vector(1,AGESUP);
                   10579:     lsurv[agegomp]=100000;
                   10580:     
                   10581:     for (k=agegomp;k<=AGESUP;k++) {
                   10582:       agemortsup=k;
                   10583:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10584:     }
                   10585:     
                   10586:     for (k=agegomp;k<agemortsup;k++)
                   10587:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10588:     
                   10589:     for (k=agegomp;k<agemortsup;k++){
                   10590:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10591:       sumlpop=sumlpop+lpop[k];
                   10592:     }
                   10593:     
                   10594:     tpop[agegomp]=sumlpop;
                   10595:     for (k=agegomp;k<(agemortsup-3);k++){
                   10596:       /*  tpop[k+1]=2;*/
                   10597:       tpop[k+1]=tpop[k]-lpop[k];
                   10598:     }
                   10599:     
                   10600:     
                   10601:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10602:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10603:       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]);
                   10604:     
                   10605:     
                   10606:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10607:                ageminpar=50;
                   10608:                agemaxpar=100;
1.194     brouard  10609:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10610:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10611: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10612: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10613:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10614: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10615: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10616:     }else{
                   10617:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10618:                        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  10619:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10620:                }
1.201     brouard  10621:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10622:                     stepm, weightopt,\
                   10623:                     model,imx,p,matcov,agemortsup);
                   10624:     
                   10625:     free_vector(lsurv,1,AGESUP);
                   10626:     free_vector(lpop,1,AGESUP);
                   10627:     free_vector(tpop,1,AGESUP);
1.220     brouard  10628:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10629:     free_ivector(cens,1,n);
                   10630:     free_vector(agecens,1,n);
                   10631:     free_ivector(dcwave,1,n);
1.220     brouard  10632: #ifdef GSL
1.136     brouard  10633: #endif
1.186     brouard  10634:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10635:   /* Standard  */
                   10636:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10637:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10638:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10639:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10640:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10641:     for (k=1; k<=npar;k++)
                   10642:       printf(" %d %8.5f",k,p[k]);
                   10643:     printf("\n");
1.205     brouard  10644:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10645:       /* mlikeli uses func not funcone */
                   10646:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10647:     }
                   10648:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10649:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10650:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10651:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10652:     }
                   10653:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10654:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10655:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10656:     for (k=1; k<=npar;k++)
                   10657:       printf(" %d %8.5f",k,p[k]);
                   10658:     printf("\n");
                   10659:     
                   10660:     /*--------- results files --------------*/
1.224     brouard  10661:     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  10662:     
                   10663:     
                   10664:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10665:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10666:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10667:     for(i=1,jk=1; i <=nlstate; i++){
                   10668:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10669:        if (k != i) {
                   10670:          printf("%d%d ",i,k);
                   10671:          fprintf(ficlog,"%d%d ",i,k);
                   10672:          fprintf(ficres,"%1d%1d ",i,k);
                   10673:          for(j=1; j <=ncovmodel; j++){
                   10674:            printf("%12.7f ",p[jk]);
                   10675:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10676:            fprintf(ficres,"%12.7f ",p[jk]);
                   10677:            jk++; 
                   10678:          }
                   10679:          printf("\n");
                   10680:          fprintf(ficlog,"\n");
                   10681:          fprintf(ficres,"\n");
                   10682:        }
1.126     brouard  10683:       }
                   10684:     }
1.203     brouard  10685:     if(mle != 0){
                   10686:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10687:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10688:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10689:       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");
                   10690:       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");
                   10691:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10692:        for(k=1; k <=(nlstate+ndeath); k++){
                   10693:          if (k != i) {
                   10694:            printf("%d%d ",i,k);
                   10695:            fprintf(ficlog,"%d%d ",i,k);
                   10696:            for(j=1; j <=ncovmodel; j++){
                   10697:              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]));
                   10698:              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]));
                   10699:              jk++; 
                   10700:            }
                   10701:            printf("\n");
                   10702:            fprintf(ficlog,"\n");
                   10703:          }
                   10704:        }
1.193     brouard  10705:       }
1.203     brouard  10706:     } /* end of hesscov and Wald tests */
1.225     brouard  10707:     
1.203     brouard  10708:     /*  */
1.126     brouard  10709:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10710:     printf("# Scales (for hessian or gradient estimation)\n");
                   10711:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10712:     for(i=1,jk=1; i <=nlstate; i++){
                   10713:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10714:        if (j!=i) {
                   10715:          fprintf(ficres,"%1d%1d",i,j);
                   10716:          printf("%1d%1d",i,j);
                   10717:          fprintf(ficlog,"%1d%1d",i,j);
                   10718:          for(k=1; k<=ncovmodel;k++){
                   10719:            printf(" %.5e",delti[jk]);
                   10720:            fprintf(ficlog," %.5e",delti[jk]);
                   10721:            fprintf(ficres," %.5e",delti[jk]);
                   10722:            jk++;
                   10723:          }
                   10724:          printf("\n");
                   10725:          fprintf(ficlog,"\n");
                   10726:          fprintf(ficres,"\n");
                   10727:        }
1.126     brouard  10728:       }
                   10729:     }
                   10730:     
                   10731:     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  10732:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10733:       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");
                   10734:     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");
                   10735:     /* # 121 Var(a12)\n\ */
                   10736:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10737:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10738:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10739:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10740:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10741:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10742:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10743:     
                   10744:     
                   10745:     /* Just to have a covariance matrix which will be more understandable
                   10746:        even is we still don't want to manage dictionary of variables
                   10747:     */
                   10748:     for(itimes=1;itimes<=2;itimes++){
                   10749:       jj=0;
                   10750:       for(i=1; i <=nlstate; i++){
1.225     brouard  10751:        for(j=1; j <=nlstate+ndeath; j++){
                   10752:          if(j==i) continue;
                   10753:          for(k=1; k<=ncovmodel;k++){
                   10754:            jj++;
                   10755:            ca[0]= k+'a'-1;ca[1]='\0';
                   10756:            if(itimes==1){
                   10757:              if(mle>=1)
                   10758:                printf("#%1d%1d%d",i,j,k);
                   10759:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10760:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10761:            }else{
                   10762:              if(mle>=1)
                   10763:                printf("%1d%1d%d",i,j,k);
                   10764:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10765:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10766:            }
                   10767:            ll=0;
                   10768:            for(li=1;li <=nlstate; li++){
                   10769:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10770:                if(lj==li) continue;
                   10771:                for(lk=1;lk<=ncovmodel;lk++){
                   10772:                  ll++;
                   10773:                  if(ll<=jj){
                   10774:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10775:                    if(ll<jj){
                   10776:                      if(itimes==1){
                   10777:                        if(mle>=1)
                   10778:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10779:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10780:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10781:                      }else{
                   10782:                        if(mle>=1)
                   10783:                          printf(" %.5e",matcov[jj][ll]); 
                   10784:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10785:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10786:                      }
                   10787:                    }else{
                   10788:                      if(itimes==1){
                   10789:                        if(mle>=1)
                   10790:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10791:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10792:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10793:                      }else{
                   10794:                        if(mle>=1)
                   10795:                          printf(" %.7e",matcov[jj][ll]); 
                   10796:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10797:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10798:                      }
                   10799:                    }
                   10800:                  }
                   10801:                } /* end lk */
                   10802:              } /* end lj */
                   10803:            } /* end li */
                   10804:            if(mle>=1)
                   10805:              printf("\n");
                   10806:            fprintf(ficlog,"\n");
                   10807:            fprintf(ficres,"\n");
                   10808:            numlinepar++;
                   10809:          } /* end k*/
                   10810:        } /*end j */
1.126     brouard  10811:       } /* end i */
                   10812:     } /* end itimes */
                   10813:     
                   10814:     fflush(ficlog);
                   10815:     fflush(ficres);
1.225     brouard  10816:     while(fgets(line, MAXLINE, ficpar)) {
                   10817:       /* If line starts with a # it is a comment */
                   10818:       if (line[0] == '#') {
                   10819:        numlinepar++;
                   10820:        fputs(line,stdout);
                   10821:        fputs(line,ficparo);
                   10822:        fputs(line,ficlog);
                   10823:        continue;
                   10824:       }else
                   10825:        break;
                   10826:     }
                   10827:     
1.209     brouard  10828:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10829:     /*   ungetc(c,ficpar); */
                   10830:     /*   fgets(line, MAXLINE, ficpar); */
                   10831:     /*   fputs(line,stdout); */
                   10832:     /*   fputs(line,ficparo); */
                   10833:     /* } */
                   10834:     /* ungetc(c,ficpar); */
1.126     brouard  10835:     
                   10836:     estepm=0;
1.209     brouard  10837:     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  10838:       
                   10839:       if (num_filled != 6) {
                   10840:        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);
                   10841:        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);
                   10842:        goto end;
                   10843:       }
                   10844:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10845:     }
                   10846:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10847:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10848:     
1.209     brouard  10849:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10850:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10851:     if (fage <= 2) {
                   10852:       bage = ageminpar;
                   10853:       fage = agemaxpar;
                   10854:     }
                   10855:     
                   10856:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10857:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10858:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10859:                
1.186     brouard  10860:     /* Other stuffs, more or less useful */    
1.126     brouard  10861:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10862:       ungetc(c,ficpar);
                   10863:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10864:       fputs(line,stdout);
1.126     brouard  10865:       fputs(line,ficparo);
                   10866:     }
                   10867:     ungetc(c,ficpar);
                   10868:     
                   10869:     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);
                   10870:     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);
                   10871:     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);
                   10872:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10873:     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);
                   10874:     
                   10875:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10876:       ungetc(c,ficpar);
                   10877:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10878:       fputs(line,stdout);
1.126     brouard  10879:       fputs(line,ficparo);
                   10880:     }
                   10881:     ungetc(c,ficpar);
                   10882:     
                   10883:     
                   10884:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10885:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10886:     
                   10887:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10888:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10889:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10890:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10891:     
                   10892:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10893:       ungetc(c,ficpar);
                   10894:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10895:       fputs(line,stdout);
1.238     brouard  10896:       fputs(line,ficres);
1.126     brouard  10897:       fputs(line,ficparo);
                   10898:     }
                   10899:     ungetc(c,ficpar);
                   10900:     
                   10901:     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);
                   10902:     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);
                   10903:     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);
                   10904:     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);
                   10905:     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);
                   10906:     /* day and month of proj2 are not used but only year anproj2.*/
                   10907:     
1.217     brouard  10908:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10909:       ungetc(c,ficpar);
                   10910:       fgets(line, MAXLINE, ficpar);
                   10911:       fputs(line,stdout);
                   10912:       fputs(line,ficparo);
1.238     brouard  10913:       fputs(line,ficres);
1.217     brouard  10914:     }
                   10915:     ungetc(c,ficpar);
                   10916:     
                   10917:     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  10918:     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);
                   10919:     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);
                   10920:     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  10921:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10922:     
1.230     brouard  10923:     /* Results */
1.235     brouard  10924:     nresult=0;
1.230     brouard  10925:     while(fgets(line, MAXLINE, ficpar)) {
                   10926:       /* If line starts with a # it is a comment */
                   10927:       if (line[0] == '#') {
                   10928:        numlinepar++;
                   10929:        fputs(line,stdout);
                   10930:        fputs(line,ficparo);
                   10931:        fputs(line,ficlog);
1.238     brouard  10932:        fputs(line,ficres);
1.230     brouard  10933:        continue;
                   10934:       }else
                   10935:        break;
                   10936:     }
1.240     brouard  10937:     if (!feof(ficpar))
1.230     brouard  10938:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240     brouard  10939:       if (num_filled == 0){
1.230     brouard  10940:        resultline[0]='\0';
1.240     brouard  10941:       break;
                   10942:       } else if (num_filled != 1){
1.230     brouard  10943:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10944:       }
1.235     brouard  10945:       nresult++; /* Sum of resultlines */
                   10946:       printf("Result %d: result=%s\n",nresult, resultline);
                   10947:       if(nresult > MAXRESULTLINES){
                   10948:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10949:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10950:        goto end;
                   10951:       }
                   10952:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  10953:       fprintf(ficparo,"result: %s\n",resultline);
                   10954:       fprintf(ficres,"result: %s\n",resultline);
                   10955:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  10956:       while(fgets(line, MAXLINE, ficpar)) {
                   10957:        /* If line starts with a # it is a comment */
                   10958:        if (line[0] == '#') {
                   10959:          numlinepar++;
                   10960:          fputs(line,stdout);
                   10961:          fputs(line,ficparo);
1.238     brouard  10962:          fputs(line,ficres);
1.230     brouard  10963:          fputs(line,ficlog);
                   10964:          continue;
                   10965:        }else
                   10966:          break;
                   10967:       }
                   10968:       if (feof(ficpar))
                   10969:        break;
                   10970:       else{ /* Processess output results for this combination of covariate values */
                   10971:       }                                   
1.240     brouard  10972:     } /* end while */
1.230     brouard  10973: 
                   10974: 
1.126     brouard  10975:     
1.230     brouard  10976:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10977:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10978:     
                   10979:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10980:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10981:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10982: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10983: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10984:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10985: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10986: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10987:     }else{
1.218     brouard  10988:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10989:     }
                   10990:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10991:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10992:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10993:                
1.225     brouard  10994:     /*------------ free_vector  -------------*/
                   10995:     /*  chdir(path); */
1.220     brouard  10996:                
1.215     brouard  10997:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10998:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10999:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   11000:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  11001:     free_lvector(num,1,n);
                   11002:     free_vector(agedc,1,n);
                   11003:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   11004:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   11005:     fclose(ficparo);
                   11006:     fclose(ficres);
1.220     brouard  11007:                
                   11008:                
1.186     brouard  11009:     /* Other results (useful)*/
1.220     brouard  11010:                
                   11011:                
1.126     brouard  11012:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11013:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11014:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11015:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11016:     fclose(ficrespl);
                   11017: 
                   11018:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11019:     /*#include "hpijx.h"*/
                   11020:     hPijx(p, bage, fage);
1.145     brouard  11021:     fclose(ficrespij);
1.227     brouard  11022:     
1.220     brouard  11023:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11024:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11025:     k=1;
1.126     brouard  11026:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11027:     
1.219     brouard  11028:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11029:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11030:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11031:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11032:        for(k=1;k<=ncovcombmax;k++)
                   11033:          probs[i][j][k]=0.;
1.219     brouard  11034:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11035:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11036:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11037:       for(i=1;i<=AGESUP;i++)
                   11038:        for(j=1;j<=nlstate;j++)
                   11039:          for(k=1;k<=ncovcombmax;k++)
                   11040:            mobaverages[i][j][k]=0.;
1.219     brouard  11041:       mobaverage=mobaverages;
                   11042:       if (mobilav!=0) {
1.235     brouard  11043:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  11044:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11045:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11046:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11047:        }
1.219     brouard  11048:       }
                   11049:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11050:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11051:       else if (mobilavproj !=0) {
1.235     brouard  11052:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  11053:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11054:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11055:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11056:        }
1.219     brouard  11057:       }
                   11058:     }/* end if moving average */
1.227     brouard  11059:     
1.126     brouard  11060:     /*---------- Forecasting ------------------*/
                   11061:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11062:     if(prevfcast==1){
                   11063:       /*    if(stepm ==1){*/
1.225     brouard  11064:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11065:     }
1.217     brouard  11066:     if(backcast==1){
1.219     brouard  11067:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11068:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11069:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11070: 
                   11071:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11072: 
                   11073:       bprlim=matrix(1,nlstate,1,nlstate);
                   11074:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11075:       fclose(ficresplb);
                   11076: 
1.222     brouard  11077:       hBijx(p, bage, fage, mobaverage);
                   11078:       fclose(ficrespijb);
1.219     brouard  11079:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11080: 
                   11081:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11082:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11083:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11084:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11085:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11086:     }
1.217     brouard  11087:     
1.186     brouard  11088:  
                   11089:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11090: 
1.215     brouard  11091:     free_ivector(wav,1,imx);
                   11092:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11093:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11094:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11095:                
                   11096:                
1.127     brouard  11097:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11098:                
1.201     brouard  11099:     strcpy(filerese,"E_");
                   11100:     strcat(filerese,fileresu);
1.126     brouard  11101:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11102:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11103:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11104:     }
1.208     brouard  11105:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11106:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11107: 
                   11108:     pstamp(ficreseij);
1.219     brouard  11109:                
1.235     brouard  11110:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11111:     if (cptcovn < 1){i1=1;}
                   11112:     
                   11113:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11114:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11115:       if(TKresult[nres]!= k)
                   11116:        continue;
1.219     brouard  11117:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11118:       printf("\n#****** ");
1.225     brouard  11119:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11120:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11121:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11122:       }
                   11123:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11124:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11125:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11126:       }
                   11127:       fprintf(ficreseij,"******\n");
1.235     brouard  11128:       printf("******\n");
1.219     brouard  11129:       
                   11130:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11131:       oldm=oldms;savm=savms;
1.235     brouard  11132:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11133:       
1.219     brouard  11134:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11135:     }
                   11136:     fclose(ficreseij);
1.208     brouard  11137:     printf("done evsij\n");fflush(stdout);
                   11138:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11139:                
1.227     brouard  11140:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11141:                
                   11142:                
1.201     brouard  11143:     strcpy(filerest,"T_");
                   11144:     strcat(filerest,fileresu);
1.127     brouard  11145:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11146:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11147:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11148:     }
1.208     brouard  11149:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11150:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11151:                
1.126     brouard  11152: 
1.201     brouard  11153:     strcpy(fileresstde,"STDE_");
                   11154:     strcat(fileresstde,fileresu);
1.126     brouard  11155:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11156:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11157:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11158:     }
1.227     brouard  11159:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11160:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11161: 
1.201     brouard  11162:     strcpy(filerescve,"CVE_");
                   11163:     strcat(filerescve,fileresu);
1.126     brouard  11164:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11165:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11166:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11167:     }
1.227     brouard  11168:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11169:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11170: 
1.201     brouard  11171:     strcpy(fileresv,"V_");
                   11172:     strcat(fileresv,fileresu);
1.126     brouard  11173:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11174:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11175:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11176:     }
1.227     brouard  11177:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11178:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11179: 
1.145     brouard  11180:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11181:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11182:           
1.235     brouard  11183:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11184:     if (cptcovn < 1){i1=1;}
                   11185:     
                   11186:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11187:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11188:       if(TKresult[nres]!= k)
                   11189:        continue;
1.242     brouard  11190:       printf("\n#****** Result for:");
                   11191:       fprintf(ficrest,"\n#****** Result for:");
                   11192:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11193:       for(j=1;j<=cptcoveff;j++){ 
                   11194:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11195:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11196:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11197:       }
1.235     brouard  11198:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11199:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11200:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11201:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11202:       }        
1.208     brouard  11203:       fprintf(ficrest,"******\n");
1.227     brouard  11204:       fprintf(ficlog,"******\n");
                   11205:       printf("******\n");
1.208     brouard  11206:       
                   11207:       fprintf(ficresstdeij,"\n#****** ");
                   11208:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11209:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11210:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11211:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11212:       }
1.235     brouard  11213:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11214:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11215:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11216:       }        
1.208     brouard  11217:       fprintf(ficresstdeij,"******\n");
                   11218:       fprintf(ficrescveij,"******\n");
                   11219:       
                   11220:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11221:       /* pstamp(ficresvij); */
1.225     brouard  11222:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11223:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11224:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11225:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11226:       }        
1.208     brouard  11227:       fprintf(ficresvij,"******\n");
                   11228:       
                   11229:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11230:       oldm=oldms;savm=savms;
1.235     brouard  11231:       printf(" cvevsij ");
                   11232:       fprintf(ficlog, " cvevsij ");
                   11233:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11234:       printf(" end cvevsij \n ");
                   11235:       fprintf(ficlog, " end cvevsij \n ");
                   11236:       
                   11237:       /*
                   11238:        */
                   11239:       /* goto endfree; */
                   11240:       
                   11241:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11242:       pstamp(ficrest);
                   11243:       
                   11244:       
                   11245:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11246:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11247:        cptcod= 0; /* To be deleted */
                   11248:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11249:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11250:        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  11251:        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 ");
                   11252:        if(vpopbased==1)
                   11253:          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);
                   11254:        else
                   11255:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11256:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11257:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11258:        fprintf(ficrest,"\n");
                   11259:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11260:        epj=vector(1,nlstate+1);
                   11261:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11262:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11263:        for(age=bage; age <=fage ;age++){
1.235     brouard  11264:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11265:          if (vpopbased==1) {
                   11266:            if(mobilav ==0){
                   11267:              for(i=1; i<=nlstate;i++)
                   11268:                prlim[i][i]=probs[(int)age][i][k];
                   11269:            }else{ /* mobilav */ 
                   11270:              for(i=1; i<=nlstate;i++)
                   11271:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11272:            }
                   11273:          }
1.219     brouard  11274:          
1.227     brouard  11275:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11276:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11277:          /* printf(" age %4.0f ",age); */
                   11278:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11279:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11280:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11281:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11282:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11283:            }
                   11284:            epj[nlstate+1] +=epj[j];
                   11285:          }
                   11286:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11287:          
1.227     brouard  11288:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11289:            for(j=1;j <=nlstate;j++)
                   11290:              vepp += vareij[i][j][(int)age];
                   11291:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11292:          for(j=1;j <=nlstate;j++){
                   11293:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11294:          }
                   11295:          fprintf(ficrest,"\n");
                   11296:        }
1.208     brouard  11297:       } /* End vpopbased */
                   11298:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11299:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11300:       free_vector(epj,1,nlstate+1);
1.235     brouard  11301:       printf("done selection\n");fflush(stdout);
                   11302:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11303:       
1.145     brouard  11304:       /*}*/
1.235     brouard  11305:     } /* End k selection */
1.227     brouard  11306: 
                   11307:     printf("done State-specific expectancies\n");fflush(stdout);
                   11308:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11309: 
1.126     brouard  11310:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11311:     
1.201     brouard  11312:     strcpy(fileresvpl,"VPL_");
                   11313:     strcat(fileresvpl,fileresu);
1.126     brouard  11314:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11315:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11316:       exit(0);
                   11317:     }
1.208     brouard  11318:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11319:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11320:     
1.145     brouard  11321:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11322:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11323:     
1.235     brouard  11324:     i1=pow(2,cptcoveff);
                   11325:     if (cptcovn < 1){i1=1;}
                   11326: 
                   11327:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11328:     for(k=1; k<=i1;k++){
                   11329:       if(TKresult[nres]!= k)
                   11330:        continue;
1.227     brouard  11331:       fprintf(ficresvpl,"\n#****** ");
                   11332:       printf("\n#****** ");
                   11333:       fprintf(ficlog,"\n#****** ");
                   11334:       for(j=1;j<=cptcoveff;j++) {
                   11335:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11336:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11337:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11338:       }
1.235     brouard  11339:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11340:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11341:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11342:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11343:       }        
1.227     brouard  11344:       fprintf(ficresvpl,"******\n");
                   11345:       printf("******\n");
                   11346:       fprintf(ficlog,"******\n");
                   11347:       
                   11348:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11349:       oldm=oldms;savm=savms;
1.235     brouard  11350:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11351:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11352:       /*}*/
1.126     brouard  11353:     }
1.227     brouard  11354:     
1.126     brouard  11355:     fclose(ficresvpl);
1.208     brouard  11356:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11357:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11358:     
                   11359:     free_vector(weight,1,n);
                   11360:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11361:     free_imatrix(s,1,maxwav+1,1,n);
                   11362:     free_matrix(anint,1,maxwav,1,n); 
                   11363:     free_matrix(mint,1,maxwav,1,n);
                   11364:     free_ivector(cod,1,n);
                   11365:     free_ivector(tab,1,NCOVMAX);
                   11366:     fclose(ficresstdeij);
                   11367:     fclose(ficrescveij);
                   11368:     fclose(ficresvij);
                   11369:     fclose(ficrest);
                   11370:     fclose(ficpar);
                   11371:     
                   11372:     
1.126     brouard  11373:     /*---------- End : free ----------------*/
1.219     brouard  11374:     if (mobilav!=0 ||mobilavproj !=0)
                   11375:       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  11376:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11377:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11378:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11379:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11380:   /* endfree:*/
                   11381:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11382:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11383:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11384:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11385:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11386:   free_matrix(coqvar,1,maxwav,1,n);
                   11387:   free_matrix(covar,0,NCOVMAX,1,n);
                   11388:   free_matrix(matcov,1,npar,1,npar);
                   11389:   free_matrix(hess,1,npar,1,npar);
                   11390:   /*free_vector(delti,1,npar);*/
                   11391:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11392:   free_matrix(agev,1,maxwav,1,imx);
                   11393:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11394:   
                   11395:   free_ivector(ncodemax,1,NCOVMAX);
                   11396:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11397:   free_ivector(Dummy,-1,NCOVMAX);
                   11398:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11399:   free_ivector(DummyV,1,NCOVMAX);
                   11400:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11401:   free_ivector(Typevar,-1,NCOVMAX);
                   11402:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11403:   free_ivector(TvarsQ,1,NCOVMAX);
                   11404:   free_ivector(TvarsQind,1,NCOVMAX);
                   11405:   free_ivector(TvarsD,1,NCOVMAX);
                   11406:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11407:   free_ivector(TvarFD,1,NCOVMAX);
                   11408:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11409:   free_ivector(TvarF,1,NCOVMAX);
                   11410:   free_ivector(TvarFind,1,NCOVMAX);
                   11411:   free_ivector(TvarV,1,NCOVMAX);
                   11412:   free_ivector(TvarVind,1,NCOVMAX);
                   11413:   free_ivector(TvarA,1,NCOVMAX);
                   11414:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11415:   free_ivector(TvarFQ,1,NCOVMAX);
                   11416:   free_ivector(TvarFQind,1,NCOVMAX);
                   11417:   free_ivector(TvarVD,1,NCOVMAX);
                   11418:   free_ivector(TvarVDind,1,NCOVMAX);
                   11419:   free_ivector(TvarVQ,1,NCOVMAX);
                   11420:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11421:   free_ivector(Tvarsel,1,NCOVMAX);
                   11422:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11423:   free_ivector(Tposprod,1,NCOVMAX);
                   11424:   free_ivector(Tprod,1,NCOVMAX);
                   11425:   free_ivector(Tvaraff,1,NCOVMAX);
                   11426:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11427:   free_ivector(Tage,1,NCOVMAX);
                   11428:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11429:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11430:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11431:   
                   11432:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11433:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11434:   fflush(fichtm);
                   11435:   fflush(ficgp);
                   11436:   
1.227     brouard  11437:   
1.126     brouard  11438:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11439:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11440:     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  11441:   }else{
                   11442:     printf("End of Imach\n");
                   11443:     fprintf(ficlog,"End of Imach\n");
                   11444:   }
                   11445:   printf("See log file on %s\n",filelog);
                   11446:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11447:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11448:   rend_time = time(NULL);  
                   11449:   end_time = *localtime(&rend_time);
                   11450:   /* tml = *localtime(&end_time.tm_sec); */
                   11451:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11452:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11453:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11454:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11455:   
1.157     brouard  11456:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11457:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11458:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11459:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11460: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11461:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11462:   fclose(fichtm);
                   11463:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11464:   fclose(fichtmcov);
                   11465:   fclose(ficgp);
                   11466:   fclose(ficlog);
                   11467:   /*------ End -----------*/
1.227     brouard  11468:   
                   11469:   
                   11470:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11471: #ifdef WIN32
1.227     brouard  11472:   if (_chdir(pathcd) != 0)
                   11473:     printf("Can't move to directory %s!\n",path);
                   11474:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11475: #else
1.227     brouard  11476:     if(chdir(pathcd) != 0)
                   11477:       printf("Can't move to directory %s!\n", path);
                   11478:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11479: #endif 
1.126     brouard  11480:     printf("Current directory %s!\n",pathcd);
                   11481:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11482:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11483: #ifdef _WIN32
1.126     brouard  11484:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11485: #endif
                   11486:   if(!stat(plotcmd,&info)){
1.158     brouard  11487:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11488:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11489:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11490:     }else
                   11491:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11492: #ifdef __unix
1.126     brouard  11493:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11494:     if(!stat(plotcmd,&info)){
1.158     brouard  11495:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11496:     }else
                   11497:       strcpy(pplotcmd,plotcmd);
                   11498: #endif
                   11499:   }else
                   11500:     strcpy(pplotcmd,plotcmd);
                   11501:   
                   11502:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11503:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11504:   
1.126     brouard  11505:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11506:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11507:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11508:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11509:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11510:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11511:   }
1.158     brouard  11512:   printf(" Successful, please wait...");
1.126     brouard  11513:   while (z[0] != 'q') {
                   11514:     /* chdir(path); */
1.154     brouard  11515:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11516:     scanf("%s",z);
                   11517: /*     if (z[0] == 'c') system("./imach"); */
                   11518:     if (z[0] == 'e') {
1.158     brouard  11519: #ifdef __APPLE__
1.152     brouard  11520:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11521: #elif __linux
                   11522:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11523: #else
1.152     brouard  11524:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11525: #endif
                   11526:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11527:       system(pplotcmd);
1.126     brouard  11528:     }
                   11529:     else if (z[0] == 'g') system(plotcmd);
                   11530:     else if (z[0] == 'q') exit(0);
                   11531:   }
1.227     brouard  11532: end:
1.126     brouard  11533:   while (z[0] != 'q') {
1.195     brouard  11534:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11535:     scanf("%s",z);
                   11536:   }
                   11537: }

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