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

1.240   ! brouard     1: /* $Id: imach.c,v 1.239 2016/08/26 15:51:03 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.240   ! brouard     4:   Revision 1.239  2016/08/26 15:51:03  brouard
        !             5:   Summary: Improvement in Powell output in order to copy and paste
        !             6: 
        !             7:   Author:
        !             8: 
1.239     brouard     9:   Revision 1.238  2016/08/26 14:23:35  brouard
                     10:   Summary: Starting tests of 0.99
                     11: 
1.238     brouard    12:   Revision 1.237  2016/08/26 09:20:19  brouard
                     13:   Summary: to valgrind
                     14: 
1.237     brouard    15:   Revision 1.236  2016/08/25 10:50:18  brouard
                     16:   *** empty log message ***
                     17: 
1.236     brouard    18:   Revision 1.235  2016/08/25 06:59:23  brouard
                     19:   *** empty log message ***
                     20: 
1.235     brouard    21:   Revision 1.234  2016/08/23 16:51:20  brouard
                     22:   *** empty log message ***
                     23: 
1.234     brouard    24:   Revision 1.233  2016/08/23 07:40:50  brouard
                     25:   Summary: not working
                     26: 
1.233     brouard    27:   Revision 1.232  2016/08/22 14:20:21  brouard
                     28:   Summary: not working
                     29: 
1.232     brouard    30:   Revision 1.231  2016/08/22 07:17:15  brouard
                     31:   Summary: not working
                     32: 
1.231     brouard    33:   Revision 1.230  2016/08/22 06:55:53  brouard
                     34:   Summary: Not working
                     35: 
1.230     brouard    36:   Revision 1.229  2016/07/23 09:45:53  brouard
                     37:   Summary: Completing for func too
                     38: 
1.229     brouard    39:   Revision 1.228  2016/07/22 17:45:30  brouard
                     40:   Summary: Fixing some arrays, still debugging
                     41: 
1.227     brouard    42:   Revision 1.226  2016/07/12 18:42:34  brouard
                     43:   Summary: temp
                     44: 
1.226     brouard    45:   Revision 1.225  2016/07/12 08:40:03  brouard
                     46:   Summary: saving but not running
                     47: 
1.225     brouard    48:   Revision 1.224  2016/07/01 13:16:01  brouard
                     49:   Summary: Fixes
                     50: 
1.224     brouard    51:   Revision 1.223  2016/02/19 09:23:35  brouard
                     52:   Summary: temporary
                     53: 
1.223     brouard    54:   Revision 1.222  2016/02/17 08:14:50  brouard
                     55:   Summary: Probably last 0.98 stable version 0.98r6
                     56: 
1.222     brouard    57:   Revision 1.221  2016/02/15 23:35:36  brouard
                     58:   Summary: minor bug
                     59: 
1.220     brouard    60:   Revision 1.219  2016/02/15 00:48:12  brouard
                     61:   *** empty log message ***
                     62: 
1.219     brouard    63:   Revision 1.218  2016/02/12 11:29:23  brouard
                     64:   Summary: 0.99 Back projections
                     65: 
1.218     brouard    66:   Revision 1.217  2015/12/23 17:18:31  brouard
                     67:   Summary: Experimental backcast
                     68: 
1.217     brouard    69:   Revision 1.216  2015/12/18 17:32:11  brouard
                     70:   Summary: 0.98r4 Warning and status=-2
                     71: 
                     72:   Version 0.98r4 is now:
                     73:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     74:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     75:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     76: 
1.216     brouard    77:   Revision 1.215  2015/12/16 08:52:24  brouard
                     78:   Summary: 0.98r4 working
                     79: 
1.215     brouard    80:   Revision 1.214  2015/12/16 06:57:54  brouard
                     81:   Summary: temporary not working
                     82: 
1.214     brouard    83:   Revision 1.213  2015/12/11 18:22:17  brouard
                     84:   Summary: 0.98r4
                     85: 
1.213     brouard    86:   Revision 1.212  2015/11/21 12:47:24  brouard
                     87:   Summary: minor typo
                     88: 
1.212     brouard    89:   Revision 1.211  2015/11/21 12:41:11  brouard
                     90:   Summary: 0.98r3 with some graph of projected cross-sectional
                     91: 
                     92:   Author: Nicolas Brouard
                     93: 
1.211     brouard    94:   Revision 1.210  2015/11/18 17:41:20  brouard
                     95:   Summary: Start working on projected prevalences
                     96: 
1.210     brouard    97:   Revision 1.209  2015/11/17 22:12:03  brouard
                     98:   Summary: Adding ftolpl parameter
                     99:   Author: N Brouard
                    100: 
                    101:   We had difficulties to get smoothed confidence intervals. It was due
                    102:   to the period prevalence which wasn't computed accurately. The inner
                    103:   parameter ftolpl is now an outer parameter of the .imach parameter
                    104:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    105:   computation are long.
                    106: 
1.209     brouard   107:   Revision 1.208  2015/11/17 14:31:57  brouard
                    108:   Summary: temporary
                    109: 
1.208     brouard   110:   Revision 1.207  2015/10/27 17:36:57  brouard
                    111:   *** empty log message ***
                    112: 
1.207     brouard   113:   Revision 1.206  2015/10/24 07:14:11  brouard
                    114:   *** empty log message ***
                    115: 
1.206     brouard   116:   Revision 1.205  2015/10/23 15:50:53  brouard
                    117:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    118: 
1.205     brouard   119:   Revision 1.204  2015/10/01 16:20:26  brouard
                    120:   Summary: Some new graphs of contribution to likelihood
                    121: 
1.204     brouard   122:   Revision 1.203  2015/09/30 17:45:14  brouard
                    123:   Summary: looking at better estimation of the hessian
                    124: 
                    125:   Also a better criteria for convergence to the period prevalence And
                    126:   therefore adding the number of years needed to converge. (The
                    127:   prevalence in any alive state shold sum to one
                    128: 
1.203     brouard   129:   Revision 1.202  2015/09/22 19:45:16  brouard
                    130:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    131: 
1.202     brouard   132:   Revision 1.201  2015/09/15 17:34:58  brouard
                    133:   Summary: 0.98r0
                    134: 
                    135:   - Some new graphs like suvival functions
                    136:   - Some bugs fixed like model=1+age+V2.
                    137: 
1.201     brouard   138:   Revision 1.200  2015/09/09 16:53:55  brouard
                    139:   Summary: Big bug thanks to Flavia
                    140: 
                    141:   Even model=1+age+V2. did not work anymore
                    142: 
1.200     brouard   143:   Revision 1.199  2015/09/07 14:09:23  brouard
                    144:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    145: 
1.199     brouard   146:   Revision 1.198  2015/09/03 07:14:39  brouard
                    147:   Summary: 0.98q5 Flavia
                    148: 
1.198     brouard   149:   Revision 1.197  2015/09/01 18:24:39  brouard
                    150:   *** empty log message ***
                    151: 
1.197     brouard   152:   Revision 1.196  2015/08/18 23:17:52  brouard
                    153:   Summary: 0.98q5
                    154: 
1.196     brouard   155:   Revision 1.195  2015/08/18 16:28:39  brouard
                    156:   Summary: Adding a hack for testing purpose
                    157: 
                    158:   After reading the title, ftol and model lines, if the comment line has
                    159:   a q, starting with #q, the answer at the end of the run is quit. It
                    160:   permits to run test files in batch with ctest. The former workaround was
                    161:   $ echo q | imach foo.imach
                    162: 
1.195     brouard   163:   Revision 1.194  2015/08/18 13:32:00  brouard
                    164:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    165: 
1.194     brouard   166:   Revision 1.193  2015/08/04 07:17:42  brouard
                    167:   Summary: 0.98q4
                    168: 
1.193     brouard   169:   Revision 1.192  2015/07/16 16:49:02  brouard
                    170:   Summary: Fixing some outputs
                    171: 
1.192     brouard   172:   Revision 1.191  2015/07/14 10:00:33  brouard
                    173:   Summary: Some fixes
                    174: 
1.191     brouard   175:   Revision 1.190  2015/05/05 08:51:13  brouard
                    176:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    177: 
                    178:   Fix 1+age+.
                    179: 
1.190     brouard   180:   Revision 1.189  2015/04/30 14:45:16  brouard
                    181:   Summary: 0.98q2
                    182: 
1.189     brouard   183:   Revision 1.188  2015/04/30 08:27:53  brouard
                    184:   *** empty log message ***
                    185: 
1.188     brouard   186:   Revision 1.187  2015/04/29 09:11:15  brouard
                    187:   *** empty log message ***
                    188: 
1.187     brouard   189:   Revision 1.186  2015/04/23 12:01:52  brouard
                    190:   Summary: V1*age is working now, version 0.98q1
                    191: 
                    192:   Some codes had been disabled in order to simplify and Vn*age was
                    193:   working in the optimization phase, ie, giving correct MLE parameters,
                    194:   but, as usual, outputs were not correct and program core dumped.
                    195: 
1.186     brouard   196:   Revision 1.185  2015/03/11 13:26:42  brouard
                    197:   Summary: Inclusion of compile and links command line for Intel Compiler
                    198: 
1.185     brouard   199:   Revision 1.184  2015/03/11 11:52:39  brouard
                    200:   Summary: Back from Windows 8. Intel Compiler
                    201: 
1.184     brouard   202:   Revision 1.183  2015/03/10 20:34:32  brouard
                    203:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    204: 
                    205:   We use directest instead of original Powell test; probably no
                    206:   incidence on the results, but better justifications;
                    207:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    208:   wrong results.
                    209: 
1.183     brouard   210:   Revision 1.182  2015/02/12 08:19:57  brouard
                    211:   Summary: Trying to keep directest which seems simpler and more general
                    212:   Author: Nicolas Brouard
                    213: 
1.182     brouard   214:   Revision 1.181  2015/02/11 23:22:24  brouard
                    215:   Summary: Comments on Powell added
                    216: 
                    217:   Author:
                    218: 
1.181     brouard   219:   Revision 1.180  2015/02/11 17:33:45  brouard
                    220:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    221: 
1.180     brouard   222:   Revision 1.179  2015/01/04 09:57:06  brouard
                    223:   Summary: back to OS/X
                    224: 
1.179     brouard   225:   Revision 1.178  2015/01/04 09:35:48  brouard
                    226:   *** empty log message ***
                    227: 
1.178     brouard   228:   Revision 1.177  2015/01/03 18:40:56  brouard
                    229:   Summary: Still testing ilc32 on OSX
                    230: 
1.177     brouard   231:   Revision 1.176  2015/01/03 16:45:04  brouard
                    232:   *** empty log message ***
                    233: 
1.176     brouard   234:   Revision 1.175  2015/01/03 16:33:42  brouard
                    235:   *** empty log message ***
                    236: 
1.175     brouard   237:   Revision 1.174  2015/01/03 16:15:49  brouard
                    238:   Summary: Still in cross-compilation
                    239: 
1.174     brouard   240:   Revision 1.173  2015/01/03 12:06:26  brouard
                    241:   Summary: trying to detect cross-compilation
                    242: 
1.173     brouard   243:   Revision 1.172  2014/12/27 12:07:47  brouard
                    244:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    245: 
1.172     brouard   246:   Revision 1.171  2014/12/23 13:26:59  brouard
                    247:   Summary: Back from Visual C
                    248: 
                    249:   Still problem with utsname.h on Windows
                    250: 
1.171     brouard   251:   Revision 1.170  2014/12/23 11:17:12  brouard
                    252:   Summary: Cleaning some \%% back to %%
                    253: 
                    254:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    255: 
1.170     brouard   256:   Revision 1.169  2014/12/22 23:08:31  brouard
                    257:   Summary: 0.98p
                    258: 
                    259:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    260: 
1.169     brouard   261:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   262:   Summary: update
1.169     brouard   263: 
1.168     brouard   264:   Revision 1.167  2014/12/22 13:50:56  brouard
                    265:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    266: 
                    267:   Testing on Linux 64
                    268: 
1.167     brouard   269:   Revision 1.166  2014/12/22 11:40:47  brouard
                    270:   *** empty log message ***
                    271: 
1.166     brouard   272:   Revision 1.165  2014/12/16 11:20:36  brouard
                    273:   Summary: After compiling on Visual C
                    274: 
                    275:   * imach.c (Module): Merging 1.61 to 1.162
                    276: 
1.165     brouard   277:   Revision 1.164  2014/12/16 10:52:11  brouard
                    278:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    279: 
                    280:   * imach.c (Module): Merging 1.61 to 1.162
                    281: 
1.164     brouard   282:   Revision 1.163  2014/12/16 10:30:11  brouard
                    283:   * imach.c (Module): Merging 1.61 to 1.162
                    284: 
1.163     brouard   285:   Revision 1.162  2014/09/25 11:43:39  brouard
                    286:   Summary: temporary backup 0.99!
                    287: 
1.162     brouard   288:   Revision 1.1  2014/09/16 11:06:58  brouard
                    289:   Summary: With some code (wrong) for nlopt
                    290: 
                    291:   Author:
                    292: 
                    293:   Revision 1.161  2014/09/15 20:41:41  brouard
                    294:   Summary: Problem with macro SQR on Intel compiler
                    295: 
1.161     brouard   296:   Revision 1.160  2014/09/02 09:24:05  brouard
                    297:   *** empty log message ***
                    298: 
1.160     brouard   299:   Revision 1.159  2014/09/01 10:34:10  brouard
                    300:   Summary: WIN32
                    301:   Author: Brouard
                    302: 
1.159     brouard   303:   Revision 1.158  2014/08/27 17:11:51  brouard
                    304:   *** empty log message ***
                    305: 
1.158     brouard   306:   Revision 1.157  2014/08/27 16:26:55  brouard
                    307:   Summary: Preparing windows Visual studio version
                    308:   Author: Brouard
                    309: 
                    310:   In order to compile on Visual studio, time.h is now correct and time_t
                    311:   and tm struct should be used. difftime should be used but sometimes I
                    312:   just make the differences in raw time format (time(&now).
                    313:   Trying to suppress #ifdef LINUX
                    314:   Add xdg-open for __linux in order to open default browser.
                    315: 
1.157     brouard   316:   Revision 1.156  2014/08/25 20:10:10  brouard
                    317:   *** empty log message ***
                    318: 
1.156     brouard   319:   Revision 1.155  2014/08/25 18:32:34  brouard
                    320:   Summary: New compile, minor changes
                    321:   Author: Brouard
                    322: 
1.155     brouard   323:   Revision 1.154  2014/06/20 17:32:08  brouard
                    324:   Summary: Outputs now all graphs of convergence to period prevalence
                    325: 
1.154     brouard   326:   Revision 1.153  2014/06/20 16:45:46  brouard
                    327:   Summary: If 3 live state, convergence to period prevalence on same graph
                    328:   Author: Brouard
                    329: 
1.153     brouard   330:   Revision 1.152  2014/06/18 17:54:09  brouard
                    331:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    332: 
1.152     brouard   333:   Revision 1.151  2014/06/18 16:43:30  brouard
                    334:   *** empty log message ***
                    335: 
1.151     brouard   336:   Revision 1.150  2014/06/18 16:42:35  brouard
                    337:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    338:   Author: brouard
                    339: 
1.150     brouard   340:   Revision 1.149  2014/06/18 15:51:14  brouard
                    341:   Summary: Some fixes in parameter files errors
                    342:   Author: Nicolas Brouard
                    343: 
1.149     brouard   344:   Revision 1.148  2014/06/17 17:38:48  brouard
                    345:   Summary: Nothing new
                    346:   Author: Brouard
                    347: 
                    348:   Just a new packaging for OS/X version 0.98nS
                    349: 
1.148     brouard   350:   Revision 1.147  2014/06/16 10:33:11  brouard
                    351:   *** empty log message ***
                    352: 
1.147     brouard   353:   Revision 1.146  2014/06/16 10:20:28  brouard
                    354:   Summary: Merge
                    355:   Author: Brouard
                    356: 
                    357:   Merge, before building revised version.
                    358: 
1.146     brouard   359:   Revision 1.145  2014/06/10 21:23:15  brouard
                    360:   Summary: Debugging with valgrind
                    361:   Author: Nicolas Brouard
                    362: 
                    363:   Lot of changes in order to output the results with some covariates
                    364:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    365:   improve the code.
                    366:   No more memory valgrind error but a lot has to be done in order to
                    367:   continue the work of splitting the code into subroutines.
                    368:   Also, decodemodel has been improved. Tricode is still not
                    369:   optimal. nbcode should be improved. Documentation has been added in
                    370:   the source code.
                    371: 
1.144     brouard   372:   Revision 1.143  2014/01/26 09:45:38  brouard
                    373:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    374: 
                    375:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    376:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    377: 
1.143     brouard   378:   Revision 1.142  2014/01/26 03:57:36  brouard
                    379:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    380: 
                    381:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    382: 
1.142     brouard   383:   Revision 1.141  2014/01/26 02:42:01  brouard
                    384:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    385: 
1.141     brouard   386:   Revision 1.140  2011/09/02 10:37:54  brouard
                    387:   Summary: times.h is ok with mingw32 now.
                    388: 
1.140     brouard   389:   Revision 1.139  2010/06/14 07:50:17  brouard
                    390:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    391:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    392: 
1.139     brouard   393:   Revision 1.138  2010/04/30 18:19:40  brouard
                    394:   *** empty log message ***
                    395: 
1.138     brouard   396:   Revision 1.137  2010/04/29 18:11:38  brouard
                    397:   (Module): Checking covariates for more complex models
                    398:   than V1+V2. A lot of change to be done. Unstable.
                    399: 
1.137     brouard   400:   Revision 1.136  2010/04/26 20:30:53  brouard
                    401:   (Module): merging some libgsl code. Fixing computation
                    402:   of likelione (using inter/intrapolation if mle = 0) in order to
                    403:   get same likelihood as if mle=1.
                    404:   Some cleaning of code and comments added.
                    405: 
1.136     brouard   406:   Revision 1.135  2009/10/29 15:33:14  brouard
                    407:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    408: 
1.135     brouard   409:   Revision 1.134  2009/10/29 13:18:53  brouard
                    410:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    411: 
1.134     brouard   412:   Revision 1.133  2009/07/06 10:21:25  brouard
                    413:   just nforces
                    414: 
1.133     brouard   415:   Revision 1.132  2009/07/06 08:22:05  brouard
                    416:   Many tings
                    417: 
1.132     brouard   418:   Revision 1.131  2009/06/20 16:22:47  brouard
                    419:   Some dimensions resccaled
                    420: 
1.131     brouard   421:   Revision 1.130  2009/05/26 06:44:34  brouard
                    422:   (Module): Max Covariate is now set to 20 instead of 8. A
                    423:   lot of cleaning with variables initialized to 0. Trying to make
                    424:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    425: 
1.130     brouard   426:   Revision 1.129  2007/08/31 13:49:27  lievre
                    427:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    428: 
1.129     lievre    429:   Revision 1.128  2006/06/30 13:02:05  brouard
                    430:   (Module): Clarifications on computing e.j
                    431: 
1.128     brouard   432:   Revision 1.127  2006/04/28 18:11:50  brouard
                    433:   (Module): Yes the sum of survivors was wrong since
                    434:   imach-114 because nhstepm was no more computed in the age
                    435:   loop. Now we define nhstepma in the age loop.
                    436:   (Module): In order to speed up (in case of numerous covariates) we
                    437:   compute health expectancies (without variances) in a first step
                    438:   and then all the health expectancies with variances or standard
                    439:   deviation (needs data from the Hessian matrices) which slows the
                    440:   computation.
                    441:   In the future we should be able to stop the program is only health
                    442:   expectancies and graph are needed without standard deviations.
                    443: 
1.127     brouard   444:   Revision 1.126  2006/04/28 17:23:28  brouard
                    445:   (Module): Yes the sum of survivors was wrong since
                    446:   imach-114 because nhstepm was no more computed in the age
                    447:   loop. Now we define nhstepma in the age loop.
                    448:   Version 0.98h
                    449: 
1.126     brouard   450:   Revision 1.125  2006/04/04 15:20:31  lievre
                    451:   Errors in calculation of health expectancies. Age was not initialized.
                    452:   Forecasting file added.
                    453: 
                    454:   Revision 1.124  2006/03/22 17:13:53  lievre
                    455:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    456:   The log-likelihood is printed in the log file
                    457: 
                    458:   Revision 1.123  2006/03/20 10:52:43  brouard
                    459:   * imach.c (Module): <title> changed, corresponds to .htm file
                    460:   name. <head> headers where missing.
                    461: 
                    462:   * imach.c (Module): Weights can have a decimal point as for
                    463:   English (a comma might work with a correct LC_NUMERIC environment,
                    464:   otherwise the weight is truncated).
                    465:   Modification of warning when the covariates values are not 0 or
                    466:   1.
                    467:   Version 0.98g
                    468: 
                    469:   Revision 1.122  2006/03/20 09:45:41  brouard
                    470:   (Module): Weights can have a decimal point as for
                    471:   English (a comma might work with a correct LC_NUMERIC environment,
                    472:   otherwise the weight is truncated).
                    473:   Modification of warning when the covariates values are not 0 or
                    474:   1.
                    475:   Version 0.98g
                    476: 
                    477:   Revision 1.121  2006/03/16 17:45:01  lievre
                    478:   * imach.c (Module): Comments concerning covariates added
                    479: 
                    480:   * imach.c (Module): refinements in the computation of lli if
                    481:   status=-2 in order to have more reliable computation if stepm is
                    482:   not 1 month. Version 0.98f
                    483: 
                    484:   Revision 1.120  2006/03/16 15:10:38  lievre
                    485:   (Module): refinements in the computation of lli if
                    486:   status=-2 in order to have more reliable computation if stepm is
                    487:   not 1 month. Version 0.98f
                    488: 
                    489:   Revision 1.119  2006/03/15 17:42:26  brouard
                    490:   (Module): Bug if status = -2, the loglikelihood was
                    491:   computed as likelihood omitting the logarithm. Version O.98e
                    492: 
                    493:   Revision 1.118  2006/03/14 18:20:07  brouard
                    494:   (Module): varevsij Comments added explaining the second
                    495:   table of variances if popbased=1 .
                    496:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    497:   (Module): Function pstamp added
                    498:   (Module): Version 0.98d
                    499: 
                    500:   Revision 1.117  2006/03/14 17:16:22  brouard
                    501:   (Module): varevsij Comments added explaining the second
                    502:   table of variances if popbased=1 .
                    503:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    504:   (Module): Function pstamp added
                    505:   (Module): Version 0.98d
                    506: 
                    507:   Revision 1.116  2006/03/06 10:29:27  brouard
                    508:   (Module): Variance-covariance wrong links and
                    509:   varian-covariance of ej. is needed (Saito).
                    510: 
                    511:   Revision 1.115  2006/02/27 12:17:45  brouard
                    512:   (Module): One freematrix added in mlikeli! 0.98c
                    513: 
                    514:   Revision 1.114  2006/02/26 12:57:58  brouard
                    515:   (Module): Some improvements in processing parameter
                    516:   filename with strsep.
                    517: 
                    518:   Revision 1.113  2006/02/24 14:20:24  brouard
                    519:   (Module): Memory leaks checks with valgrind and:
                    520:   datafile was not closed, some imatrix were not freed and on matrix
                    521:   allocation too.
                    522: 
                    523:   Revision 1.112  2006/01/30 09:55:26  brouard
                    524:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    525: 
                    526:   Revision 1.111  2006/01/25 20:38:18  brouard
                    527:   (Module): Lots of cleaning and bugs added (Gompertz)
                    528:   (Module): Comments can be added in data file. Missing date values
                    529:   can be a simple dot '.'.
                    530: 
                    531:   Revision 1.110  2006/01/25 00:51:50  brouard
                    532:   (Module): Lots of cleaning and bugs added (Gompertz)
                    533: 
                    534:   Revision 1.109  2006/01/24 19:37:15  brouard
                    535:   (Module): Comments (lines starting with a #) are allowed in data.
                    536: 
                    537:   Revision 1.108  2006/01/19 18:05:42  lievre
                    538:   Gnuplot problem appeared...
                    539:   To be fixed
                    540: 
                    541:   Revision 1.107  2006/01/19 16:20:37  brouard
                    542:   Test existence of gnuplot in imach path
                    543: 
                    544:   Revision 1.106  2006/01/19 13:24:36  brouard
                    545:   Some cleaning and links added in html output
                    546: 
                    547:   Revision 1.105  2006/01/05 20:23:19  lievre
                    548:   *** empty log message ***
                    549: 
                    550:   Revision 1.104  2005/09/30 16:11:43  lievre
                    551:   (Module): sump fixed, loop imx fixed, and simplifications.
                    552:   (Module): If the status is missing at the last wave but we know
                    553:   that the person is alive, then we can code his/her status as -2
                    554:   (instead of missing=-1 in earlier versions) and his/her
                    555:   contributions to the likelihood is 1 - Prob of dying from last
                    556:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    557:   the healthy state at last known wave). Version is 0.98
                    558: 
                    559:   Revision 1.103  2005/09/30 15:54:49  lievre
                    560:   (Module): sump fixed, loop imx fixed, and simplifications.
                    561: 
                    562:   Revision 1.102  2004/09/15 17:31:30  brouard
                    563:   Add the possibility to read data file including tab characters.
                    564: 
                    565:   Revision 1.101  2004/09/15 10:38:38  brouard
                    566:   Fix on curr_time
                    567: 
                    568:   Revision 1.100  2004/07/12 18:29:06  brouard
                    569:   Add version for Mac OS X. Just define UNIX in Makefile
                    570: 
                    571:   Revision 1.99  2004/06/05 08:57:40  brouard
                    572:   *** empty log message ***
                    573: 
                    574:   Revision 1.98  2004/05/16 15:05:56  brouard
                    575:   New version 0.97 . First attempt to estimate force of mortality
                    576:   directly from the data i.e. without the need of knowing the health
                    577:   state at each age, but using a Gompertz model: log u =a + b*age .
                    578:   This is the basic analysis of mortality and should be done before any
                    579:   other analysis, in order to test if the mortality estimated from the
                    580:   cross-longitudinal survey is different from the mortality estimated
                    581:   from other sources like vital statistic data.
                    582: 
                    583:   The same imach parameter file can be used but the option for mle should be -3.
                    584: 
1.133     brouard   585:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   586:   former routines in order to include the new code within the former code.
                    587: 
                    588:   The output is very simple: only an estimate of the intercept and of
                    589:   the slope with 95% confident intervals.
                    590: 
                    591:   Current limitations:
                    592:   A) Even if you enter covariates, i.e. with the
                    593:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    594:   B) There is no computation of Life Expectancy nor Life Table.
                    595: 
                    596:   Revision 1.97  2004/02/20 13:25:42  lievre
                    597:   Version 0.96d. Population forecasting command line is (temporarily)
                    598:   suppressed.
                    599: 
                    600:   Revision 1.96  2003/07/15 15:38:55  brouard
                    601:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    602:   rewritten within the same printf. Workaround: many printfs.
                    603: 
                    604:   Revision 1.95  2003/07/08 07:54:34  brouard
                    605:   * imach.c (Repository):
                    606:   (Repository): Using imachwizard code to output a more meaningful covariance
                    607:   matrix (cov(a12,c31) instead of numbers.
                    608: 
                    609:   Revision 1.94  2003/06/27 13:00:02  brouard
                    610:   Just cleaning
                    611: 
                    612:   Revision 1.93  2003/06/25 16:33:55  brouard
                    613:   (Module): On windows (cygwin) function asctime_r doesn't
                    614:   exist so I changed back to asctime which exists.
                    615:   (Module): Version 0.96b
                    616: 
                    617:   Revision 1.92  2003/06/25 16:30:45  brouard
                    618:   (Module): On windows (cygwin) function asctime_r doesn't
                    619:   exist so I changed back to asctime which exists.
                    620: 
                    621:   Revision 1.91  2003/06/25 15:30:29  brouard
                    622:   * imach.c (Repository): Duplicated warning errors corrected.
                    623:   (Repository): Elapsed time after each iteration is now output. It
                    624:   helps to forecast when convergence will be reached. Elapsed time
                    625:   is stamped in powell.  We created a new html file for the graphs
                    626:   concerning matrix of covariance. It has extension -cov.htm.
                    627: 
                    628:   Revision 1.90  2003/06/24 12:34:15  brouard
                    629:   (Module): Some bugs corrected for windows. Also, when
                    630:   mle=-1 a template is output in file "or"mypar.txt with the design
                    631:   of the covariance matrix to be input.
                    632: 
                    633:   Revision 1.89  2003/06/24 12:30:52  brouard
                    634:   (Module): Some bugs corrected for windows. Also, when
                    635:   mle=-1 a template is output in file "or"mypar.txt with the design
                    636:   of the covariance matrix to be input.
                    637: 
                    638:   Revision 1.88  2003/06/23 17:54:56  brouard
                    639:   * 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.
                    640: 
                    641:   Revision 1.87  2003/06/18 12:26:01  brouard
                    642:   Version 0.96
                    643: 
                    644:   Revision 1.86  2003/06/17 20:04:08  brouard
                    645:   (Module): Change position of html and gnuplot routines and added
                    646:   routine fileappend.
                    647: 
                    648:   Revision 1.85  2003/06/17 13:12:43  brouard
                    649:   * imach.c (Repository): Check when date of death was earlier that
                    650:   current date of interview. It may happen when the death was just
                    651:   prior to the death. In this case, dh was negative and likelihood
                    652:   was wrong (infinity). We still send an "Error" but patch by
                    653:   assuming that the date of death was just one stepm after the
                    654:   interview.
                    655:   (Repository): Because some people have very long ID (first column)
                    656:   we changed int to long in num[] and we added a new lvector for
                    657:   memory allocation. But we also truncated to 8 characters (left
                    658:   truncation)
                    659:   (Repository): No more line truncation errors.
                    660: 
                    661:   Revision 1.84  2003/06/13 21:44:43  brouard
                    662:   * imach.c (Repository): Replace "freqsummary" at a correct
                    663:   place. It differs from routine "prevalence" which may be called
                    664:   many times. Probs is memory consuming and must be used with
                    665:   parcimony.
                    666:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    667: 
                    668:   Revision 1.83  2003/06/10 13:39:11  lievre
                    669:   *** empty log message ***
                    670: 
                    671:   Revision 1.82  2003/06/05 15:57:20  brouard
                    672:   Add log in  imach.c and  fullversion number is now printed.
                    673: 
                    674: */
                    675: /*
                    676:    Interpolated Markov Chain
                    677: 
                    678:   Short summary of the programme:
                    679:   
1.227     brouard   680:   This program computes Healthy Life Expectancies or State-specific
                    681:   (if states aren't health statuses) Expectancies from
                    682:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    683: 
                    684:   -1- a first survey ("cross") where individuals from different ages
                    685:   are interviewed on their health status or degree of disability (in
                    686:   the case of a health survey which is our main interest)
                    687: 
                    688:   -2- at least a second wave of interviews ("longitudinal") which
                    689:   measure each change (if any) in individual health status.  Health
                    690:   expectancies are computed from the time spent in each health state
                    691:   according to a model. More health states you consider, more time is
                    692:   necessary to reach the Maximum Likelihood of the parameters involved
                    693:   in the model.  The simplest model is the multinomial logistic model
                    694:   where pij is the probability to be observed in state j at the second
                    695:   wave conditional to be observed in state i at the first
                    696:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    697:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    698:   have a more complex model than "constant and age", you should modify
                    699:   the program where the markup *Covariates have to be included here
                    700:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   701:   convergence.
                    702: 
                    703:   The advantage of this computer programme, compared to a simple
                    704:   multinomial logistic model, is clear when the delay between waves is not
                    705:   identical for each individual. Also, if a individual missed an
                    706:   intermediate interview, the information is lost, but taken into
                    707:   account using an interpolation or extrapolation.  
                    708: 
                    709:   hPijx is the probability to be observed in state i at age x+h
                    710:   conditional to the observed state i at age x. The delay 'h' can be
                    711:   split into an exact number (nh*stepm) of unobserved intermediate
                    712:   states. This elementary transition (by month, quarter,
                    713:   semester or year) is modelled as a multinomial logistic.  The hPx
                    714:   matrix is simply the matrix product of nh*stepm elementary matrices
                    715:   and the contribution of each individual to the likelihood is simply
                    716:   hPijx.
                    717: 
                    718:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   719:   of the life expectancies. It also computes the period (stable) prevalence.
                    720: 
                    721: Back prevalence and projections:
1.227     brouard   722: 
                    723:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    724:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    725:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    726:    mobilavproj)
                    727: 
                    728:     Computes the back prevalence limit for any combination of
                    729:     covariate values k at any age between ageminpar and agemaxpar and
                    730:     returns it in **bprlim. In the loops,
                    731: 
                    732:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    733:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    734: 
                    735:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   736:    Computes for any combination of covariates k and any age between bage and fage 
                    737:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    738:                        oldm=oldms;savm=savms;
1.227     brouard   739: 
                    740:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   741:      Computes the transition matrix starting at age 'age' over
                    742:      'nhstepm*hstepm*stepm' months (i.e. until
                    743:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   744:      nhstepm*hstepm matrices. 
                    745: 
                    746:      Returns p3mat[i][j][h] after calling
                    747:      p3mat[i][j][h]=matprod2(newm,
                    748:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    749:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    750:      oldm);
1.226     brouard   751: 
                    752: Important routines
                    753: 
                    754: - func (or funcone), computes logit (pij) distinguishing
                    755:   o fixed variables (single or product dummies or quantitative);
                    756:   o varying variables by:
                    757:    (1) wave (single, product dummies, quantitative), 
                    758:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    759:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    760:        % varying dummy (not done) or quantitative (not done);
                    761: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    762:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    763: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    764:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    765:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   766: 
1.226     brouard   767: 
                    768:   
1.133     brouard   769:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    770:            Institut national d'études démographiques, Paris.
1.126     brouard   771:   This software have been partly granted by Euro-REVES, a concerted action
                    772:   from the European Union.
                    773:   It is copyrighted identically to a GNU software product, ie programme and
                    774:   software can be distributed freely for non commercial use. Latest version
                    775:   can be accessed at http://euroreves.ined.fr/imach .
                    776: 
                    777:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    778:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    779:   
                    780:   **********************************************************************/
                    781: /*
                    782:   main
                    783:   read parameterfile
                    784:   read datafile
                    785:   concatwav
                    786:   freqsummary
                    787:   if (mle >= 1)
                    788:     mlikeli
                    789:   print results files
                    790:   if mle==1 
                    791:      computes hessian
                    792:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    793:       begin-prev-date,...
                    794:   open gnuplot file
                    795:   open html file
1.145     brouard   796:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    797:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    798:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    799:     freexexit2 possible for memory heap.
                    800: 
                    801:   h Pij x                         | pij_nom  ficrestpij
                    802:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    803:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    804:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    805: 
                    806:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    807:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    808:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    809:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    810:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    811: 
1.126     brouard   812:   forecasting if prevfcast==1 prevforecast call prevalence()
                    813:   health expectancies
                    814:   Variance-covariance of DFLE
                    815:   prevalence()
                    816:    movingaverage()
                    817:   varevsij() 
                    818:   if popbased==1 varevsij(,popbased)
                    819:   total life expectancies
                    820:   Variance of period (stable) prevalence
                    821:  end
                    822: */
                    823: 
1.187     brouard   824: /* #define DEBUG */
                    825: /* #define DEBUGBRENT */
1.203     brouard   826: /* #define DEBUGLINMIN */
                    827: /* #define DEBUGHESS */
                    828: #define DEBUGHESSIJ
1.224     brouard   829: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   830: #define POWELL /* Instead of NLOPT */
1.224     brouard   831: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   832: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    833: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   834: 
                    835: #include <math.h>
                    836: #include <stdio.h>
                    837: #include <stdlib.h>
                    838: #include <string.h>
1.226     brouard   839: #include <ctype.h>
1.159     brouard   840: 
                    841: #ifdef _WIN32
                    842: #include <io.h>
1.172     brouard   843: #include <windows.h>
                    844: #include <tchar.h>
1.159     brouard   845: #else
1.126     brouard   846: #include <unistd.h>
1.159     brouard   847: #endif
1.126     brouard   848: 
                    849: #include <limits.h>
                    850: #include <sys/types.h>
1.171     brouard   851: 
                    852: #if defined(__GNUC__)
                    853: #include <sys/utsname.h> /* Doesn't work on Windows */
                    854: #endif
                    855: 
1.126     brouard   856: #include <sys/stat.h>
                    857: #include <errno.h>
1.159     brouard   858: /* extern int errno; */
1.126     brouard   859: 
1.157     brouard   860: /* #ifdef LINUX */
                    861: /* #include <time.h> */
                    862: /* #include "timeval.h" */
                    863: /* #else */
                    864: /* #include <sys/time.h> */
                    865: /* #endif */
                    866: 
1.126     brouard   867: #include <time.h>
                    868: 
1.136     brouard   869: #ifdef GSL
                    870: #include <gsl/gsl_errno.h>
                    871: #include <gsl/gsl_multimin.h>
                    872: #endif
                    873: 
1.167     brouard   874: 
1.162     brouard   875: #ifdef NLOPT
                    876: #include <nlopt.h>
                    877: typedef struct {
                    878:   double (* function)(double [] );
                    879: } myfunc_data ;
                    880: #endif
                    881: 
1.126     brouard   882: /* #include <libintl.h> */
                    883: /* #define _(String) gettext (String) */
                    884: 
1.141     brouard   885: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   886: 
                    887: #define GNUPLOTPROGRAM "gnuplot"
                    888: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    889: #define FILENAMELENGTH 132
                    890: 
                    891: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    892: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    893: 
1.144     brouard   894: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    895: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   896: 
                    897: #define NINTERVMAX 8
1.144     brouard   898: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    899: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    900: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   901: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   902: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    903: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   904: #define MAXN 20000
1.144     brouard   905: #define YEARM 12. /**< Number of months per year */
1.218     brouard   906: /* #define AGESUP 130 */
                    907: #define AGESUP 150
                    908: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   909: #define AGEBASE 40
1.194     brouard   910: #define AGEOVERFLOW 1.e20
1.164     brouard   911: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   912: #ifdef _WIN32
                    913: #define DIRSEPARATOR '\\'
                    914: #define CHARSEPARATOR "\\"
                    915: #define ODIRSEPARATOR '/'
                    916: #else
1.126     brouard   917: #define DIRSEPARATOR '/'
                    918: #define CHARSEPARATOR "/"
                    919: #define ODIRSEPARATOR '\\'
                    920: #endif
                    921: 
1.240   ! brouard   922: /* $Id: imach.c,v 1.239 2016/08/26 15:51:03 brouard Exp $ */
1.126     brouard   923: /* $State: Exp $ */
1.196     brouard   924: #include "version.h"
                    925: char version[]=__IMACH_VERSION__;
1.224     brouard   926: 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.240   ! brouard   927: char fullversion[]="$Revision: 1.239 $ $Date: 2016/08/26 15:51:03 $"; 
1.126     brouard   928: char strstart[80];
                    929: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   930: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   931: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   932: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    933: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    934: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   935: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    936: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   937: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    938: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    939: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   940: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    941: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   942: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   943: int nsd=0; /**< Total number of single dummy variables (output) */
                    944: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   945: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   946: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   947: int ntveff=0; /**< ntveff number of effective time varying variables */
                    948: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   949: int cptcov=0; /* Working variable */
1.218     brouard   950: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   951: int npar=NPARMAX;
                    952: int nlstate=2; /* Number of live states */
                    953: int ndeath=1; /* Number of dead states */
1.130     brouard   954: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   955: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   956: int popbased=0;
                    957: 
                    958: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   959: int maxwav=0; /* Maxim number of waves */
                    960: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    961: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    962: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   963:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   964: int mle=1, weightopt=0;
1.126     brouard   965: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    966: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    967: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    968:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   969: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   970: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    971: 
1.130     brouard   972: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   973: double **matprod2(); /* test */
1.126     brouard   974: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    975: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   976: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    977: 
1.136     brouard   978: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   979: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   980: FILE *ficlog, *ficrespow;
1.130     brouard   981: int globpr=0; /* Global variable for printing or not */
1.126     brouard   982: double fretone; /* Only one call to likelihood */
1.130     brouard   983: long ipmx=0; /* Number of contributions */
1.126     brouard   984: double sw; /* Sum of weights */
                    985: char filerespow[FILENAMELENGTH];
                    986: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    987: FILE *ficresilk;
                    988: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    989: FILE *ficresprobmorprev;
                    990: FILE *fichtm, *fichtmcov; /* Html File */
                    991: FILE *ficreseij;
                    992: char filerese[FILENAMELENGTH];
                    993: FILE *ficresstdeij;
                    994: char fileresstde[FILENAMELENGTH];
                    995: FILE *ficrescveij;
                    996: char filerescve[FILENAMELENGTH];
                    997: FILE  *ficresvij;
                    998: char fileresv[FILENAMELENGTH];
                    999: FILE  *ficresvpl;
                   1000: char fileresvpl[FILENAMELENGTH];
                   1001: char title[MAXLINE];
1.234     brouard  1002: char model[MAXLINE]; /**< The model line */
1.217     brouard  1003: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1004: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1005: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1006: char command[FILENAMELENGTH];
                   1007: int  outcmd=0;
                   1008: 
1.217     brouard  1009: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1010: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1011: char filelog[FILENAMELENGTH]; /* Log file */
                   1012: char filerest[FILENAMELENGTH];
                   1013: char fileregp[FILENAMELENGTH];
                   1014: char popfile[FILENAMELENGTH];
                   1015: 
                   1016: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1017: 
1.157     brouard  1018: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1019: /* struct timezone tzp; */
                   1020: /* extern int gettimeofday(); */
                   1021: struct tm tml, *gmtime(), *localtime();
                   1022: 
                   1023: extern time_t time();
                   1024: 
                   1025: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1026: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1027: struct tm tm;
                   1028: 
1.126     brouard  1029: char strcurr[80], strfor[80];
                   1030: 
                   1031: char *endptr;
                   1032: long lval;
                   1033: double dval;
                   1034: 
                   1035: #define NR_END 1
                   1036: #define FREE_ARG char*
                   1037: #define FTOL 1.0e-10
                   1038: 
                   1039: #define NRANSI 
1.240   ! brouard  1040: #define ITMAX 200
        !          1041: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1042: 
                   1043: #define TOL 2.0e-4 
                   1044: 
                   1045: #define CGOLD 0.3819660 
                   1046: #define ZEPS 1.0e-10 
                   1047: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1048: 
                   1049: #define GOLD 1.618034 
                   1050: #define GLIMIT 100.0 
                   1051: #define TINY 1.0e-20 
                   1052: 
                   1053: static double maxarg1,maxarg2;
                   1054: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1055: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1056:   
                   1057: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1058: #define rint(a) floor(a+0.5)
1.166     brouard  1059: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1060: #define mytinydouble 1.0e-16
1.166     brouard  1061: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1062: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1063: /* static double dsqrarg; */
                   1064: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1065: static double sqrarg;
                   1066: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1067: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1068: int agegomp= AGEGOMP;
                   1069: 
                   1070: int imx; 
                   1071: int stepm=1;
                   1072: /* Stepm, step in month: minimum step interpolation*/
                   1073: 
                   1074: int estepm;
                   1075: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1076: 
                   1077: int m,nb;
                   1078: long *num;
1.197     brouard  1079: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1080: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1081:                   covariate for which somebody answered excluding 
                   1082:                   undefined. Usually 2: 0 and 1. */
                   1083: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1084:                             covariate for which somebody answered including 
                   1085:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1086: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1087: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1088: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1089: double *ageexmed,*agecens;
                   1090: double dateintmean=0;
                   1091: 
                   1092: double *weight;
                   1093: int **s; /* Status */
1.141     brouard  1094: double *agedc;
1.145     brouard  1095: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1096:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1097:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1098: double **coqvar; /* Fixed quantitative covariate iqv */
                   1099: double ***cotvar; /* Time varying covariate itv */
                   1100: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1101: double  idx; 
                   1102: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1103: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1104: /*k          1  2   3   4     5    6    7     8    9 */
                   1105: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1106: /* Tndvar[k]    1   2   3               4          5 */
                   1107: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1108: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1109: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1110: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1111: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1112: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1113: /* Tprod[i]=k           4               7            */
                   1114: /* Tage[i]=k                  5               8      */
                   1115: /* */
                   1116: /* Type                    */
                   1117: /* V         1  2  3  4  5 */
                   1118: /*           F  F  V  V  V */
                   1119: /*           D  Q  D  D  Q */
                   1120: /*                         */
                   1121: int *TvarsD;
                   1122: int *TvarsDind;
                   1123: int *TvarsQ;
                   1124: int *TvarsQind;
                   1125: 
1.235     brouard  1126: #define MAXRESULTLINES 10
                   1127: int nresult=0;
                   1128: int TKresult[MAXRESULTLINES];
1.237     brouard  1129: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1130: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1131: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1132: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1133: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1134: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1135: 
1.234     brouard  1136: /* 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  1137: 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 */
                   1138: 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 */
                   1139: 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 */
                   1140: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1141: 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 */
                   1142: 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  1143: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1144: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1145: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1146: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1147: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1148: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1149: 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 */
                   1150: 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 */
                   1151: 
1.230     brouard  1152: int *Tvarsel; /**< Selected covariates for output */
                   1153: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1154: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1155: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1156: 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  1157: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1158: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1159: int *Tage;
1.227     brouard  1160: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1161: 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  1162: 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*/ 
                   1163: 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  1164: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1165: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1166: int **Tvard;
                   1167: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1168: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1169: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1170:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1171:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1172: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1173: double *lsurv, *lpop, *tpop;
                   1174: 
1.231     brouard  1175: #define FD 1; /* Fixed dummy covariate */
                   1176: #define FQ 2; /* Fixed quantitative covariate */
                   1177: #define FP 3; /* Fixed product covariate */
                   1178: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1179: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1180: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1181: #define VD 10; /* Varying dummy covariate */
                   1182: #define VQ 11; /* Varying quantitative covariate */
                   1183: #define VP 12; /* Varying product covariate */
                   1184: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1185: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1186: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1187: #define APFD 16; /* Age product * fixed dummy covariate */
                   1188: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1189: #define APVD 18; /* Age product * varying dummy covariate */
                   1190: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1191: 
                   1192: #define FTYPE 1; /* Fixed covariate */
                   1193: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1194: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1195: 
                   1196: struct kmodel{
                   1197:        int maintype; /* main type */
                   1198:        int subtype; /* subtype */
                   1199: };
                   1200: struct kmodel modell[NCOVMAX];
                   1201: 
1.143     brouard  1202: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1203: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1204: 
                   1205: /**************** split *************************/
                   1206: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1207: {
                   1208:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1209:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1210:   */ 
                   1211:   char *ss;                            /* pointer */
1.186     brouard  1212:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1213: 
                   1214:   l1 = strlen(path );                  /* length of path */
                   1215:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1216:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1217:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1218:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1219:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1220:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1221:     /* get current working directory */
                   1222:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1223: #ifdef WIN32
                   1224:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1225: #else
                   1226:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1227: #endif
1.126     brouard  1228:       return( GLOCK_ERROR_GETCWD );
                   1229:     }
                   1230:     /* got dirc from getcwd*/
                   1231:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1232:   } else {                             /* strip directory from path */
1.126     brouard  1233:     ss++;                              /* after this, the filename */
                   1234:     l2 = strlen( ss );                 /* length of filename */
                   1235:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1236:     strcpy( name, ss );                /* save file name */
                   1237:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1238:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1239:     printf(" DIRC2 = %s \n",dirc);
                   1240:   }
                   1241:   /* We add a separator at the end of dirc if not exists */
                   1242:   l1 = strlen( dirc );                 /* length of directory */
                   1243:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1244:     dirc[l1] =  DIRSEPARATOR;
                   1245:     dirc[l1+1] = 0; 
                   1246:     printf(" DIRC3 = %s \n",dirc);
                   1247:   }
                   1248:   ss = strrchr( name, '.' );           /* find last / */
                   1249:   if (ss >0){
                   1250:     ss++;
                   1251:     strcpy(ext,ss);                    /* save extension */
                   1252:     l1= strlen( name);
                   1253:     l2= strlen(ss)+1;
                   1254:     strncpy( finame, name, l1-l2);
                   1255:     finame[l1-l2]= 0;
                   1256:   }
                   1257: 
                   1258:   return( 0 );                         /* we're done */
                   1259: }
                   1260: 
                   1261: 
                   1262: /******************************************/
                   1263: 
                   1264: void replace_back_to_slash(char *s, char*t)
                   1265: {
                   1266:   int i;
                   1267:   int lg=0;
                   1268:   i=0;
                   1269:   lg=strlen(t);
                   1270:   for(i=0; i<= lg; i++) {
                   1271:     (s[i] = t[i]);
                   1272:     if (t[i]== '\\') s[i]='/';
                   1273:   }
                   1274: }
                   1275: 
1.132     brouard  1276: char *trimbb(char *out, char *in)
1.137     brouard  1277: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1278:   char *s;
                   1279:   s=out;
                   1280:   while (*in != '\0'){
1.137     brouard  1281:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1282:       in++;
                   1283:     }
                   1284:     *out++ = *in++;
                   1285:   }
                   1286:   *out='\0';
                   1287:   return s;
                   1288: }
                   1289: 
1.187     brouard  1290: /* char *substrchaine(char *out, char *in, char *chain) */
                   1291: /* { */
                   1292: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1293: /*   char *s, *t; */
                   1294: /*   t=in;s=out; */
                   1295: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1296: /*     *out++ = *in++; */
                   1297: /*   } */
                   1298: 
                   1299: /*   /\* *in matches *chain *\/ */
                   1300: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1301: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1302: /*   } */
                   1303: /*   in--; chain--; */
                   1304: /*   while ( (*in != '\0')){ */
                   1305: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1306: /*     *out++ = *in++; */
                   1307: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1308: /*   } */
                   1309: /*   *out='\0'; */
                   1310: /*   out=s; */
                   1311: /*   return out; */
                   1312: /* } */
                   1313: char *substrchaine(char *out, char *in, char *chain)
                   1314: {
                   1315:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1316:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1317: 
                   1318:   char *strloc;
                   1319: 
                   1320:   strcpy (out, in); 
                   1321:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1322:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1323:   if(strloc != NULL){ 
                   1324:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1325:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1326:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1327:   }
                   1328:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1329:   return out;
                   1330: }
                   1331: 
                   1332: 
1.145     brouard  1333: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1334: {
1.187     brouard  1335:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1336:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1337:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1338:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1339:   */
1.160     brouard  1340:   char *s, *t;
1.145     brouard  1341:   t=in;s=in;
                   1342:   while ((*in != occ) && (*in != '\0')){
                   1343:     *alocc++ = *in++;
                   1344:   }
                   1345:   if( *in == occ){
                   1346:     *(alocc)='\0';
                   1347:     s=++in;
                   1348:   }
                   1349:  
                   1350:   if (s == t) {/* occ not found */
                   1351:     *(alocc-(in-s))='\0';
                   1352:     in=s;
                   1353:   }
                   1354:   while ( *in != '\0'){
                   1355:     *blocc++ = *in++;
                   1356:   }
                   1357: 
                   1358:   *blocc='\0';
                   1359:   return t;
                   1360: }
1.137     brouard  1361: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1362: {
1.187     brouard  1363:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1364:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1365:      gives blocc="abcdef2ghi" and alocc="j".
                   1366:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1367:   */
                   1368:   char *s, *t;
                   1369:   t=in;s=in;
                   1370:   while (*in != '\0'){
                   1371:     while( *in == occ){
                   1372:       *blocc++ = *in++;
                   1373:       s=in;
                   1374:     }
                   1375:     *blocc++ = *in++;
                   1376:   }
                   1377:   if (s == t) /* occ not found */
                   1378:     *(blocc-(in-s))='\0';
                   1379:   else
                   1380:     *(blocc-(in-s)-1)='\0';
                   1381:   in=s;
                   1382:   while ( *in != '\0'){
                   1383:     *alocc++ = *in++;
                   1384:   }
                   1385: 
                   1386:   *alocc='\0';
                   1387:   return s;
                   1388: }
                   1389: 
1.126     brouard  1390: int nbocc(char *s, char occ)
                   1391: {
                   1392:   int i,j=0;
                   1393:   int lg=20;
                   1394:   i=0;
                   1395:   lg=strlen(s);
                   1396:   for(i=0; i<= lg; i++) {
1.234     brouard  1397:     if  (s[i] == occ ) j++;
1.126     brouard  1398:   }
                   1399:   return j;
                   1400: }
                   1401: 
1.137     brouard  1402: /* void cutv(char *u,char *v, char*t, char occ) */
                   1403: /* { */
                   1404: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1405: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1406: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1407: /*   int i,lg,j,p=0; */
                   1408: /*   i=0; */
                   1409: /*   lg=strlen(t); */
                   1410: /*   for(j=0; j<=lg-1; j++) { */
                   1411: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1412: /*   } */
1.126     brouard  1413: 
1.137     brouard  1414: /*   for(j=0; j<p; j++) { */
                   1415: /*     (u[j] = t[j]); */
                   1416: /*   } */
                   1417: /*      u[p]='\0'; */
1.126     brouard  1418: 
1.137     brouard  1419: /*    for(j=0; j<= lg; j++) { */
                   1420: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1421: /*   } */
                   1422: /* } */
1.126     brouard  1423: 
1.160     brouard  1424: #ifdef _WIN32
                   1425: char * strsep(char **pp, const char *delim)
                   1426: {
                   1427:   char *p, *q;
                   1428:          
                   1429:   if ((p = *pp) == NULL)
                   1430:     return 0;
                   1431:   if ((q = strpbrk (p, delim)) != NULL)
                   1432:   {
                   1433:     *pp = q + 1;
                   1434:     *q = '\0';
                   1435:   }
                   1436:   else
                   1437:     *pp = 0;
                   1438:   return p;
                   1439: }
                   1440: #endif
                   1441: 
1.126     brouard  1442: /********************** nrerror ********************/
                   1443: 
                   1444: void nrerror(char error_text[])
                   1445: {
                   1446:   fprintf(stderr,"ERREUR ...\n");
                   1447:   fprintf(stderr,"%s\n",error_text);
                   1448:   exit(EXIT_FAILURE);
                   1449: }
                   1450: /*********************** vector *******************/
                   1451: double *vector(int nl, int nh)
                   1452: {
                   1453:   double *v;
                   1454:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1455:   if (!v) nrerror("allocation failure in vector");
                   1456:   return v-nl+NR_END;
                   1457: }
                   1458: 
                   1459: /************************ free vector ******************/
                   1460: void free_vector(double*v, int nl, int nh)
                   1461: {
                   1462:   free((FREE_ARG)(v+nl-NR_END));
                   1463: }
                   1464: 
                   1465: /************************ivector *******************************/
                   1466: int *ivector(long nl,long nh)
                   1467: {
                   1468:   int *v;
                   1469:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1470:   if (!v) nrerror("allocation failure in ivector");
                   1471:   return v-nl+NR_END;
                   1472: }
                   1473: 
                   1474: /******************free ivector **************************/
                   1475: void free_ivector(int *v, long nl, long nh)
                   1476: {
                   1477:   free((FREE_ARG)(v+nl-NR_END));
                   1478: }
                   1479: 
                   1480: /************************lvector *******************************/
                   1481: long *lvector(long nl,long nh)
                   1482: {
                   1483:   long *v;
                   1484:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1485:   if (!v) nrerror("allocation failure in ivector");
                   1486:   return v-nl+NR_END;
                   1487: }
                   1488: 
                   1489: /******************free lvector **************************/
                   1490: void free_lvector(long *v, long nl, long nh)
                   1491: {
                   1492:   free((FREE_ARG)(v+nl-NR_END));
                   1493: }
                   1494: 
                   1495: /******************* imatrix *******************************/
                   1496: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1497:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1498: { 
                   1499:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1500:   int **m; 
                   1501:   
                   1502:   /* allocate pointers to rows */ 
                   1503:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1504:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1505:   m += NR_END; 
                   1506:   m -= nrl; 
                   1507:   
                   1508:   
                   1509:   /* allocate rows and set pointers to them */ 
                   1510:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1511:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1512:   m[nrl] += NR_END; 
                   1513:   m[nrl] -= ncl; 
                   1514:   
                   1515:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1516:   
                   1517:   /* return pointer to array of pointers to rows */ 
                   1518:   return m; 
                   1519: } 
                   1520: 
                   1521: /****************** free_imatrix *************************/
                   1522: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1523:       int **m;
                   1524:       long nch,ncl,nrh,nrl; 
                   1525:      /* free an int matrix allocated by imatrix() */ 
                   1526: { 
                   1527:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1528:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1529: } 
                   1530: 
                   1531: /******************* matrix *******************************/
                   1532: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1533: {
                   1534:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1535:   double **m;
                   1536: 
                   1537:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1538:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1539:   m += NR_END;
                   1540:   m -= nrl;
                   1541: 
                   1542:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1543:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1544:   m[nrl] += NR_END;
                   1545:   m[nrl] -= ncl;
                   1546: 
                   1547:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1548:   return m;
1.145     brouard  1549:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1550: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1551: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1552:    */
                   1553: }
                   1554: 
                   1555: /*************************free matrix ************************/
                   1556: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1557: {
                   1558:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1559:   free((FREE_ARG)(m+nrl-NR_END));
                   1560: }
                   1561: 
                   1562: /******************* ma3x *******************************/
                   1563: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1564: {
                   1565:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1566:   double ***m;
                   1567: 
                   1568:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1569:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1570:   m += NR_END;
                   1571:   m -= nrl;
                   1572: 
                   1573:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1574:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1575:   m[nrl] += NR_END;
                   1576:   m[nrl] -= ncl;
                   1577: 
                   1578:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1579: 
                   1580:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1581:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1582:   m[nrl][ncl] += NR_END;
                   1583:   m[nrl][ncl] -= nll;
                   1584:   for (j=ncl+1; j<=nch; j++) 
                   1585:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1586:   
                   1587:   for (i=nrl+1; i<=nrh; i++) {
                   1588:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1589:     for (j=ncl+1; j<=nch; j++) 
                   1590:       m[i][j]=m[i][j-1]+nlay;
                   1591:   }
                   1592:   return m; 
                   1593:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1594:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1595:   */
                   1596: }
                   1597: 
                   1598: /*************************free ma3x ************************/
                   1599: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1600: {
                   1601:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1602:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1603:   free((FREE_ARG)(m+nrl-NR_END));
                   1604: }
                   1605: 
                   1606: /*************** function subdirf ***********/
                   1607: char *subdirf(char fileres[])
                   1608: {
                   1609:   /* Caution optionfilefiname is hidden */
                   1610:   strcpy(tmpout,optionfilefiname);
                   1611:   strcat(tmpout,"/"); /* Add to the right */
                   1612:   strcat(tmpout,fileres);
                   1613:   return tmpout;
                   1614: }
                   1615: 
                   1616: /*************** function subdirf2 ***********/
                   1617: char *subdirf2(char fileres[], char *preop)
                   1618: {
                   1619:   
                   1620:   /* Caution optionfilefiname is hidden */
                   1621:   strcpy(tmpout,optionfilefiname);
                   1622:   strcat(tmpout,"/");
                   1623:   strcat(tmpout,preop);
                   1624:   strcat(tmpout,fileres);
                   1625:   return tmpout;
                   1626: }
                   1627: 
                   1628: /*************** function subdirf3 ***********/
                   1629: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1630: {
                   1631:   
                   1632:   /* Caution optionfilefiname is hidden */
                   1633:   strcpy(tmpout,optionfilefiname);
                   1634:   strcat(tmpout,"/");
                   1635:   strcat(tmpout,preop);
                   1636:   strcat(tmpout,preop2);
                   1637:   strcat(tmpout,fileres);
                   1638:   return tmpout;
                   1639: }
1.213     brouard  1640:  
                   1641: /*************** function subdirfext ***********/
                   1642: char *subdirfext(char fileres[], char *preop, char *postop)
                   1643: {
                   1644:   
                   1645:   strcpy(tmpout,preop);
                   1646:   strcat(tmpout,fileres);
                   1647:   strcat(tmpout,postop);
                   1648:   return tmpout;
                   1649: }
1.126     brouard  1650: 
1.213     brouard  1651: /*************** function subdirfext3 ***********/
                   1652: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1653: {
                   1654:   
                   1655:   /* Caution optionfilefiname is hidden */
                   1656:   strcpy(tmpout,optionfilefiname);
                   1657:   strcat(tmpout,"/");
                   1658:   strcat(tmpout,preop);
                   1659:   strcat(tmpout,fileres);
                   1660:   strcat(tmpout,postop);
                   1661:   return tmpout;
                   1662: }
                   1663:  
1.162     brouard  1664: char *asc_diff_time(long time_sec, char ascdiff[])
                   1665: {
                   1666:   long sec_left, days, hours, minutes;
                   1667:   days = (time_sec) / (60*60*24);
                   1668:   sec_left = (time_sec) % (60*60*24);
                   1669:   hours = (sec_left) / (60*60) ;
                   1670:   sec_left = (sec_left) %(60*60);
                   1671:   minutes = (sec_left) /60;
                   1672:   sec_left = (sec_left) % (60);
                   1673:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1674:   return ascdiff;
                   1675: }
                   1676: 
1.126     brouard  1677: /***************** f1dim *************************/
                   1678: extern int ncom; 
                   1679: extern double *pcom,*xicom;
                   1680: extern double (*nrfunc)(double []); 
                   1681:  
                   1682: double f1dim(double x) 
                   1683: { 
                   1684:   int j; 
                   1685:   double f;
                   1686:   double *xt; 
                   1687:  
                   1688:   xt=vector(1,ncom); 
                   1689:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1690:   f=(*nrfunc)(xt); 
                   1691:   free_vector(xt,1,ncom); 
                   1692:   return f; 
                   1693: } 
                   1694: 
                   1695: /*****************brent *************************/
                   1696: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1697: {
                   1698:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1699:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1700:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1701:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1702:    * returned function value. 
                   1703:   */
1.126     brouard  1704:   int iter; 
                   1705:   double a,b,d,etemp;
1.159     brouard  1706:   double fu=0,fv,fw,fx;
1.164     brouard  1707:   double ftemp=0.;
1.126     brouard  1708:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1709:   double e=0.0; 
                   1710:  
                   1711:   a=(ax < cx ? ax : cx); 
                   1712:   b=(ax > cx ? ax : cx); 
                   1713:   x=w=v=bx; 
                   1714:   fw=fv=fx=(*f)(x); 
                   1715:   for (iter=1;iter<=ITMAX;iter++) { 
                   1716:     xm=0.5*(a+b); 
                   1717:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1718:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1719:     printf(".");fflush(stdout);
                   1720:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1721: #ifdef DEBUGBRENT
1.126     brouard  1722:     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);
                   1723:     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);
                   1724:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1725: #endif
                   1726:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1727:       *xmin=x; 
                   1728:       return fx; 
                   1729:     } 
                   1730:     ftemp=fu;
                   1731:     if (fabs(e) > tol1) { 
                   1732:       r=(x-w)*(fx-fv); 
                   1733:       q=(x-v)*(fx-fw); 
                   1734:       p=(x-v)*q-(x-w)*r; 
                   1735:       q=2.0*(q-r); 
                   1736:       if (q > 0.0) p = -p; 
                   1737:       q=fabs(q); 
                   1738:       etemp=e; 
                   1739:       e=d; 
                   1740:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1741:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1742:       else { 
1.224     brouard  1743:                                d=p/q; 
                   1744:                                u=x+d; 
                   1745:                                if (u-a < tol2 || b-u < tol2) 
                   1746:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1747:       } 
                   1748:     } else { 
                   1749:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1750:     } 
                   1751:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1752:     fu=(*f)(u); 
                   1753:     if (fu <= fx) { 
                   1754:       if (u >= x) a=x; else b=x; 
                   1755:       SHFT(v,w,x,u) 
1.183     brouard  1756:       SHFT(fv,fw,fx,fu) 
                   1757:     } else { 
                   1758:       if (u < x) a=u; else b=u; 
                   1759:       if (fu <= fw || w == x) { 
1.224     brouard  1760:                                v=w; 
                   1761:                                w=u; 
                   1762:                                fv=fw; 
                   1763:                                fw=fu; 
1.183     brouard  1764:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1765:                                v=u; 
                   1766:                                fv=fu; 
1.183     brouard  1767:       } 
                   1768:     } 
1.126     brouard  1769:   } 
                   1770:   nrerror("Too many iterations in brent"); 
                   1771:   *xmin=x; 
                   1772:   return fx; 
                   1773: } 
                   1774: 
                   1775: /****************** mnbrak ***********************/
                   1776: 
                   1777: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1778:            double (*func)(double)) 
1.183     brouard  1779: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1780: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1781: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1782: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1783:    */
1.126     brouard  1784:   double ulim,u,r,q, dum;
                   1785:   double fu; 
1.187     brouard  1786: 
                   1787:   double scale=10.;
                   1788:   int iterscale=0;
                   1789: 
                   1790:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1791:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1792: 
                   1793: 
                   1794:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1795:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1796:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1797:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1798:   /* } */
                   1799: 
1.126     brouard  1800:   if (*fb > *fa) { 
                   1801:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1802:     SHFT(dum,*fb,*fa,dum) 
                   1803:   } 
1.126     brouard  1804:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1805:   *fc=(*func)(*cx); 
1.183     brouard  1806: #ifdef DEBUG
1.224     brouard  1807:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1808:   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  1809: #endif
1.224     brouard  1810:   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  1811:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1812:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1813:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1814:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1815:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1816:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1817:       fu=(*func)(u); 
1.163     brouard  1818: #ifdef DEBUG
                   1819:       /* f(x)=A(x-u)**2+f(u) */
                   1820:       double A, fparabu; 
                   1821:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1822:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1823:       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);
                   1824:       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  1825:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1826:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1827:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1828:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1829: #endif 
1.184     brouard  1830: #ifdef MNBRAKORIGINAL
1.183     brouard  1831: #else
1.191     brouard  1832: /*       if (fu > *fc) { */
                   1833: /* #ifdef DEBUG */
                   1834: /*       printf("mnbrak4  fu > fc \n"); */
                   1835: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1836: /* #endif */
                   1837: /*     /\* 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 *\\/  *\/ */
                   1838: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1839: /*     dum=u; /\* Shifting c and u *\/ */
                   1840: /*     u = *cx; */
                   1841: /*     *cx = dum; */
                   1842: /*     dum = fu; */
                   1843: /*     fu = *fc; */
                   1844: /*     *fc =dum; */
                   1845: /*       } else { /\* end *\/ */
                   1846: /* #ifdef DEBUG */
                   1847: /*       printf("mnbrak3  fu < fc \n"); */
                   1848: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1849: /* #endif */
                   1850: /*     dum=u; /\* Shifting c and u *\/ */
                   1851: /*     u = *cx; */
                   1852: /*     *cx = dum; */
                   1853: /*     dum = fu; */
                   1854: /*     fu = *fc; */
                   1855: /*     *fc =dum; */
                   1856: /*       } */
1.224     brouard  1857: #ifdef DEBUGMNBRAK
                   1858:                 double A, fparabu; 
                   1859:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1860:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1861:      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);
                   1862:      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  1863: #endif
1.191     brouard  1864:       dum=u; /* Shifting c and u */
                   1865:       u = *cx;
                   1866:       *cx = dum;
                   1867:       dum = fu;
                   1868:       fu = *fc;
                   1869:       *fc =dum;
1.183     brouard  1870: #endif
1.162     brouard  1871:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1872: #ifdef DEBUG
1.224     brouard  1873:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1874:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1875: #endif
1.126     brouard  1876:       fu=(*func)(u); 
                   1877:       if (fu < *fc) { 
1.183     brouard  1878: #ifdef DEBUG
1.224     brouard  1879:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1880:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1881: #endif
                   1882:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1883:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1884: #ifdef DEBUG
                   1885:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1886: #endif
                   1887:       } 
1.162     brouard  1888:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1889: #ifdef DEBUG
1.224     brouard  1890:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1891:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1892: #endif
1.126     brouard  1893:       u=ulim; 
                   1894:       fu=(*func)(u); 
1.183     brouard  1895:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1896: #ifdef DEBUG
1.224     brouard  1897:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1898:       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  1899: #endif
1.126     brouard  1900:       u=(*cx)+GOLD*(*cx-*bx); 
                   1901:       fu=(*func)(u); 
1.224     brouard  1902: #ifdef DEBUG
                   1903:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1904:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1905: #endif
1.183     brouard  1906:     } /* end tests */
1.126     brouard  1907:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1908:     SHFT(*fa,*fb,*fc,fu) 
                   1909: #ifdef DEBUG
1.224     brouard  1910:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1911:       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  1912: #endif
                   1913:   } /* 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  1914: } 
                   1915: 
                   1916: /*************** linmin ************************/
1.162     brouard  1917: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1918: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1919: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1920: the value of func at the returned location p . This is actually all accomplished by calling the
                   1921: routines mnbrak and brent .*/
1.126     brouard  1922: int ncom; 
                   1923: double *pcom,*xicom;
                   1924: double (*nrfunc)(double []); 
                   1925:  
1.224     brouard  1926: #ifdef LINMINORIGINAL
1.126     brouard  1927: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1928: #else
                   1929: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1930: #endif
1.126     brouard  1931: { 
                   1932:   double brent(double ax, double bx, double cx, 
                   1933:               double (*f)(double), double tol, double *xmin); 
                   1934:   double f1dim(double x); 
                   1935:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1936:              double *fc, double (*func)(double)); 
                   1937:   int j; 
                   1938:   double xx,xmin,bx,ax; 
                   1939:   double fx,fb,fa;
1.187     brouard  1940: 
1.203     brouard  1941: #ifdef LINMINORIGINAL
                   1942: #else
                   1943:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1944: #endif
                   1945:   
1.126     brouard  1946:   ncom=n; 
                   1947:   pcom=vector(1,n); 
                   1948:   xicom=vector(1,n); 
                   1949:   nrfunc=func; 
                   1950:   for (j=1;j<=n;j++) { 
                   1951:     pcom[j]=p[j]; 
1.202     brouard  1952:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1953:   } 
1.187     brouard  1954: 
1.203     brouard  1955: #ifdef LINMINORIGINAL
                   1956:   xx=1.;
                   1957: #else
                   1958:   axs=0.0;
                   1959:   xxs=1.;
                   1960:   do{
                   1961:     xx= xxs;
                   1962: #endif
1.187     brouard  1963:     ax=0.;
                   1964:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1965:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1966:     /* 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))   */
                   1967:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1968:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1969:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1970:     /* 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  1971: #ifdef LINMINORIGINAL
                   1972: #else
                   1973:     if (fx != fx){
1.224     brouard  1974:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1975:                        printf("|");
                   1976:                        fprintf(ficlog,"|");
1.203     brouard  1977: #ifdef DEBUGLINMIN
1.224     brouard  1978:                        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  1979: #endif
                   1980:     }
1.224     brouard  1981:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1982: #endif
                   1983:   
1.191     brouard  1984: #ifdef DEBUGLINMIN
                   1985:   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  1986:   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  1987: #endif
1.224     brouard  1988: #ifdef LINMINORIGINAL
                   1989: #else
                   1990:        if(fb == fx){ /* Flat function in the direction */
                   1991:                xmin=xx;
                   1992:     *flat=1;
                   1993:        }else{
                   1994:     *flat=0;
                   1995: #endif
                   1996:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  1997:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1998:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1999:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2000:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2001:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2002: #ifdef DEBUG
1.224     brouard  2003:   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);
                   2004:   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);
                   2005: #endif
                   2006: #ifdef LINMINORIGINAL
                   2007: #else
                   2008:                        }
1.126     brouard  2009: #endif
1.191     brouard  2010: #ifdef DEBUGLINMIN
                   2011:   printf("linmin end ");
1.202     brouard  2012:   fprintf(ficlog,"linmin end ");
1.191     brouard  2013: #endif
1.126     brouard  2014:   for (j=1;j<=n;j++) { 
1.203     brouard  2015: #ifdef LINMINORIGINAL
                   2016:     xi[j] *= xmin; 
                   2017: #else
                   2018: #ifdef DEBUGLINMIN
                   2019:     if(xxs <1.0)
                   2020:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2021: #endif
                   2022:     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) */
                   2023: #ifdef DEBUGLINMIN
                   2024:     if(xxs <1.0)
                   2025:       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 );
                   2026: #endif
                   2027: #endif
1.187     brouard  2028:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2029:   } 
1.191     brouard  2030: #ifdef DEBUGLINMIN
1.203     brouard  2031:   printf("\n");
1.191     brouard  2032:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2033:   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  2034:   for (j=1;j<=n;j++) { 
1.202     brouard  2035:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2036:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2037:     if(j % ncovmodel == 0){
1.191     brouard  2038:       printf("\n");
1.202     brouard  2039:       fprintf(ficlog,"\n");
                   2040:     }
1.191     brouard  2041:   }
1.203     brouard  2042: #else
1.191     brouard  2043: #endif
1.126     brouard  2044:   free_vector(xicom,1,n); 
                   2045:   free_vector(pcom,1,n); 
                   2046: } 
                   2047: 
                   2048: 
                   2049: /*************** powell ************************/
1.162     brouard  2050: /*
                   2051: Minimization of a function func of n variables. Input consists of an initial starting point
                   2052: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2053: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2054: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2055: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2056: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2057:  */
1.224     brouard  2058: #ifdef LINMINORIGINAL
                   2059: #else
                   2060:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2061:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2062: #endif
1.126     brouard  2063: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2064:            double (*func)(double [])) 
                   2065: { 
1.224     brouard  2066: #ifdef LINMINORIGINAL
                   2067:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2068:              double (*func)(double [])); 
1.224     brouard  2069: #else 
                   2070:  void linmin(double p[], double xi[], int n, double *fret, 
                   2071:                                                 double (*func)(double []),int *flat); 
                   2072: #endif
1.239     brouard  2073:  int i,ibig,j,jk,k; 
1.126     brouard  2074:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2075:   double directest;
1.126     brouard  2076:   double fp,fptt;
                   2077:   double *xits;
                   2078:   int niterf, itmp;
1.224     brouard  2079: #ifdef LINMINORIGINAL
                   2080: #else
                   2081: 
                   2082:   flatdir=ivector(1,n); 
                   2083:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2084: #endif
1.126     brouard  2085: 
                   2086:   pt=vector(1,n); 
                   2087:   ptt=vector(1,n); 
                   2088:   xit=vector(1,n); 
                   2089:   xits=vector(1,n); 
                   2090:   *fret=(*func)(p); 
                   2091:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2092:   rcurr_time = time(NULL);  
1.126     brouard  2093:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2094:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2095:     ibig=0; 
                   2096:     del=0.0; 
1.157     brouard  2097:     rlast_time=rcurr_time;
                   2098:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2099:     rcurr_time = time(NULL);  
                   2100:     curr_time = *localtime(&rcurr_time);
                   2101:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2102:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2103: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2104:     for (i=1;i<=n;i++) {
1.126     brouard  2105:       fprintf(ficrespow," %.12lf", p[i]);
                   2106:     }
1.239     brouard  2107:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2108:     printf("\n#model=  1      +     age ");
                   2109:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2110:     if(nagesqr==1){
                   2111:        printf("  + age*age  ",Tvar[j]);
                   2112:        fprintf(ficlog,"  + age*age  ",Tvar[j]);
                   2113:     }
                   2114:     for(j=1;j <=ncovmodel-2;j++){
                   2115:       if(Typevar[j]==0) {
                   2116:        printf("  +      V%d  ",Tvar[j]);
                   2117:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2118:       }else if(Typevar[j]==1) {
                   2119:        printf("  +    V%d*age ",Tvar[j]);
                   2120:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2121:       }else if(Typevar[j]==2) {
                   2122:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2123:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2124:       }
                   2125:     }
1.126     brouard  2126:     printf("\n");
1.239     brouard  2127: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2128: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2129:     fprintf(ficlog,"\n");
1.239     brouard  2130:     for(i=1,jk=1; i <=nlstate; i++){
                   2131:       for(k=1; k <=(nlstate+ndeath); k++){
                   2132:        if (k != i) {
                   2133:          printf("%d%d ",i,k);
                   2134:          fprintf(ficlog,"%d%d ",i,k);
                   2135:          for(j=1; j <=ncovmodel; j++){
                   2136:            printf("%12.7f ",p[jk]);
                   2137:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2138:            jk++; 
                   2139:          }
                   2140:          printf("\n");
                   2141:          fprintf(ficlog,"\n");
                   2142:        }
                   2143:       }
                   2144:     }
1.126     brouard  2145:     if(*iter <=3){
1.157     brouard  2146:       tml = *localtime(&rcurr_time);
                   2147:       strcpy(strcurr,asctime(&tml));
                   2148:       rforecast_time=rcurr_time; 
1.126     brouard  2149:       itmp = strlen(strcurr);
                   2150:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.224     brouard  2151:                                strcurr[itmp-1]='\0';
1.162     brouard  2152:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2153:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2154:       for(niterf=10;niterf<=30;niterf+=10){
1.224     brouard  2155:                                rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2156:                                forecast_time = *localtime(&rforecast_time);
                   2157:                                strcpy(strfor,asctime(&forecast_time));
                   2158:                                itmp = strlen(strfor);
                   2159:                                if(strfor[itmp-1]=='\n')
                   2160:                                        strfor[itmp-1]='\0';
                   2161:                                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);
                   2162:                                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  2163:       }
                   2164:     }
1.187     brouard  2165:     for (i=1;i<=n;i++) { /* For each direction i */
                   2166:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2167:       fptt=(*fret); 
                   2168: #ifdef DEBUG
1.203     brouard  2169:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2170:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2171: #endif
1.203     brouard  2172:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2173:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2174: #ifdef LINMINORIGINAL
1.188     brouard  2175:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2176: #else
                   2177:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2178:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2179: #endif
                   2180:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2181:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2182:                                /* because that direction will be replaced unless the gain del is small */
                   2183:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2184:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2185:                                /* with the new direction. */
                   2186:                                del=fabs(fptt-(*fret)); 
                   2187:                                ibig=i; 
1.126     brouard  2188:       } 
                   2189: #ifdef DEBUG
                   2190:       printf("%d %.12e",i,(*fret));
                   2191:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2192:       for (j=1;j<=n;j++) {
1.224     brouard  2193:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2194:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2195:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2196:       }
                   2197:       for(j=1;j<=n;j++) {
1.225     brouard  2198:                                printf(" p(%d)=%.12e",j,p[j]);
                   2199:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2200:       }
                   2201:       printf("\n");
                   2202:       fprintf(ficlog,"\n");
                   2203: #endif
1.187     brouard  2204:     } /* end loop on each direction i */
                   2205:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2206:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2207:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2208:       for(j=1;j<=n;j++) {
1.225     brouard  2209:                                if(flatdir[j] >0){
                   2210:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2211:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2212:                                }
                   2213:                                /* printf("\n"); */
                   2214:                                /* fprintf(ficlog,"\n"); */
                   2215:                        }
1.182     brouard  2216:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  2217:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2218:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2219:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2220:       /* decreased of more than 3.84  */
                   2221:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2222:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2223:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2224:                        
1.188     brouard  2225:       /* Starting the program with initial values given by a former maximization will simply change */
                   2226:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2227:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2228:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2229: #ifdef DEBUG
                   2230:       int k[2],l;
                   2231:       k[0]=1;
                   2232:       k[1]=-1;
                   2233:       printf("Max: %.12e",(*func)(p));
                   2234:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2235:       for (j=1;j<=n;j++) {
                   2236:        printf(" %.12e",p[j]);
                   2237:        fprintf(ficlog," %.12e",p[j]);
                   2238:       }
                   2239:       printf("\n");
                   2240:       fprintf(ficlog,"\n");
                   2241:       for(l=0;l<=1;l++) {
                   2242:        for (j=1;j<=n;j++) {
                   2243:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2244:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2245:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2246:        }
                   2247:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2248:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2249:       }
                   2250: #endif
                   2251: 
1.224     brouard  2252: #ifdef LINMINORIGINAL
                   2253: #else
                   2254:       free_ivector(flatdir,1,n); 
                   2255: #endif
1.126     brouard  2256:       free_vector(xit,1,n); 
                   2257:       free_vector(xits,1,n); 
                   2258:       free_vector(ptt,1,n); 
                   2259:       free_vector(pt,1,n); 
                   2260:       return; 
1.192     brouard  2261:     } /* enough precision */ 
1.240   ! brouard  2262:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2263:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2264:       ptt[j]=2.0*p[j]-pt[j]; 
                   2265:       xit[j]=p[j]-pt[j]; 
                   2266:       pt[j]=p[j]; 
                   2267:     } 
1.181     brouard  2268:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2269: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2270:                if (*iter <=4) {
1.225     brouard  2271: #else
                   2272: #endif
1.224     brouard  2273: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2274: #else
1.161     brouard  2275:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2276: #endif
1.162     brouard  2277:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2278:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2279:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2280:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2281:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2282:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2283:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2284:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2285:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2286:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2287:       /* mu² and del² are equal when f3=f1 */
                   2288:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2289:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2290:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2291:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2292: #ifdef NRCORIGINAL
                   2293:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2294: #else
                   2295:       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  2296:       t= t- del*SQR(fp-fptt);
1.183     brouard  2297: #endif
1.202     brouard  2298:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2299: #ifdef DEBUG
1.181     brouard  2300:       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);
                   2301:       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  2302:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2303:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2304:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2305:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2306:       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);
                   2307:       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);
                   2308: #endif
1.183     brouard  2309: #ifdef POWELLORIGINAL
                   2310:       if (t < 0.0) { /* Then we use it for new direction */
                   2311: #else
1.182     brouard  2312:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2313:                                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  2314:         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  2315:         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  2316:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2317:       } 
1.181     brouard  2318:       if (directest < 0.0) { /* Then we use it for new direction */
                   2319: #endif
1.191     brouard  2320: #ifdef DEBUGLINMIN
1.234     brouard  2321:        printf("Before linmin in direction P%d-P0\n",n);
                   2322:        for (j=1;j<=n;j++) {
                   2323:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2324:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2325:          if(j % ncovmodel == 0){
                   2326:            printf("\n");
                   2327:            fprintf(ficlog,"\n");
                   2328:          }
                   2329:        }
1.224     brouard  2330: #endif
                   2331: #ifdef LINMINORIGINAL
1.234     brouard  2332:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2333: #else
1.234     brouard  2334:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2335:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2336: #endif
1.234     brouard  2337:        
1.191     brouard  2338: #ifdef DEBUGLINMIN
1.234     brouard  2339:        for (j=1;j<=n;j++) { 
                   2340:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2341:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2342:          if(j % ncovmodel == 0){
                   2343:            printf("\n");
                   2344:            fprintf(ficlog,"\n");
                   2345:          }
                   2346:        }
1.224     brouard  2347: #endif
1.234     brouard  2348:        for (j=1;j<=n;j++) { 
                   2349:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2350:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2351:        }
1.224     brouard  2352: #ifdef LINMINORIGINAL
                   2353: #else
1.234     brouard  2354:        for (j=1, flatd=0;j<=n;j++) {
                   2355:          if(flatdir[j]>0)
                   2356:            flatd++;
                   2357:        }
                   2358:        if(flatd >0){
                   2359:          printf("%d flat directions\n",flatd);
                   2360:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2361:          for (j=1;j<=n;j++) { 
                   2362:            if(flatdir[j]>0){
                   2363:              printf("%d ",j);
                   2364:              fprintf(ficlog,"%d ",j);
                   2365:            }
                   2366:          }
                   2367:          printf("\n");
                   2368:          fprintf(ficlog,"\n");
                   2369:        }
1.191     brouard  2370: #endif
1.234     brouard  2371:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2372:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2373:        
1.126     brouard  2374: #ifdef DEBUG
1.234     brouard  2375:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2376:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2377:        for(j=1;j<=n;j++){
                   2378:          printf(" %lf",xit[j]);
                   2379:          fprintf(ficlog," %lf",xit[j]);
                   2380:        }
                   2381:        printf("\n");
                   2382:        fprintf(ficlog,"\n");
1.126     brouard  2383: #endif
1.192     brouard  2384:       } /* end of t or directest negative */
1.224     brouard  2385: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2386: #else
1.234     brouard  2387:       } /* end if (fptt < fp)  */
1.192     brouard  2388: #endif
1.225     brouard  2389: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2390:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2391: #else
1.224     brouard  2392: #endif
1.234     brouard  2393:                } /* loop iteration */ 
1.126     brouard  2394: } 
1.234     brouard  2395:   
1.126     brouard  2396: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2397:   
1.235     brouard  2398:   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  2399:   {
1.235     brouard  2400:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2401:        (and selected quantitative values in nres)
                   2402:        by left multiplying the unit
1.234     brouard  2403:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2404:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2405:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2406:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2407:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2408:   /* Initial matrix pimij */
                   2409:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2410:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2411:   /*  0,                   0                  , 1} */
                   2412:   /*
                   2413:    * and after some iteration: */
                   2414:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2415:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2416:   /*  0,                   0                  , 1} */
                   2417:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2418:   /* {0.51571254859325999, 0.4842874514067399, */
                   2419:   /*  0.51326036147820708, 0.48673963852179264} */
                   2420:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2421:     
1.126     brouard  2422:   int i, ii,j,k;
1.209     brouard  2423:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2424:   /* double **matprod2(); */ /* test */
1.218     brouard  2425:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2426:   double **newm;
1.209     brouard  2427:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2428:   int ncvloop=0;
1.169     brouard  2429:   
1.209     brouard  2430:   min=vector(1,nlstate);
                   2431:   max=vector(1,nlstate);
                   2432:   meandiff=vector(1,nlstate);
                   2433: 
1.218     brouard  2434:        /* Starting with matrix unity */
1.126     brouard  2435:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2436:     for (j=1;j<=nlstate+ndeath;j++){
                   2437:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2438:     }
1.169     brouard  2439:   
                   2440:   cov[1]=1.;
                   2441:   
                   2442:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2443:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2444:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2445:     ncvloop++;
1.126     brouard  2446:     newm=savm;
                   2447:     /* Covariates have to be included here again */
1.138     brouard  2448:     cov[2]=agefin;
1.187     brouard  2449:     if(nagesqr==1)
                   2450:       cov[3]= agefin*agefin;;
1.234     brouard  2451:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2452:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2453:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2454:       /* 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  2455:     }
                   2456:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2457:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2458:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2459:       /* 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  2460:     }
1.237     brouard  2461:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2462:       if(Dummy[Tvar[Tage[k]]]){
                   2463:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2464:       } else{
1.235     brouard  2465:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2466:       }
1.235     brouard  2467:       /* 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  2468:     }
1.237     brouard  2469:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2470:       /* 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  2471:       if(Dummy[Tvard[k][1]==0]){
                   2472:        if(Dummy[Tvard[k][2]==0]){
                   2473:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2474:        }else{
                   2475:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2476:        }
                   2477:       }else{
                   2478:        if(Dummy[Tvard[k][2]==0]){
                   2479:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2480:        }else{
                   2481:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2482:        }
                   2483:       }
1.234     brouard  2484:     }
1.138     brouard  2485:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2486:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2487:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2488:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2489:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2490:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2491:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2492:     
1.126     brouard  2493:     savm=oldm;
                   2494:     oldm=newm;
1.209     brouard  2495: 
                   2496:     for(j=1; j<=nlstate; j++){
                   2497:       max[j]=0.;
                   2498:       min[j]=1.;
                   2499:     }
                   2500:     for(i=1;i<=nlstate;i++){
                   2501:       sumnew=0;
                   2502:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2503:       for(j=1; j<=nlstate; j++){ 
                   2504:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2505:        max[j]=FMAX(max[j],prlim[i][j]);
                   2506:        min[j]=FMIN(min[j],prlim[i][j]);
                   2507:       }
                   2508:     }
                   2509: 
1.126     brouard  2510:     maxmax=0.;
1.209     brouard  2511:     for(j=1; j<=nlstate; j++){
                   2512:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2513:       maxmax=FMAX(maxmax,meandiff[j]);
                   2514:       /* 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  2515:     } /* j loop */
1.203     brouard  2516:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2517:     /* 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  2518:     if(maxmax < ftolpl){
1.209     brouard  2519:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2520:       free_vector(min,1,nlstate);
                   2521:       free_vector(max,1,nlstate);
                   2522:       free_vector(meandiff,1,nlstate);
1.126     brouard  2523:       return prlim;
                   2524:     }
1.169     brouard  2525:   } /* age loop */
1.208     brouard  2526:     /* After some age loop it doesn't converge */
1.209     brouard  2527:   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  2528: 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  2529:   /* 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); */
                   2530:   free_vector(min,1,nlstate);
                   2531:   free_vector(max,1,nlstate);
                   2532:   free_vector(meandiff,1,nlstate);
1.208     brouard  2533:   
1.169     brouard  2534:   return prlim; /* should not reach here */
1.126     brouard  2535: }
                   2536: 
1.217     brouard  2537: 
                   2538:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2539: 
1.218     brouard  2540:  /* 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) */
                   2541:  /* 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) */
                   2542:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2543: {
1.218     brouard  2544:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2545:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2546:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2547:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2548:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2549:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2550:   /* Initial matrix pimij */
                   2551:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2552:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2553:   /*  0,                   0                  , 1} */
                   2554:   /*
                   2555:    * and after some iteration: */
                   2556:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2557:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2558:   /*  0,                   0                  , 1} */
                   2559:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2560:   /* {0.51571254859325999, 0.4842874514067399, */
                   2561:   /*  0.51326036147820708, 0.48673963852179264} */
                   2562:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2563: 
                   2564:   int i, ii,j,k;
                   2565:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2566:   /* double **matprod2(); */ /* test */
                   2567:   double **out, cov[NCOVMAX+1], **bmij();
                   2568:   double **newm;
1.218     brouard  2569:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2570:   double        **oldm, **savm;  /* for use */
                   2571: 
1.217     brouard  2572:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2573:   int ncvloop=0;
                   2574:   
                   2575:   min=vector(1,nlstate);
                   2576:   max=vector(1,nlstate);
                   2577:   meandiff=vector(1,nlstate);
                   2578: 
1.218     brouard  2579:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2580:        oldm=oldms; savm=savms;
                   2581: 
                   2582:        /* Starting with matrix unity */
                   2583:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2584:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2585:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2586:     }
                   2587:   
                   2588:   cov[1]=1.;
                   2589:   
                   2590:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2591:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2592:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2593:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2594:     ncvloop++;
1.218     brouard  2595:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2596:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2597:     /* Covariates have to be included here again */
                   2598:     cov[2]=agefin;
                   2599:     if(nagesqr==1)
                   2600:       cov[3]= agefin*agefin;;
                   2601:     for (k=1; k<=cptcovn;k++) {
                   2602:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2603:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2604:       /* 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])]); */
                   2605:     }
                   2606:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2607:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2608:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2609:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2610:     
                   2611:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2612:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2613:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2614:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2615:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2616:                /* ij should be linked to the correct index of cov */
                   2617:                /* age and covariate values ij are in 'cov', but we need to pass
                   2618:                 * ij for the observed prevalence at age and status and covariate
                   2619:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2620:                 */
                   2621:     /* 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 *\/ */
                   2622:     /* 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 *\/ */
                   2623:     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  2624:     savm=oldm;
                   2625:     oldm=newm;
                   2626:     for(j=1; j<=nlstate; j++){
                   2627:       max[j]=0.;
                   2628:       min[j]=1.;
                   2629:     }
                   2630:     for(j=1; j<=nlstate; j++){ 
                   2631:       for(i=1;i<=nlstate;i++){
1.234     brouard  2632:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2633:        bprlim[i][j]= newm[i][j];
                   2634:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2635:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2636:       }
                   2637:     }
1.218     brouard  2638:                
1.217     brouard  2639:     maxmax=0.;
                   2640:     for(i=1; i<=nlstate; i++){
                   2641:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2642:       maxmax=FMAX(maxmax,meandiff[i]);
                   2643:       /* 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); */
                   2644:     } /* j loop */
                   2645:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2646:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2647:     if(maxmax < ftolpl){
1.220     brouard  2648:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2649:       free_vector(min,1,nlstate);
                   2650:       free_vector(max,1,nlstate);
                   2651:       free_vector(meandiff,1,nlstate);
                   2652:       return bprlim;
                   2653:     }
                   2654:   } /* age loop */
                   2655:     /* After some age loop it doesn't converge */
                   2656:   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\
                   2657: 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);
                   2658:   /* 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); */
                   2659:   free_vector(min,1,nlstate);
                   2660:   free_vector(max,1,nlstate);
                   2661:   free_vector(meandiff,1,nlstate);
                   2662:   
                   2663:   return bprlim; /* should not reach here */
                   2664: }
                   2665: 
1.126     brouard  2666: /*************** transition probabilities ***************/ 
                   2667: 
                   2668: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2669: {
1.138     brouard  2670:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2671:      computes the probability to be observed in state j being in state i by appying the
                   2672:      model to the ncovmodel covariates (including constant and age).
                   2673:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2674:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2675:      ncth covariate in the global vector x is given by the formula:
                   2676:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2677:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2678:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2679:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2680:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2681:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2682:   */
                   2683:   double s1, lnpijopii;
1.126     brouard  2684:   /*double t34;*/
1.164     brouard  2685:   int i,j, nc, ii, jj;
1.126     brouard  2686: 
1.223     brouard  2687:   for(i=1; i<= nlstate; i++){
                   2688:     for(j=1; j<i;j++){
                   2689:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2690:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2691:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2692:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2693:       }
                   2694:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2695:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2696:     }
                   2697:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2698:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2699:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2700:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2701:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2702:       }
                   2703:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2704:     }
                   2705:   }
1.218     brouard  2706:   
1.223     brouard  2707:   for(i=1; i<= nlstate; i++){
                   2708:     s1=0;
                   2709:     for(j=1; j<i; j++){
                   2710:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2711:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2712:     }
                   2713:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2714:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2715:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2716:     }
                   2717:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2718:     ps[i][i]=1./(s1+1.);
                   2719:     /* Computing other pijs */
                   2720:     for(j=1; j<i; j++)
                   2721:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2722:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2723:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2724:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2725:   } /* end i */
1.218     brouard  2726:   
1.223     brouard  2727:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2728:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2729:       ps[ii][jj]=0;
                   2730:       ps[ii][ii]=1;
                   2731:     }
                   2732:   }
1.218     brouard  2733:   
                   2734:   
1.223     brouard  2735:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2736:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2737:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2738:   /*   } */
                   2739:   /*   printf("\n "); */
                   2740:   /* } */
                   2741:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2742:   /*
                   2743:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2744:                goto end;*/
1.223     brouard  2745:   return ps;
1.126     brouard  2746: }
                   2747: 
1.218     brouard  2748: /*************** backward transition probabilities ***************/ 
                   2749: 
                   2750:  /* 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 ) */
                   2751: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2752:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2753: {
1.222     brouard  2754:   /* Computes the backward probability at age agefin and covariate ij
                   2755:    * and returns in **ps as well as **bmij.
                   2756:    */
1.218     brouard  2757:   int i, ii, j,k;
1.222     brouard  2758:   
                   2759:   double **out, **pmij();
                   2760:   double sumnew=0.;
1.218     brouard  2761:   double agefin;
1.222     brouard  2762:   
                   2763:   double **dnewm, **dsavm, **doldm;
                   2764:   double **bbmij;
                   2765:   
1.218     brouard  2766:   doldm=ddoldms; /* global pointers */
1.222     brouard  2767:   dnewm=ddnewms;
                   2768:   dsavm=ddsavms;
                   2769:   
                   2770:   agefin=cov[2];
                   2771:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2772:      the observed prevalence (with this covariate ij) */
                   2773:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2774:   /* We do have the matrix Px in savm  and we need pij */
                   2775:   for (j=1;j<=nlstate+ndeath;j++){
                   2776:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2777:     for (ii=1;ii<=nlstate;ii++){
                   2778:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2779:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2780:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2781:       if(sumnew >= 1.e-10){
                   2782:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2783:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2784:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2785:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2786:        /* }else */
                   2787:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2788:       }else{
                   2789:        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);
                   2790:       }
                   2791:     } /*End ii */
                   2792:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2793:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2794:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2795:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2796:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2797:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2798:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2799:   for (j=1;j<=nlstate+ndeath;j++){
                   2800:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2801:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2802:     }
                   2803:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2804:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2805:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2806:   /* end bmij */
                   2807:   return ps; 
1.218     brouard  2808: }
1.217     brouard  2809: /*************** transition probabilities ***************/ 
                   2810: 
1.218     brouard  2811: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2812: {
                   2813:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2814:      computes the probability to be observed in state j being in state i by appying the
                   2815:      model to the ncovmodel covariates (including constant and age).
                   2816:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2817:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2818:      ncth covariate in the global vector x is given by the formula:
                   2819:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2820:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2821:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2822:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2823:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2824:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2825:   */
                   2826:   double s1, lnpijopii;
                   2827:   /*double t34;*/
                   2828:   int i,j, nc, ii, jj;
                   2829: 
1.234     brouard  2830:   for(i=1; i<= nlstate; i++){
                   2831:     for(j=1; j<i;j++){
                   2832:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2833:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2834:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2835:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2836:       }
                   2837:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2838:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2839:     }
                   2840:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2841:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2842:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2843:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2844:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2845:       }
                   2846:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2847:     }
                   2848:   }
                   2849:   
                   2850:   for(i=1; i<= nlstate; i++){
                   2851:     s1=0;
                   2852:     for(j=1; j<i; j++){
                   2853:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2854:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2855:     }
                   2856:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2857:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2858:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2859:     }
                   2860:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2861:     ps[i][i]=1./(s1+1.);
                   2862:     /* Computing other pijs */
                   2863:     for(j=1; j<i; j++)
                   2864:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2865:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2866:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2867:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2868:   } /* end i */
                   2869:   
                   2870:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2871:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2872:       ps[ii][jj]=0;
                   2873:       ps[ii][ii]=1;
                   2874:     }
                   2875:   }
                   2876:   /* Added for backcast */ /* Transposed matrix too */
                   2877:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2878:     s1=0.;
                   2879:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2880:       s1+=ps[ii][jj];
                   2881:     }
                   2882:     for(ii=1; ii<= nlstate; ii++){
                   2883:       ps[ii][jj]=ps[ii][jj]/s1;
                   2884:     }
                   2885:   }
                   2886:   /* Transposition */
                   2887:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2888:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2889:       s1=ps[ii][jj];
                   2890:       ps[ii][jj]=ps[jj][ii];
                   2891:       ps[jj][ii]=s1;
                   2892:     }
                   2893:   }
                   2894:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2895:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2896:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2897:   /*   } */
                   2898:   /*   printf("\n "); */
                   2899:   /* } */
                   2900:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2901:   /*
                   2902:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2903:     goto end;*/
                   2904:   return ps;
1.217     brouard  2905: }
                   2906: 
                   2907: 
1.126     brouard  2908: /**************** Product of 2 matrices ******************/
                   2909: 
1.145     brouard  2910: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2911: {
                   2912:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2913:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2914:   /* in, b, out are matrice of pointers which should have been initialized 
                   2915:      before: only the contents of out is modified. The function returns
                   2916:      a pointer to pointers identical to out */
1.145     brouard  2917:   int i, j, k;
1.126     brouard  2918:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2919:     for(k=ncolol; k<=ncoloh; k++){
                   2920:       out[i][k]=0.;
                   2921:       for(j=ncl; j<=nch; j++)
                   2922:        out[i][k] +=in[i][j]*b[j][k];
                   2923:     }
1.126     brouard  2924:   return out;
                   2925: }
                   2926: 
                   2927: 
                   2928: /************* Higher Matrix Product ***************/
                   2929: 
1.235     brouard  2930: 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  2931: {
1.218     brouard  2932:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2933:      'nhstepm*hstepm*stepm' months (i.e. until
                   2934:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2935:      nhstepm*hstepm matrices. 
                   2936:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2937:      (typically every 2 years instead of every month which is too big 
                   2938:      for the memory).
                   2939:      Model is determined by parameters x and covariates have to be 
                   2940:      included manually here. 
                   2941: 
                   2942:      */
                   2943: 
                   2944:   int i, j, d, h, k;
1.131     brouard  2945:   double **out, cov[NCOVMAX+1];
1.126     brouard  2946:   double **newm;
1.187     brouard  2947:   double agexact;
1.214     brouard  2948:   double agebegin, ageend;
1.126     brouard  2949: 
                   2950:   /* Hstepm could be zero and should return the unit matrix */
                   2951:   for (i=1;i<=nlstate+ndeath;i++)
                   2952:     for (j=1;j<=nlstate+ndeath;j++){
                   2953:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2954:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2955:     }
                   2956:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2957:   for(h=1; h <=nhstepm; h++){
                   2958:     for(d=1; d <=hstepm; d++){
                   2959:       newm=savm;
                   2960:       /* Covariates have to be included here again */
                   2961:       cov[1]=1.;
1.214     brouard  2962:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2963:       cov[2]=agexact;
                   2964:       if(nagesqr==1)
1.227     brouard  2965:        cov[3]= agexact*agexact;
1.235     brouard  2966:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2967:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2968:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2969:        /* 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)); */
                   2970:       }
                   2971:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2972:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2973:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2974:        /* 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]); */
                   2975:       }
                   2976:       for (k=1; k<=cptcovage;k++){
                   2977:        if(Dummy[Tvar[Tage[k]]]){
                   2978:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2979:        } else{
                   2980:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2981:        }
                   2982:        /* 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]); */
                   2983:       }
                   2984:       for (k=1; k<=cptcovprod;k++){ /*  */
                   2985:        /* 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]); */
                   2986:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2987:       }
                   2988:       /* for (k=1; k<=cptcovn;k++)  */
                   2989:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2990:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   2991:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2992:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   2993:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  2994:       
                   2995:       
1.126     brouard  2996:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2997:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2998:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2999:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3000:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3001:       /* if((int)age == 70){ */
                   3002:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3003:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3004:       /*         printf("%d pmmij ",i); */
                   3005:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3006:       /*           printf("%f ",pmmij[i][j]); */
                   3007:       /*         } */
                   3008:       /*         printf(" oldm "); */
                   3009:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3010:       /*           printf("%f ",oldm[i][j]); */
                   3011:       /*         } */
                   3012:       /*         printf("\n"); */
                   3013:       /*       } */
                   3014:       /* } */
1.126     brouard  3015:       savm=oldm;
                   3016:       oldm=newm;
                   3017:     }
                   3018:     for(i=1; i<=nlstate+ndeath; i++)
                   3019:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3020:                                po[i][j][h]=newm[i][j];
                   3021:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3022:       }
1.128     brouard  3023:     /*printf("h=%d ",h);*/
1.126     brouard  3024:   } /* end h */
1.218     brouard  3025:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3026:   return po;
                   3027: }
                   3028: 
1.217     brouard  3029: /************* Higher Back Matrix Product ***************/
1.218     brouard  3030: /* 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  3031: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3032: {
1.218     brouard  3033:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3034:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3035:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3036:      nhstepm*hstepm matrices.
                   3037:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3038:      (typically every 2 years instead of every month which is too big
1.217     brouard  3039:      for the memory).
1.218     brouard  3040:      Model is determined by parameters x and covariates have to be
                   3041:      included manually here.
1.217     brouard  3042: 
1.222     brouard  3043:   */
1.217     brouard  3044: 
                   3045:   int i, j, d, h, k;
                   3046:   double **out, cov[NCOVMAX+1];
                   3047:   double **newm;
                   3048:   double agexact;
                   3049:   double agebegin, ageend;
1.222     brouard  3050:   double **oldm, **savm;
1.217     brouard  3051: 
1.222     brouard  3052:   oldm=oldms;savm=savms;
1.217     brouard  3053:   /* Hstepm could be zero and should return the unit matrix */
                   3054:   for (i=1;i<=nlstate+ndeath;i++)
                   3055:     for (j=1;j<=nlstate+ndeath;j++){
                   3056:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3057:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3058:     }
                   3059:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3060:   for(h=1; h <=nhstepm; h++){
                   3061:     for(d=1; d <=hstepm; d++){
                   3062:       newm=savm;
                   3063:       /* Covariates have to be included here again */
                   3064:       cov[1]=1.;
                   3065:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3066:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3067:       cov[2]=agexact;
                   3068:       if(nagesqr==1)
1.222     brouard  3069:        cov[3]= agexact*agexact;
1.218     brouard  3070:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3071:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3072:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3073:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3074:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3075:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3076:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3077:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3078:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3079:       /* 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  3080:                        
                   3081:                        
1.217     brouard  3082:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3083:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3084:       /* Careful transposed matrix */
1.222     brouard  3085:       /* age is in cov[2] */
1.218     brouard  3086:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3087:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3088:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3089:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3090:       /* if((int)age == 70){ */
                   3091:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3092:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3093:       /*         printf("%d pmmij ",i); */
                   3094:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3095:       /*           printf("%f ",pmmij[i][j]); */
                   3096:       /*         } */
                   3097:       /*         printf(" oldm "); */
                   3098:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3099:       /*           printf("%f ",oldm[i][j]); */
                   3100:       /*         } */
                   3101:       /*         printf("\n"); */
                   3102:       /*       } */
                   3103:       /* } */
                   3104:       savm=oldm;
                   3105:       oldm=newm;
                   3106:     }
                   3107:     for(i=1; i<=nlstate+ndeath; i++)
                   3108:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3109:        po[i][j][h]=newm[i][j];
                   3110:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3111:       }
                   3112:     /*printf("h=%d ",h);*/
                   3113:   } /* end h */
1.222     brouard  3114:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3115:   return po;
                   3116: }
                   3117: 
                   3118: 
1.162     brouard  3119: #ifdef NLOPT
                   3120:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3121:   double fret;
                   3122:   double *xt;
                   3123:   int j;
                   3124:   myfunc_data *d2 = (myfunc_data *) pd;
                   3125: /* xt = (p1-1); */
                   3126:   xt=vector(1,n); 
                   3127:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3128: 
                   3129:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3130:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3131:   printf("Function = %.12lf ",fret);
                   3132:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3133:   printf("\n");
                   3134:  free_vector(xt,1,n);
                   3135:   return fret;
                   3136: }
                   3137: #endif
1.126     brouard  3138: 
                   3139: /*************** log-likelihood *************/
                   3140: double func( double *x)
                   3141: {
1.226     brouard  3142:   int i, ii, j, k, mi, d, kk;
                   3143:   int ioffset=0;
                   3144:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3145:   double **out;
                   3146:   double lli; /* Individual log likelihood */
                   3147:   int s1, s2;
1.228     brouard  3148:   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  3149:   double bbh, survp;
                   3150:   long ipmx;
                   3151:   double agexact;
                   3152:   /*extern weight */
                   3153:   /* We are differentiating ll according to initial status */
                   3154:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3155:   /*for(i=1;i<imx;i++) 
                   3156:     printf(" %d\n",s[4][i]);
                   3157:   */
1.162     brouard  3158: 
1.226     brouard  3159:   ++countcallfunc;
1.162     brouard  3160: 
1.226     brouard  3161:   cov[1]=1.;
1.126     brouard  3162: 
1.226     brouard  3163:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3164:   ioffset=0;
1.226     brouard  3165:   if(mle==1){
                   3166:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3167:       /* Computes the values of the ncovmodel covariates of the model
                   3168:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3169:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3170:         to be observed in j being in i according to the model.
                   3171:       */
                   3172:       ioffset=2+nagesqr+cptcovage;
1.233     brouard  3173:    /* Fixed */
1.234     brouard  3174:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3175:        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)*/
                   3176:       }
1.226     brouard  3177:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3178:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3179:         has been calculated etc */
                   3180:       /* For an individual i, wav[i] gives the number of effective waves */
                   3181:       /* We compute the contribution to Likelihood of each effective transition
                   3182:         mw[mi][i] is real wave of the mi th effectve wave */
                   3183:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3184:         s2=s[mw[mi+1][i]][i];
                   3185:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3186:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3187:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3188:       */
                   3189:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3190:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
                   3191:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
                   3192:        }
                   3193:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3194:          for (j=1;j<=nlstate+ndeath;j++){
                   3195:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3196:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3197:          }
                   3198:        for(d=0; d<dh[mi][i]; d++){
                   3199:          newm=savm;
                   3200:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3201:          cov[2]=agexact;
                   3202:          if(nagesqr==1)
                   3203:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3204:          for (kk=1; kk<=cptcovage;kk++) {
                   3205:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3206:          }
                   3207:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3208:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3209:          savm=oldm;
                   3210:          oldm=newm;
                   3211:        } /* end mult */
                   3212:        
                   3213:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3214:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3215:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3216:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3217:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3218:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3219:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3220:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3221:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3222:                                 * -stepm/2 to stepm/2 .
                   3223:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3224:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3225:                                 */
1.234     brouard  3226:        s1=s[mw[mi][i]][i];
                   3227:        s2=s[mw[mi+1][i]][i];
                   3228:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3229:        /* bias bh is positive if real duration
                   3230:         * is higher than the multiple of stepm and negative otherwise.
                   3231:         */
                   3232:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3233:        if( s2 > nlstate){ 
                   3234:          /* i.e. if s2 is a death state and if the date of death is known 
                   3235:             then the contribution to the likelihood is the probability to 
                   3236:             die between last step unit time and current  step unit time, 
                   3237:             which is also equal to probability to die before dh 
                   3238:             minus probability to die before dh-stepm . 
                   3239:             In version up to 0.92 likelihood was computed
                   3240:             as if date of death was unknown. Death was treated as any other
                   3241:             health state: the date of the interview describes the actual state
                   3242:             and not the date of a change in health state. The former idea was
                   3243:             to consider that at each interview the state was recorded
                   3244:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3245:             introduced the exact date of death then we should have modified
                   3246:             the contribution of an exact death to the likelihood. This new
                   3247:             contribution is smaller and very dependent of the step unit
                   3248:             stepm. It is no more the probability to die between last interview
                   3249:             and month of death but the probability to survive from last
                   3250:             interview up to one month before death multiplied by the
                   3251:             probability to die within a month. Thanks to Chris
                   3252:             Jackson for correcting this bug.  Former versions increased
                   3253:             mortality artificially. The bad side is that we add another loop
                   3254:             which slows down the processing. The difference can be up to 10%
                   3255:             lower mortality.
                   3256:          */
                   3257:          /* If, at the beginning of the maximization mostly, the
                   3258:             cumulative probability or probability to be dead is
                   3259:             constant (ie = 1) over time d, the difference is equal to
                   3260:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3261:             s1 at precedent wave, to be dead a month before current
                   3262:             wave is equal to probability, being at state s1 at
                   3263:             precedent wave, to be dead at mont of the current
                   3264:             wave. Then the observed probability (that this person died)
                   3265:             is null according to current estimated parameter. In fact,
                   3266:             it should be very low but not zero otherwise the log go to
                   3267:             infinity.
                   3268:          */
1.183     brouard  3269: /* #ifdef INFINITYORIGINAL */
                   3270: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3271: /* #else */
                   3272: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3273: /*         lli=log(mytinydouble); */
                   3274: /*       else */
                   3275: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3276: /* #endif */
1.226     brouard  3277:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3278:          
1.226     brouard  3279:        } else if  ( s2==-1 ) { /* alive */
                   3280:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3281:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3282:          /*survp += out[s1][j]; */
                   3283:          lli= log(survp);
                   3284:        }
                   3285:        else if  (s2==-4) { 
                   3286:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3287:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3288:          lli= log(survp); 
                   3289:        } 
                   3290:        else if  (s2==-5) { 
                   3291:          for (j=1,survp=0. ; j<=2; j++)  
                   3292:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3293:          lli= log(survp); 
                   3294:        } 
                   3295:        else{
                   3296:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3297:          /*  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 */
                   3298:        } 
                   3299:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3300:        /*if(lli ==000.0)*/
                   3301:        /*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); */
                   3302:        ipmx +=1;
                   3303:        sw += weight[i];
                   3304:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3305:        /* if (lli < log(mytinydouble)){ */
                   3306:        /*   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); */
                   3307:        /*   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]); */
                   3308:        /* } */
                   3309:       } /* end of wave */
                   3310:     } /* end of individual */
                   3311:   }  else if(mle==2){
                   3312:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3313:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3314:       for(mi=1; mi<= wav[i]-1; mi++){
                   3315:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3316:          for (j=1;j<=nlstate+ndeath;j++){
                   3317:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3318:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3319:          }
                   3320:        for(d=0; d<=dh[mi][i]; d++){
                   3321:          newm=savm;
                   3322:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3323:          cov[2]=agexact;
                   3324:          if(nagesqr==1)
                   3325:            cov[3]= agexact*agexact;
                   3326:          for (kk=1; kk<=cptcovage;kk++) {
                   3327:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3328:          }
                   3329:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3330:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3331:          savm=oldm;
                   3332:          oldm=newm;
                   3333:        } /* end mult */
                   3334:       
                   3335:        s1=s[mw[mi][i]][i];
                   3336:        s2=s[mw[mi+1][i]][i];
                   3337:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3338:        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 */
                   3339:        ipmx +=1;
                   3340:        sw += weight[i];
                   3341:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3342:       } /* end of wave */
                   3343:     } /* end of individual */
                   3344:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3345:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3346:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3347:       for(mi=1; mi<= wav[i]-1; mi++){
                   3348:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3349:          for (j=1;j<=nlstate+ndeath;j++){
                   3350:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3351:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3352:          }
                   3353:        for(d=0; d<dh[mi][i]; d++){
                   3354:          newm=savm;
                   3355:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3356:          cov[2]=agexact;
                   3357:          if(nagesqr==1)
                   3358:            cov[3]= agexact*agexact;
                   3359:          for (kk=1; kk<=cptcovage;kk++) {
                   3360:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3361:          }
                   3362:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3363:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3364:          savm=oldm;
                   3365:          oldm=newm;
                   3366:        } /* end mult */
                   3367:       
                   3368:        s1=s[mw[mi][i]][i];
                   3369:        s2=s[mw[mi+1][i]][i];
                   3370:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3371:        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 */
                   3372:        ipmx +=1;
                   3373:        sw += weight[i];
                   3374:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3375:       } /* end of wave */
                   3376:     } /* end of individual */
                   3377:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3378:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3379:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3380:       for(mi=1; mi<= wav[i]-1; mi++){
                   3381:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3382:          for (j=1;j<=nlstate+ndeath;j++){
                   3383:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3384:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3385:          }
                   3386:        for(d=0; d<dh[mi][i]; d++){
                   3387:          newm=savm;
                   3388:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3389:          cov[2]=agexact;
                   3390:          if(nagesqr==1)
                   3391:            cov[3]= agexact*agexact;
                   3392:          for (kk=1; kk<=cptcovage;kk++) {
                   3393:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3394:          }
1.126     brouard  3395:        
1.226     brouard  3396:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3397:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3398:          savm=oldm;
                   3399:          oldm=newm;
                   3400:        } /* end mult */
                   3401:       
                   3402:        s1=s[mw[mi][i]][i];
                   3403:        s2=s[mw[mi+1][i]][i];
                   3404:        if( s2 > nlstate){ 
                   3405:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3406:        } else if  ( s2==-1 ) { /* alive */
                   3407:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3408:            survp += out[s1][j];
                   3409:          lli= log(survp);
                   3410:        }else{
                   3411:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3412:        }
                   3413:        ipmx +=1;
                   3414:        sw += weight[i];
                   3415:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3416: /*     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  3417:       } /* end of wave */
                   3418:     } /* end of individual */
                   3419:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3420:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3421:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3422:       for(mi=1; mi<= wav[i]-1; mi++){
                   3423:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3424:          for (j=1;j<=nlstate+ndeath;j++){
                   3425:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3426:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3427:          }
                   3428:        for(d=0; d<dh[mi][i]; d++){
                   3429:          newm=savm;
                   3430:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3431:          cov[2]=agexact;
                   3432:          if(nagesqr==1)
                   3433:            cov[3]= agexact*agexact;
                   3434:          for (kk=1; kk<=cptcovage;kk++) {
                   3435:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3436:          }
1.126     brouard  3437:        
1.226     brouard  3438:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3439:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3440:          savm=oldm;
                   3441:          oldm=newm;
                   3442:        } /* end mult */
                   3443:       
                   3444:        s1=s[mw[mi][i]][i];
                   3445:        s2=s[mw[mi+1][i]][i];
                   3446:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3447:        ipmx +=1;
                   3448:        sw += weight[i];
                   3449:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3450:        /*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]);*/
                   3451:       } /* end of wave */
                   3452:     } /* end of individual */
                   3453:   } /* End of if */
                   3454:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3455:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3456:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3457:   return -l;
1.126     brouard  3458: }
                   3459: 
                   3460: /*************** log-likelihood *************/
                   3461: double funcone( double *x)
                   3462: {
1.228     brouard  3463:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3464:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3465:   int ioffset=0;
1.131     brouard  3466:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3467:   double **out;
                   3468:   double lli; /* Individual log likelihood */
                   3469:   double llt;
                   3470:   int s1, s2;
1.228     brouard  3471:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3472: 
1.126     brouard  3473:   double bbh, survp;
1.187     brouard  3474:   double agexact;
1.214     brouard  3475:   double agebegin, ageend;
1.126     brouard  3476:   /*extern weight */
                   3477:   /* We are differentiating ll according to initial status */
                   3478:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3479:   /*for(i=1;i<imx;i++) 
                   3480:     printf(" %d\n",s[4][i]);
                   3481:   */
                   3482:   cov[1]=1.;
                   3483: 
                   3484:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3485:   ioffset=0;
                   3486:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.225     brouard  3487:     ioffset=2+nagesqr+cptcovage;
1.232     brouard  3488:     /* Fixed */
1.224     brouard  3489:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3490:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3491:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3492:       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)*/
                   3493: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3494: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3495: /*    cov[2+6]=covar[2][i]; V2  */
                   3496: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3497: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3498: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3499: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3500: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3501: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3502:     }
1.232     brouard  3503:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3504:     /*   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?)*\/ */
                   3505:     /* } */
1.231     brouard  3506:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3507:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3508:     /* } */
1.225     brouard  3509:     
1.233     brouard  3510: 
                   3511:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3512:     /* Wave varying (but not age varying) */
                   3513:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.233     brouard  3514:                                cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
1.232     brouard  3515:                        }
                   3516:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.231     brouard  3517:                                /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3518:                                /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
1.232     brouard  3519:                                /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3520:                                /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
1.231     brouard  3521:                                /* 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  3522:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3523:                        /*      iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3524:                        /*      /\* 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]); *\/ */
                   3525:                        /*      cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3526:       /* } */
1.126     brouard  3527:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.231     brouard  3528:                                for (j=1;j<=nlstate+ndeath;j++){
                   3529:                                        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3530:                                        savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3531:                                }
1.214     brouard  3532:       
                   3533:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3534:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3535:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.231     brouard  3536:                                /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3537:                                        and mw[mi+1][i]. dh depends on stepm.*/
                   3538:                                newm=savm;
                   3539:                                agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3540:                                cov[2]=agexact;
                   3541:                                if(nagesqr==1)
                   3542:                                        cov[3]= agexact*agexact;
                   3543:                                for (kk=1; kk<=cptcovage;kk++) {
                   3544:                                        cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3545:                                }
                   3546:                                /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3547:                                /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3548:                                out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3549:                                                                                 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3550:                                /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3551:                                /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3552:                                savm=oldm;
                   3553:                                oldm=newm;
1.126     brouard  3554:       } /* end mult */
                   3555:       
                   3556:       s1=s[mw[mi][i]][i];
                   3557:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3558:       /* if(s2==-1){ */
                   3559:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3560:       /*       /\* exit(1); *\/ */
                   3561:       /* } */
1.126     brouard  3562:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3563:       /* bias is positive if real duration
                   3564:        * is higher than the multiple of stepm and negative otherwise.
                   3565:        */
                   3566:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.232     brouard  3567:                                lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3568:       } else if  ( s2==-1 ) { /* alive */
1.232     brouard  3569:                                for (j=1,survp=0. ; j<=nlstate; j++) 
                   3570:                                        survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3571:                                lli= log(survp);
1.126     brouard  3572:       }else if (mle==1){
1.232     brouard  3573:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3574:       } else if(mle==2){
1.232     brouard  3575:                                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  3576:       } else if(mle==3){  /* exponential inter-extrapolation */
1.232     brouard  3577:                                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  3578:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.232     brouard  3579:                                lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3580:       } else{  /* mle=0 back to 1 */
1.232     brouard  3581:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3582:                                /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3583:       } /* End of if */
                   3584:       ipmx +=1;
                   3585:       sw += weight[i];
                   3586:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3587:       /*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  3588:       if(globpr){
1.232     brouard  3589:                                fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3590:  %11.6f %11.6f %11.6f ", \
1.232     brouard  3591:                                                                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3592:                                                                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3593:                                for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3594:                                        llt +=ll[k]*gipmx/gsw;
                   3595:                                        fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3596:                                }
                   3597:                                fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3598:       }
1.232     brouard  3599:        } /* end of wave */
                   3600: } /* end of individual */
                   3601: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3602: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3603: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3604: if(globpr==0){ /* First time we count the contributions and weights */
                   3605:        gipmx=ipmx;
                   3606:        gsw=sw;
                   3607: }
                   3608: return -l;
1.126     brouard  3609: }
                   3610: 
                   3611: 
                   3612: /*************** function likelione ***********/
                   3613: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3614: {
                   3615:   /* This routine should help understanding what is done with 
                   3616:      the selection of individuals/waves and
                   3617:      to check the exact contribution to the likelihood.
                   3618:      Plotting could be done.
                   3619:    */
                   3620:   int k;
                   3621: 
                   3622:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3623:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3624:     strcat(fileresilk,fileresu);
1.126     brouard  3625:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3626:       printf("Problem with resultfile: %s\n", fileresilk);
                   3627:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3628:     }
1.214     brouard  3629:     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");
                   3630:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3631:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3632:     for(k=1; k<=nlstate; k++) 
                   3633:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3634:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3635:   }
                   3636: 
                   3637:   *fretone=(*funcone)(p);
                   3638:   if(*globpri !=0){
                   3639:     fclose(ficresilk);
1.205     brouard  3640:     if (mle ==0)
                   3641:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3642:     else if(mle >=1)
                   3643:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3644:     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  3645:     
1.208     brouard  3646:       
                   3647:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3648:       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  3649: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3650:     }
1.207     brouard  3651:     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  3652: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3653:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3654: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3655:     fflush(fichtm);
1.205     brouard  3656:   }
1.126     brouard  3657:   return;
                   3658: }
                   3659: 
                   3660: 
                   3661: /*********** Maximum Likelihood Estimation ***************/
                   3662: 
                   3663: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3664: {
1.165     brouard  3665:   int i,j, iter=0;
1.126     brouard  3666:   double **xi;
                   3667:   double fret;
                   3668:   double fretone; /* Only one call to likelihood */
                   3669:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3670: 
                   3671: #ifdef NLOPT
                   3672:   int creturn;
                   3673:   nlopt_opt opt;
                   3674:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3675:   double *lb;
                   3676:   double minf; /* the minimum objective value, upon return */
                   3677:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3678:   myfunc_data dinst, *d = &dinst;
                   3679: #endif
                   3680: 
                   3681: 
1.126     brouard  3682:   xi=matrix(1,npar,1,npar);
                   3683:   for (i=1;i<=npar;i++)
                   3684:     for (j=1;j<=npar;j++)
                   3685:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3686:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3687:   strcpy(filerespow,"POW_"); 
1.126     brouard  3688:   strcat(filerespow,fileres);
                   3689:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3690:     printf("Problem with resultfile: %s\n", filerespow);
                   3691:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3692:   }
                   3693:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3694:   for (i=1;i<=nlstate;i++)
                   3695:     for(j=1;j<=nlstate+ndeath;j++)
                   3696:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3697:   fprintf(ficrespow,"\n");
1.162     brouard  3698: #ifdef POWELL
1.126     brouard  3699:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3700: #endif
1.126     brouard  3701: 
1.162     brouard  3702: #ifdef NLOPT
                   3703: #ifdef NEWUOA
                   3704:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3705: #else
                   3706:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3707: #endif
                   3708:   lb=vector(0,npar-1);
                   3709:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3710:   nlopt_set_lower_bounds(opt, lb);
                   3711:   nlopt_set_initial_step1(opt, 0.1);
                   3712:   
                   3713:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3714:   d->function = func;
                   3715:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3716:   nlopt_set_min_objective(opt, myfunc, d);
                   3717:   nlopt_set_xtol_rel(opt, ftol);
                   3718:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3719:     printf("nlopt failed! %d\n",creturn); 
                   3720:   }
                   3721:   else {
                   3722:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3723:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3724:     iter=1; /* not equal */
                   3725:   }
                   3726:   nlopt_destroy(opt);
                   3727: #endif
1.126     brouard  3728:   free_matrix(xi,1,npar,1,npar);
                   3729:   fclose(ficrespow);
1.203     brouard  3730:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3731:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3732:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3733: 
                   3734: }
                   3735: 
                   3736: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3737: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3738: {
                   3739:   double  **a,**y,*x,pd;
1.203     brouard  3740:   /* double **hess; */
1.164     brouard  3741:   int i, j;
1.126     brouard  3742:   int *indx;
                   3743: 
                   3744:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3745:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3746:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3747:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3748:   double gompertz(double p[]);
1.203     brouard  3749:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3750: 
                   3751:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3752:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3753:   for (i=1;i<=npar;i++){
1.203     brouard  3754:     printf("%d-",i);fflush(stdout);
                   3755:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3756:    
                   3757:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3758:     
                   3759:     /*  printf(" %f ",p[i]);
                   3760:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3761:   }
                   3762:   
                   3763:   for (i=1;i<=npar;i++) {
                   3764:     for (j=1;j<=npar;j++)  {
                   3765:       if (j>i) { 
1.203     brouard  3766:        printf(".%d-%d",i,j);fflush(stdout);
                   3767:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3768:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3769:        
                   3770:        hess[j][i]=hess[i][j];    
                   3771:        /*printf(" %lf ",hess[i][j]);*/
                   3772:       }
                   3773:     }
                   3774:   }
                   3775:   printf("\n");
                   3776:   fprintf(ficlog,"\n");
                   3777: 
                   3778:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3779:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3780:   
                   3781:   a=matrix(1,npar,1,npar);
                   3782:   y=matrix(1,npar,1,npar);
                   3783:   x=vector(1,npar);
                   3784:   indx=ivector(1,npar);
                   3785:   for (i=1;i<=npar;i++)
                   3786:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3787:   ludcmp(a,npar,indx,&pd);
                   3788: 
                   3789:   for (j=1;j<=npar;j++) {
                   3790:     for (i=1;i<=npar;i++) x[i]=0;
                   3791:     x[j]=1;
                   3792:     lubksb(a,npar,indx,x);
                   3793:     for (i=1;i<=npar;i++){ 
                   3794:       matcov[i][j]=x[i];
                   3795:     }
                   3796:   }
                   3797: 
                   3798:   printf("\n#Hessian matrix#\n");
                   3799:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3800:   for (i=1;i<=npar;i++) { 
                   3801:     for (j=1;j<=npar;j++) { 
1.203     brouard  3802:       printf("%.6e ",hess[i][j]);
                   3803:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3804:     }
                   3805:     printf("\n");
                   3806:     fprintf(ficlog,"\n");
                   3807:   }
                   3808: 
1.203     brouard  3809:   /* printf("\n#Covariance matrix#\n"); */
                   3810:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3811:   /* for (i=1;i<=npar;i++) {  */
                   3812:   /*   for (j=1;j<=npar;j++) {  */
                   3813:   /*     printf("%.6e ",matcov[i][j]); */
                   3814:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3815:   /*   } */
                   3816:   /*   printf("\n"); */
                   3817:   /*   fprintf(ficlog,"\n"); */
                   3818:   /* } */
                   3819: 
1.126     brouard  3820:   /* Recompute Inverse */
1.203     brouard  3821:   /* for (i=1;i<=npar;i++) */
                   3822:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3823:   /* ludcmp(a,npar,indx,&pd); */
                   3824: 
                   3825:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3826: 
                   3827:   /* for (j=1;j<=npar;j++) { */
                   3828:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3829:   /*   x[j]=1; */
                   3830:   /*   lubksb(a,npar,indx,x); */
                   3831:   /*   for (i=1;i<=npar;i++){  */
                   3832:   /*     y[i][j]=x[i]; */
                   3833:   /*     printf("%.3e ",y[i][j]); */
                   3834:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3835:   /*   } */
                   3836:   /*   printf("\n"); */
                   3837:   /*   fprintf(ficlog,"\n"); */
                   3838:   /* } */
                   3839: 
                   3840:   /* Verifying the inverse matrix */
                   3841: #ifdef DEBUGHESS
                   3842:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3843: 
1.203     brouard  3844:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3845:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3846: 
                   3847:   for (j=1;j<=npar;j++) {
                   3848:     for (i=1;i<=npar;i++){ 
1.203     brouard  3849:       printf("%.2f ",y[i][j]);
                   3850:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3851:     }
                   3852:     printf("\n");
                   3853:     fprintf(ficlog,"\n");
                   3854:   }
1.203     brouard  3855: #endif
1.126     brouard  3856: 
                   3857:   free_matrix(a,1,npar,1,npar);
                   3858:   free_matrix(y,1,npar,1,npar);
                   3859:   free_vector(x,1,npar);
                   3860:   free_ivector(indx,1,npar);
1.203     brouard  3861:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3862: 
                   3863: 
                   3864: }
                   3865: 
                   3866: /*************** hessian matrix ****************/
                   3867: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3868: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3869:   int i;
                   3870:   int l=1, lmax=20;
1.203     brouard  3871:   double k1,k2, res, fx;
1.132     brouard  3872:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3873:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3874:   int k=0,kmax=10;
                   3875:   double l1;
                   3876: 
                   3877:   fx=func(x);
                   3878:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3879:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3880:     l1=pow(10,l);
                   3881:     delts=delt;
                   3882:     for(k=1 ; k <kmax; k=k+1){
                   3883:       delt = delta*(l1*k);
                   3884:       p2[theta]=x[theta] +delt;
1.145     brouard  3885:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3886:       p2[theta]=x[theta]-delt;
                   3887:       k2=func(p2)-fx;
                   3888:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3889:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3890:       
1.203     brouard  3891: #ifdef DEBUGHESSII
1.126     brouard  3892:       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);
                   3893:       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);
                   3894: #endif
                   3895:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3896:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3897:        k=kmax;
                   3898:       }
                   3899:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3900:        k=kmax; l=lmax*10;
1.126     brouard  3901:       }
                   3902:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3903:        delts=delt;
                   3904:       }
1.203     brouard  3905:     } /* End loop k */
1.126     brouard  3906:   }
                   3907:   delti[theta]=delts;
                   3908:   return res; 
                   3909:   
                   3910: }
                   3911: 
1.203     brouard  3912: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3913: {
                   3914:   int i;
1.164     brouard  3915:   int l=1, lmax=20;
1.126     brouard  3916:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3917:   double p2[MAXPARM+1];
1.203     brouard  3918:   int k, kmax=1;
                   3919:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3920: 
                   3921:   int firstime=0;
1.203     brouard  3922:   
1.126     brouard  3923:   fx=func(x);
1.203     brouard  3924:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3925:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3926:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3927:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3928:     k1=func(p2)-fx;
                   3929:   
1.203     brouard  3930:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3931:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3932:     k2=func(p2)-fx;
                   3933:   
1.203     brouard  3934:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3935:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3936:     k3=func(p2)-fx;
                   3937:   
1.203     brouard  3938:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3939:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3940:     k4=func(p2)-fx;
1.203     brouard  3941:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3942:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3943:       firstime=1;
1.203     brouard  3944:       kmax=kmax+10;
1.208     brouard  3945:     }
                   3946:     if(kmax >=10 || firstime ==1){
1.218     brouard  3947:       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);
                   3948:       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  3949:       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);
                   3950:       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);
                   3951:     }
                   3952: #ifdef DEBUGHESSIJ
                   3953:     v1=hess[thetai][thetai];
                   3954:     v2=hess[thetaj][thetaj];
                   3955:     cv12=res;
                   3956:     /* Computing eigen value of Hessian matrix */
                   3957:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3958:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3959:     if ((lc2 <0) || (lc1 <0) ){
                   3960:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3961:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3962:       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);
                   3963:       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);
                   3964:     }
1.126     brouard  3965: #endif
                   3966:   }
                   3967:   return res;
                   3968: }
                   3969: 
1.203     brouard  3970:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3971: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3972: /* { */
                   3973: /*   int i; */
                   3974: /*   int l=1, lmax=20; */
                   3975: /*   double k1,k2,k3,k4,res,fx; */
                   3976: /*   double p2[MAXPARM+1]; */
                   3977: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3978: /*   int k=0,kmax=10; */
                   3979: /*   double l1; */
                   3980:   
                   3981: /*   fx=func(x); */
                   3982: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3983: /*     l1=pow(10,l); */
                   3984: /*     delts=delt; */
                   3985: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3986: /*       delt = delti*(l1*k); */
                   3987: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3988: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3989: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3990: /*       k1=func(p2)-fx; */
                   3991:       
                   3992: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3993: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3994: /*       k2=func(p2)-fx; */
                   3995:       
                   3996: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3997: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3998: /*       k3=func(p2)-fx; */
                   3999:       
                   4000: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4001: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4002: /*       k4=func(p2)-fx; */
                   4003: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4004: /* #ifdef DEBUGHESSIJ */
                   4005: /*       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); */
                   4006: /*       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); */
                   4007: /* #endif */
                   4008: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4009: /*     k=kmax; */
                   4010: /*       } */
                   4011: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4012: /*     k=kmax; l=lmax*10; */
                   4013: /*       } */
                   4014: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4015: /*     delts=delt; */
                   4016: /*       } */
                   4017: /*     } /\* End loop k *\/ */
                   4018: /*   } */
                   4019: /*   delti[theta]=delts; */
                   4020: /*   return res;  */
                   4021: /* } */
                   4022: 
                   4023: 
1.126     brouard  4024: /************** Inverse of matrix **************/
                   4025: void ludcmp(double **a, int n, int *indx, double *d) 
                   4026: { 
                   4027:   int i,imax,j,k; 
                   4028:   double big,dum,sum,temp; 
                   4029:   double *vv; 
                   4030:  
                   4031:   vv=vector(1,n); 
                   4032:   *d=1.0; 
                   4033:   for (i=1;i<=n;i++) { 
                   4034:     big=0.0; 
                   4035:     for (j=1;j<=n;j++) 
                   4036:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   4037:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   4038:     vv[i]=1.0/big; 
                   4039:   } 
                   4040:   for (j=1;j<=n;j++) { 
                   4041:     for (i=1;i<j;i++) { 
                   4042:       sum=a[i][j]; 
                   4043:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4044:       a[i][j]=sum; 
                   4045:     } 
                   4046:     big=0.0; 
                   4047:     for (i=j;i<=n;i++) { 
                   4048:       sum=a[i][j]; 
                   4049:       for (k=1;k<j;k++) 
                   4050:        sum -= a[i][k]*a[k][j]; 
                   4051:       a[i][j]=sum; 
                   4052:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4053:        big=dum; 
                   4054:        imax=i; 
                   4055:       } 
                   4056:     } 
                   4057:     if (j != imax) { 
                   4058:       for (k=1;k<=n;k++) { 
                   4059:        dum=a[imax][k]; 
                   4060:        a[imax][k]=a[j][k]; 
                   4061:        a[j][k]=dum; 
                   4062:       } 
                   4063:       *d = -(*d); 
                   4064:       vv[imax]=vv[j]; 
                   4065:     } 
                   4066:     indx[j]=imax; 
                   4067:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4068:     if (j != n) { 
                   4069:       dum=1.0/(a[j][j]); 
                   4070:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4071:     } 
                   4072:   } 
                   4073:   free_vector(vv,1,n);  /* Doesn't work */
                   4074: ;
                   4075: } 
                   4076: 
                   4077: void lubksb(double **a, int n, int *indx, double b[]) 
                   4078: { 
                   4079:   int i,ii=0,ip,j; 
                   4080:   double sum; 
                   4081:  
                   4082:   for (i=1;i<=n;i++) { 
                   4083:     ip=indx[i]; 
                   4084:     sum=b[ip]; 
                   4085:     b[ip]=b[i]; 
                   4086:     if (ii) 
                   4087:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4088:     else if (sum) ii=i; 
                   4089:     b[i]=sum; 
                   4090:   } 
                   4091:   for (i=n;i>=1;i--) { 
                   4092:     sum=b[i]; 
                   4093:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4094:     b[i]=sum/a[i][i]; 
                   4095:   } 
                   4096: } 
                   4097: 
                   4098: void pstamp(FILE *fichier)
                   4099: {
1.196     brouard  4100:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4101: }
                   4102: 
                   4103: /************ Frequencies ********************/
1.226     brouard  4104: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4105:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4106:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4107: {  /* Some frequencies */
                   4108:   
1.227     brouard  4109:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4110:   int iind=0, iage=0;
                   4111:   int mi; /* Effective wave */
                   4112:   int first;
                   4113:   double ***freq; /* Frequencies */
                   4114:   double *meanq;
                   4115:   double **meanqt;
                   4116:   double *pp, **prop, *posprop, *pospropt;
                   4117:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4118:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4119:   double agebegin, ageend;
                   4120:     
                   4121:   pp=vector(1,nlstate);
                   4122:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4123:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4124:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4125:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4126:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4127:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4128:   strcpy(fileresp,"P_");
                   4129:   strcat(fileresp,fileresu);
                   4130:   /*strcat(fileresphtm,fileresu);*/
                   4131:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4132:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4133:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4134:     exit(0);
                   4135:   }
1.240   ! brouard  4136:   
1.226     brouard  4137:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4138:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4139:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4140:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4141:     fflush(ficlog);
                   4142:     exit(70); 
                   4143:   }
                   4144:   else{
                   4145:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240   ! brouard  4146: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4147: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4148:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4149:   }
1.237     brouard  4150:   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  4151:   
1.226     brouard  4152:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4153:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4154:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4155:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4156:     fflush(ficlog);
                   4157:     exit(70); 
1.240   ! brouard  4158:   } else{
1.226     brouard  4159:     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  4160: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4161: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4162:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4163:   }
1.240   ! brouard  4164:   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);
        !          4165:   
1.226     brouard  4166:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4167:   j1=0;
1.126     brouard  4168:   
1.227     brouard  4169:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4170:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4171:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240   ! brouard  4172:   
1.226     brouard  4173:   first=1;
1.240   ! brouard  4174:   
1.226     brouard  4175:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4176:      reference=low_education V1=0,V2=0
                   4177:      med_educ                V1=1 V2=0, 
                   4178:      high_educ               V1=0 V2=1
                   4179:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4180:   */
1.240   ! brouard  4181:   
1.227     brouard  4182:   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  4183:     posproptt=0.;
                   4184:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4185:       scanf("%d", i);*/
                   4186:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4187:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.240   ! brouard  4188:        for(m=iagemin; m <= iagemax+3; m++)
        !          4189:          freq[i][jk][m]=0;
        !          4190:     
1.226     brouard  4191:     for (i=1; i<=nlstate; i++)  {
                   4192:       for(m=iagemin; m <= iagemax+3; m++)
1.240   ! brouard  4193:        prop[i][m]=0;
1.226     brouard  4194:       posprop[i]=0;
                   4195:       pospropt[i]=0;
                   4196:     }
1.227     brouard  4197:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4198:     /*   meanq[z1]+=0.; */
                   4199:     /*   for(m=1;m<=lastpass;m++){ */
                   4200:     /*         meanqt[m][z1]=0.; */
                   4201:     /*   } */
                   4202:     /* } */
1.240   ! brouard  4203:     
1.226     brouard  4204:     dateintsum=0;
                   4205:     k2cpt=0;
1.227     brouard  4206:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4207:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4208:       bool=1;
1.227     brouard  4209:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4210:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4211:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4212:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4213:          /* } */
1.234     brouard  4214:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4215:            /* if(Tvaraff[z1] ==-20){ */
                   4216:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4217:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4218:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4219:            /* }else  */
                   4220:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4221:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4222:              bool=0;
                   4223:              /* 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", 
                   4224:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4225:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4226:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4227:            } /* Onlyf fixed */
                   4228:          } /* end z1 */
                   4229:        } /* cptcovn > 0 */
1.227     brouard  4230:       } /* end any */
                   4231:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4232:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4233:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4234:          m=mw[mi][iind];
                   4235:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4236:            for (z1=1; z1<=cptcoveff; z1++) {
                   4237:              if( Fixed[Tmodelind[z1]]==1){
                   4238:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4239:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4240:                  bool=0;
                   4241:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4242:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4243:                  bool=0;
                   4244:                }
                   4245:              }
                   4246:            }
                   4247:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4248:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4249:          if(bool==1){
                   4250:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4251:               and mw[mi+1][iind]. dh depends on stepm. */
                   4252:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4253:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4254:            if(m >=firstpass && m <=lastpass){
                   4255:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4256:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4257:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4258:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4259:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4260:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4261:              if (m<lastpass) {
                   4262:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4263:                /*   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]); */
                   4264:                if(s[m][iind]==-1)
                   4265:                  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.));
                   4266:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4267:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4268:                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 */
                   4269:              }
                   4270:            } /* end if between passes */  
                   4271:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4272:              dateintsum=dateintsum+k2;
                   4273:              k2cpt++;
                   4274:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4275:            }
                   4276:          } /* end bool 2 */
                   4277:        } /* end m */
1.226     brouard  4278:       } /* end bool */
                   4279:     } /* end iind = 1 to imx */
                   4280:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4281:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.240   ! brouard  4282:     
        !          4283:     
1.226     brouard  4284:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4285:     pstamp(ficresp);
1.240   ! brouard  4286:     if  (cptcoveff>0){
1.226     brouard  4287:       fprintf(ficresp, "\n#********** Variable "); 
                   4288:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4289:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.240   ! brouard  4290:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4291:       for (z1=1; z1<=cptcoveff; z1++){
1.240   ! brouard  4292:        if(DummyV[z1]){
        !          4293:          fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4294:          fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4295:          fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4296:          fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4297:        }else{
        !          4298:          fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4299:          fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4300:          fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4301:          fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          4302:        }
1.226     brouard  4303:       }
                   4304:       fprintf(ficresp, "**********\n#");
                   4305:       fprintf(ficresphtm, "**********</h3>\n");
                   4306:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4307:       fprintf(ficlog, "**********\n");
                   4308:     }
                   4309:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4310:     for(i=1; i<=nlstate;i++) {
1.240   ! brouard  4311:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
1.226     brouard  4312:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4313:     }
                   4314:     fprintf(ficresp, "\n");
                   4315:     fprintf(ficresphtm, "\n");
1.240   ! brouard  4316:     
1.226     brouard  4317:     /* Header of frequency table by age */
                   4318:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4319:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4320:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4321:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4322:        if(jk!=0 && m!=0)
                   4323:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4324:       }
                   4325:     }
                   4326:     fprintf(ficresphtmfr, "\n");
1.240   ! brouard  4327:     
1.226     brouard  4328:     /* For each age */
                   4329:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4330:       fprintf(ficresphtm,"<tr>");
                   4331:       if(iage==iagemax+1){
1.240   ! brouard  4332:        fprintf(ficlog,"1");
        !          4333:        fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4334:       }else if(iage==iagemax+2){
1.240   ! brouard  4335:        fprintf(ficlog,"0");
        !          4336:        fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4337:       }else if(iage==iagemax+3){
1.240   ! brouard  4338:        fprintf(ficlog,"Total");
        !          4339:        fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4340:       }else{
1.240   ! brouard  4341:        if(first==1){
        !          4342:          first=0;
        !          4343:          printf("See log file for details...\n");
        !          4344:        }
        !          4345:        fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
        !          4346:        fprintf(ficlog,"Age %d", iage);
1.226     brouard  4347:       }
                   4348:       for(jk=1; jk <=nlstate ; jk++){
1.240   ! brouard  4349:        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
        !          4350:          pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4351:       }
                   4352:       for(jk=1; jk <=nlstate ; jk++){
1.240   ! brouard  4353:        for(m=-1, pos=0; m <=0 ; m++)
        !          4354:          pos += freq[jk][m][iage];
        !          4355:        if(pp[jk]>=1.e-10){
        !          4356:          if(first==1){
        !          4357:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
        !          4358:          }
        !          4359:          fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
        !          4360:        }else{
        !          4361:          if(first==1)
        !          4362:            printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
        !          4363:          fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
        !          4364:        }
1.226     brouard  4365:       }
1.240   ! brouard  4366:       
1.226     brouard  4367:       for(jk=1; jk <=nlstate ; jk++){ 
1.240   ! brouard  4368:        /* posprop[jk]=0; */
        !          4369:        for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
        !          4370:          pp[jk] += freq[jk][m][iage];
1.226     brouard  4371:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.240   ! brouard  4372:       
1.226     brouard  4373:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.240   ! brouard  4374:        pos += pp[jk]; /* pos is the total number of transitions until this age */
        !          4375:        posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
        !          4376:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
        !          4377:        pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
        !          4378:                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4379:       }
                   4380:       for(jk=1; jk <=nlstate ; jk++){
1.240   ! brouard  4381:        if(pos>=1.e-5){
        !          4382:          if(first==1)
        !          4383:            printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
        !          4384:          fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
        !          4385:        }else{
        !          4386:          if(first==1)
        !          4387:            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
        !          4388:          fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
        !          4389:        }
        !          4390:        if( iage <= iagemax){
        !          4391:          if(pos>=1.e-5){
        !          4392:            fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
        !          4393:            fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
        !          4394:            /*probs[iage][jk][j1]= pp[jk]/pos;*/
        !          4395:            /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
        !          4396:          }
        !          4397:          else{
        !          4398:            fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
        !          4399:            fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
        !          4400:          }
        !          4401:        }
        !          4402:        pospropt[jk] +=posprop[jk];
1.226     brouard  4403:       } /* end loop jk */
                   4404:       /* pospropt=0.; */
                   4405:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.240   ! brouard  4406:        for(m=-1; m <=nlstate+ndeath; m++){
        !          4407:          if(freq[jk][m][iage] !=0 ) { /* minimizing output */
        !          4408:            if(first==1){
        !          4409:              printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
        !          4410:            }
        !          4411:            fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
        !          4412:          }
        !          4413:          if(jk!=0 && m!=0)
        !          4414:            fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
        !          4415:        }
1.226     brouard  4416:       } /* end loop jk */
                   4417:       posproptt=0.; 
                   4418:       for(jk=1; jk <=nlstate; jk++){
1.240   ! brouard  4419:        posproptt += pospropt[jk];
1.226     brouard  4420:       }
                   4421:       fprintf(ficresphtmfr,"</tr>\n ");
                   4422:       if(iage <= iagemax){
1.240   ! brouard  4423:        fprintf(ficresp,"\n");
        !          4424:        fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4425:       }
                   4426:       if(first==1)
1.240   ! brouard  4427:        printf("Others in log...\n");
1.226     brouard  4428:       fprintf(ficlog,"\n");
                   4429:     } /* end loop age iage */
                   4430:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4431:     for(jk=1; jk <=nlstate ; jk++){
                   4432:       if(posproptt < 1.e-5){
1.240   ! brouard  4433:        fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4434:       }else{
1.240   ! brouard  4435:        fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4436:       }
                   4437:     }
                   4438:     fprintf(ficresphtm,"</tr>\n");
                   4439:     fprintf(ficresphtm,"</table>\n");
                   4440:     fprintf(ficresphtmfr,"</table>\n");
                   4441:     if(posproptt < 1.e-5){
                   4442:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4443:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4444:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4445:       invalidvarcomb[j1]=1;
                   4446:     }else{
                   4447:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4448:       invalidvarcomb[j1]=0;
                   4449:     }
                   4450:     fprintf(ficresphtmfr,"</table>\n");
                   4451:   } /* end selected combination of covariate j1 */
                   4452:   dateintmean=dateintsum/k2cpt; 
1.240   ! brouard  4453:   
1.226     brouard  4454:   fclose(ficresp);
                   4455:   fclose(ficresphtm);
                   4456:   fclose(ficresphtmfr);
                   4457:   free_vector(meanq,1,nqfveff);
                   4458:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4459:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4460:   free_vector(pospropt,1,nlstate);
                   4461:   free_vector(posprop,1,nlstate);
                   4462:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4463:   free_vector(pp,1,nlstate);
                   4464:   /* End of freqsummary */
                   4465: }
1.126     brouard  4466: 
                   4467: /************ Prevalence ********************/
1.227     brouard  4468: 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)
                   4469: {  
                   4470:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4471:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4472:      We still use firstpass and lastpass as another selection.
                   4473:   */
1.126     brouard  4474:  
1.227     brouard  4475:   int i, m, jk, j1, bool, z1,j, iv;
                   4476:   int mi; /* Effective wave */
                   4477:   int iage;
                   4478:   double agebegin, ageend;
                   4479: 
                   4480:   double **prop;
                   4481:   double posprop; 
                   4482:   double  y2; /* in fractional years */
                   4483:   int iagemin, iagemax;
                   4484:   int first; /** to stop verbosity which is redirected to log file */
                   4485: 
                   4486:   iagemin= (int) agemin;
                   4487:   iagemax= (int) agemax;
                   4488:   /*pp=vector(1,nlstate);*/
                   4489:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4490:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4491:   j1=0;
1.222     brouard  4492:   
1.227     brouard  4493:   /*j=cptcoveff;*/
                   4494:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4495:   
1.227     brouard  4496:   first=1;
                   4497:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4498:     for (i=1; i<=nlstate; i++)  
                   4499:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4500:        prop[i][iage]=0.0;
                   4501:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4502:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4503:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4504:     
                   4505:     for (i=1; i<=imx; i++) { /* Each individual */
                   4506:       bool=1;
                   4507:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4508:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4509:        m=mw[mi][i];
                   4510:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4511:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4512:        for (z1=1; z1<=cptcoveff; z1++){
                   4513:          if( Fixed[Tmodelind[z1]]==1){
                   4514:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4515:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4516:              bool=0;
                   4517:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4518:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4519:              bool=0;
                   4520:            }
                   4521:        }
                   4522:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4523:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4524:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4525:          if(m >=firstpass && m <=lastpass){
                   4526:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4527:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4528:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4529:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4530:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4531:                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); 
                   4532:                exit(1);
                   4533:              }
                   4534:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4535:                /*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]]);*/
                   4536:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4537:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4538:              } /* end valid statuses */ 
                   4539:            } /* end selection of dates */
                   4540:          } /* end selection of waves */
                   4541:        } /* end bool */
                   4542:       } /* end wave */
                   4543:     } /* end individual */
                   4544:     for(i=iagemin; i <= iagemax+3; i++){  
                   4545:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4546:        posprop += prop[jk][i]; 
                   4547:       } 
                   4548:       
                   4549:       for(jk=1; jk <=nlstate ; jk++){      
                   4550:        if( i <=  iagemax){ 
                   4551:          if(posprop>=1.e-5){ 
                   4552:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4553:          } else{
                   4554:            if(first==1){
                   4555:              first=0;
                   4556:              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]);
                   4557:            }
                   4558:          }
                   4559:        } 
                   4560:       }/* end jk */ 
                   4561:     }/* end i */ 
1.222     brouard  4562:      /*} *//* end i1 */
1.227     brouard  4563:   } /* end j1 */
1.222     brouard  4564:   
1.227     brouard  4565:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4566:   /*free_vector(pp,1,nlstate);*/
                   4567:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4568: }  /* End of prevalence */
1.126     brouard  4569: 
                   4570: /************* Waves Concatenation ***************/
                   4571: 
                   4572: 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)
                   4573: {
                   4574:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4575:      Death is a valid wave (if date is known).
                   4576:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4577:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4578:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4579:   */
1.126     brouard  4580: 
1.224     brouard  4581:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4582:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4583:      double sum=0., jmean=0.;*/
1.224     brouard  4584:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4585:   int j, k=0,jk, ju, jl;
                   4586:   double sum=0.;
                   4587:   first=0;
1.214     brouard  4588:   firstwo=0;
1.217     brouard  4589:   firsthree=0;
1.218     brouard  4590:   firstfour=0;
1.164     brouard  4591:   jmin=100000;
1.126     brouard  4592:   jmax=-1;
                   4593:   jmean=0.;
1.224     brouard  4594: 
                   4595: /* Treating live states */
1.214     brouard  4596:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4597:     mi=0;  /* First valid wave */
1.227     brouard  4598:     mli=0; /* Last valid wave */
1.126     brouard  4599:     m=firstpass;
1.214     brouard  4600:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4601:       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 */
                   4602:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4603:       }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 */
                   4604:        mw[++mi][i]=m;
                   4605:        mli=m;
1.224     brouard  4606:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4607:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4608:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4609:       }
1.227     brouard  4610:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4611: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4612:        break;
1.224     brouard  4613: #else
1.227     brouard  4614:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4615:          if(firsthree == 0){
                   4616:            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);
                   4617:            firsthree=1;
                   4618:          }
                   4619:          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);
                   4620:          mw[++mi][i]=m;
                   4621:          mli=m;
                   4622:        }
                   4623:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4624:          nbwarn++;
                   4625:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4626:            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);
                   4627:            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);
                   4628:          }
                   4629:          break;
                   4630:        }
                   4631:        break;
1.224     brouard  4632: #endif
1.227     brouard  4633:       }/* End m >= lastpass */
1.126     brouard  4634:     }/* end while */
1.224     brouard  4635: 
1.227     brouard  4636:     /* 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  4637:     /* After last pass */
1.224     brouard  4638: /* Treating death states */
1.214     brouard  4639:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4640:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4641:       /* } */
1.126     brouard  4642:       mi++;    /* Death is another wave */
                   4643:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4644:       /* Only death is a correct wave */
1.126     brouard  4645:       mw[mi][i]=m;
1.224     brouard  4646:     }
                   4647: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4648:     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  4649:       /* m++; */
                   4650:       /* mi++; */
                   4651:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4652:       /* mw[mi][i]=m; */
1.218     brouard  4653:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4654:        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 */
                   4655:          nbwarn++;
                   4656:          if(firstfiv==0){
                   4657:            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 );
                   4658:            firstfiv=1;
                   4659:          }else{
                   4660:            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 );
                   4661:          }
                   4662:        }else{ /* Death occured afer last wave potential bias */
                   4663:          nberr++;
                   4664:          if(firstwo==0){
                   4665:            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 );
                   4666:            firstwo=1;
                   4667:          }
                   4668:          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 );
                   4669:        }
1.218     brouard  4670:       }else{ /* end date of interview is known */
1.227     brouard  4671:        /* death is known but not confirmed by death status at any wave */
                   4672:        if(firstfour==0){
                   4673:          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 );
                   4674:          firstfour=1;
                   4675:        }
                   4676:        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  4677:       }
1.224     brouard  4678:     } /* end if date of death is known */
                   4679: #endif
                   4680:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4681:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4682:     if(mi==0){
                   4683:       nbwarn++;
                   4684:       if(first==0){
1.227     brouard  4685:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4686:        first=1;
1.126     brouard  4687:       }
                   4688:       if(first==1){
1.227     brouard  4689:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4690:       }
                   4691:     } /* end mi==0 */
                   4692:   } /* End individuals */
1.214     brouard  4693:   /* wav and mw are no more changed */
1.223     brouard  4694:        
1.214     brouard  4695:   
1.126     brouard  4696:   for(i=1; i<=imx; i++){
                   4697:     for(mi=1; mi<wav[i];mi++){
                   4698:       if (stepm <=0)
1.227     brouard  4699:        dh[mi][i]=1;
1.126     brouard  4700:       else{
1.227     brouard  4701:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4702:          if (agedc[i] < 2*AGESUP) {
                   4703:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4704:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4705:            else if(j<0){
                   4706:              nberr++;
                   4707:              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]);
                   4708:              j=1; /* Temporary Dangerous patch */
                   4709:              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);
                   4710:              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]);
                   4711:              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);
                   4712:            }
                   4713:            k=k+1;
                   4714:            if (j >= jmax){
                   4715:              jmax=j;
                   4716:              ijmax=i;
                   4717:            }
                   4718:            if (j <= jmin){
                   4719:              jmin=j;
                   4720:              ijmin=i;
                   4721:            }
                   4722:            sum=sum+j;
                   4723:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4724:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4725:          }
                   4726:        }
                   4727:        else{
                   4728:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4729: /*       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  4730:                                        
1.227     brouard  4731:          k=k+1;
                   4732:          if (j >= jmax) {
                   4733:            jmax=j;
                   4734:            ijmax=i;
                   4735:          }
                   4736:          else if (j <= jmin){
                   4737:            jmin=j;
                   4738:            ijmin=i;
                   4739:          }
                   4740:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4741:          /*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]);*/
                   4742:          if(j<0){
                   4743:            nberr++;
                   4744:            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]);
                   4745:            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]);
                   4746:          }
                   4747:          sum=sum+j;
                   4748:        }
                   4749:        jk= j/stepm;
                   4750:        jl= j -jk*stepm;
                   4751:        ju= j -(jk+1)*stepm;
                   4752:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4753:          if(jl==0){
                   4754:            dh[mi][i]=jk;
                   4755:            bh[mi][i]=0;
                   4756:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4757:                  * to avoid the price of an extra matrix product in likelihood */
                   4758:            dh[mi][i]=jk+1;
                   4759:            bh[mi][i]=ju;
                   4760:          }
                   4761:        }else{
                   4762:          if(jl <= -ju){
                   4763:            dh[mi][i]=jk;
                   4764:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4765:                                 * is higher than the multiple of stepm and negative otherwise.
                   4766:                                 */
                   4767:          }
                   4768:          else{
                   4769:            dh[mi][i]=jk+1;
                   4770:            bh[mi][i]=ju;
                   4771:          }
                   4772:          if(dh[mi][i]==0){
                   4773:            dh[mi][i]=1; /* At least one step */
                   4774:            bh[mi][i]=ju; /* At least one step */
                   4775:            /*  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);*/
                   4776:          }
                   4777:        } /* end if mle */
1.126     brouard  4778:       }
                   4779:     } /* end wave */
                   4780:   }
                   4781:   jmean=sum/k;
                   4782:   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  4783:   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  4784: }
1.126     brouard  4785: 
                   4786: /*********** Tricode ****************************/
1.220     brouard  4787:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4788: {
1.144     brouard  4789:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4790:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
1.169     brouard  4791:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.224     brouard  4792:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4793:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
1.144     brouard  4794:   */
1.130     brouard  4795: 
1.145     brouard  4796:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4797:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4798:   int cptcode=0; /* Modality max of covariates j */
                   4799:   int modmincovj=0; /* Modality min of covariates j */
                   4800: 
                   4801: 
1.220     brouard  4802:   /* cptcoveff=0;  */
1.224     brouard  4803:        /* *cptcov=0; */
1.126     brouard  4804:  
1.144     brouard  4805:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4806: 
1.224     brouard  4807:   /* Loop on covariates without age and products and no quantitative variable */
                   4808:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
1.227     brouard  4809:   for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4810:     for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4811:     if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4812:       switch(Fixed[k]) {
                   4813:       case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.231     brouard  4814:                                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*/
                   4815:                                        ij=(int)(covar[Tvar[k]][i]);
                   4816:                                        /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4817:                                         * If product of Vn*Vm, still boolean *:
                   4818:                                         * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4819:                                         * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4820:                                        /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4821:                                                 modality of the nth covariate of individual i. */
                   4822:                                        if (ij > modmaxcovj)
                   4823:                                                modmaxcovj=ij; 
                   4824:                                        else if (ij < modmincovj) 
                   4825:                                                modmincovj=ij; 
                   4826:                                        if ((ij < -1) && (ij > NCOVMAX)){
                   4827:                                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4828:                                                exit(1);
                   4829:                                        }else
                   4830:                                                Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4831:                                        /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4832:                                        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4833:                                        /* getting the maximum value of the modality of the covariate
                   4834:                                                 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4835:                                                 female ies 1, then modmaxcovj=1.
                   4836:                                        */
                   4837:                                } /* end for loop on individuals i */
                   4838:                                printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4839:                                fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4840:                                cptcode=modmaxcovj;
                   4841:                                /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4842:                                /*for (i=0; i<=cptcode; i++) {*/
                   4843:                                for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4844:                                        printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4845:                                        fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4846:                                        if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4847:                                                if( j != -1){
                   4848:                                                        ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4849:                                                                                                                                 covariate for which somebody answered excluding 
                   4850:                                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4851:                                                }
                   4852:                                                ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4853:                                                                                                                                                covariate for which somebody answered including 
                   4854:                                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
                   4855:                                        }       /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4856:                                                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4857:                                } /* Ndum[-1] number of undefined modalities */
                   4858:                        
                   4859:                                /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4860:                                /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4861:                                /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4862:                                /* modmincovj=3; modmaxcovj = 7; */
                   4863:                                /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4864:                                /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4865:                          /*             defining two dummy variables: variables V1_1 and V1_2.*/
                   4866:              /* nbcode[Tvar[j]][ij]=k; */
                   4867:              /* nbcode[Tvar[j]][1]=0; */
                   4868:              /* nbcode[Tvar[j]][2]=1; */
                   4869:              /* nbcode[Tvar[j]][3]=2; */
                   4870:              /* To be continued (not working yet). */
                   4871:              ij=0; /* ij is similar to i but can jump over null modalities */
                   4872:                                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*/
                   4873:          if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4874:                  break;
                   4875:                }
                   4876:                                        ij++;
                   4877:                                        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*/
                   4878:                                        cptcode = ij; /* New max modality for covar j */
                   4879:                                } /* end of loop on modality i=-1 to 1 or more */
                   4880:                                break;
1.227     brouard  4881:       case 1: /* Testing on varying covariate, could be simple and
                   4882:               * should look at waves or product of fixed *
                   4883:               * varying. No time to test -1, assuming 0 and 1 only */
1.231     brouard  4884:                                ij=0;
                   4885:                                for(i=0; i<=1;i++){
                   4886:                                        nbcode[Tvar[k]][++ij]=i;
                   4887:                                }
                   4888:                                break;
1.227     brouard  4889:       default:
1.231     brouard  4890:                                break;
1.227     brouard  4891:       } /* end switch */
                   4892:     } /* end dummy test */
1.225     brouard  4893:     
1.192     brouard  4894:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4895:     /*         /\*recode from 0 *\/ */
                   4896:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4897:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4898:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4899:     /*         } */
                   4900:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4901:     /*         if (ij > ncodemax[j]) { */
                   4902:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4903:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4904:     /*           break; */
                   4905:     /*         } */
                   4906:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4907:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4908:   
1.225     brouard  4909:   for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.227     brouard  4910:   /* Look at fixed dummy (single or product) covariates to check empty modalities */
1.187     brouard  4911:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.225     brouard  4912:     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
1.227     brouard  4913:     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 */ 
                   4914:     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 */
                   4915:     /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
1.225     brouard  4916:   } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4917:   
                   4918:   ij=0;
1.227     brouard  4919:   /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4920:   for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.225     brouard  4921:     /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.227     brouard  4922:     /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4923:     if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4924:       /* If product not in single variable we don't print results */
1.225     brouard  4925:       /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.230     brouard  4926:       ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   4927:       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*/
                   4928:       Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
1.231     brouard  4929:       TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
1.227     brouard  4930:       if(Fixed[k]!=0)
                   4931:         anyvaryingduminmodel=1;
1.231     brouard  4932:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   4933:                        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4934:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   4935:                        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   4936:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   4937:                        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
1.227     brouard  4938:     } 
1.225     brouard  4939:   } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   4940:   /* ij--; */
                   4941:   /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4942:   *cptcov=ij; /*Number of total real effective covariates: effective
1.231     brouard  4943:                                                         * because they can be excluded from the model and real
                   4944:                                                         * if in the model but excluded because missing values, but how to get k from ij?*/
1.227     brouard  4945:   for(j=ij+1; j<= cptcovt; j++){
                   4946:     Tvaraff[j]=0;
                   4947:     Tmodelind[j]=0;
                   4948:   }
1.228     brouard  4949:   for(j=ntveff+1; j<= cptcovt; j++){
                   4950:     TmodelInvind[j]=0;
                   4951:   }
1.227     brouard  4952:   /* To be sorted */
                   4953:   ;
1.126     brouard  4954: }
                   4955: 
1.145     brouard  4956: 
1.126     brouard  4957: /*********** Health Expectancies ****************/
                   4958: 
1.235     brouard  4959:  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  4960: 
                   4961: {
                   4962:   /* Health expectancies, no variances */
1.164     brouard  4963:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4964:   int nhstepma, nstepma; /* Decreasing with age */
                   4965:   double age, agelim, hf;
                   4966:   double ***p3mat;
                   4967:   double eip;
                   4968: 
1.238     brouard  4969:   /* pstamp(ficreseij); */
1.126     brouard  4970:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4971:   fprintf(ficreseij,"# Age");
                   4972:   for(i=1; i<=nlstate;i++){
                   4973:     for(j=1; j<=nlstate;j++){
                   4974:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4975:     }
                   4976:     fprintf(ficreseij," e%1d. ",i);
                   4977:   }
                   4978:   fprintf(ficreseij,"\n");
                   4979: 
                   4980:   
                   4981:   if(estepm < stepm){
                   4982:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4983:   }
                   4984:   else  hstepm=estepm;   
                   4985:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4986:    * This is mainly to measure the difference between two models: for example
                   4987:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4988:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4989:    * progression in between and thus overestimating or underestimating according
                   4990:    * to the curvature of the survival function. If, for the same date, we 
                   4991:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4992:    * to compare the new estimate of Life expectancy with the same linear 
                   4993:    * hypothesis. A more precise result, taking into account a more precise
                   4994:    * curvature will be obtained if estepm is as small as stepm. */
                   4995: 
                   4996:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4997:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4998:      nhstepm is the number of hstepm from age to agelim 
                   4999:      nstepm is the number of stepm from age to agelin. 
                   5000:      Look at hpijx to understand the reason of that which relies in memory size
                   5001:      and note for a fixed period like estepm months */
                   5002:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5003:      survival function given by stepm (the optimization length). Unfortunately it
                   5004:      means that if the survival funtion is printed only each two years of age and if
                   5005:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5006:      results. So we changed our mind and took the option of the best precision.
                   5007:   */
                   5008:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5009: 
                   5010:   agelim=AGESUP;
                   5011:   /* If stepm=6 months */
                   5012:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5013:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5014:     
                   5015: /* nhstepm age range expressed in number of stepm */
                   5016:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5017:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5018:   /* if (stepm >= YEARM) hstepm=1;*/
                   5019:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5020:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5021: 
                   5022:   for (age=bage; age<=fage; age ++){ 
                   5023:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5024:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5025:     /* if (stepm >= YEARM) hstepm=1;*/
                   5026:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5027: 
                   5028:     /* If stepm=6 months */
                   5029:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5030:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5031:     
1.235     brouard  5032:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5033:     
                   5034:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5035:     
                   5036:     printf("%d|",(int)age);fflush(stdout);
                   5037:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5038:     
                   5039:     /* Computing expectancies */
                   5040:     for(i=1; i<=nlstate;i++)
                   5041:       for(j=1; j<=nlstate;j++)
                   5042:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5043:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5044:          
                   5045:          /* 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]);*/
                   5046: 
                   5047:        }
                   5048: 
                   5049:     fprintf(ficreseij,"%3.0f",age );
                   5050:     for(i=1; i<=nlstate;i++){
                   5051:       eip=0;
                   5052:       for(j=1; j<=nlstate;j++){
                   5053:        eip +=eij[i][j][(int)age];
                   5054:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5055:       }
                   5056:       fprintf(ficreseij,"%9.4f", eip );
                   5057:     }
                   5058:     fprintf(ficreseij,"\n");
                   5059:     
                   5060:   }
                   5061:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5062:   printf("\n");
                   5063:   fprintf(ficlog,"\n");
                   5064:   
                   5065: }
                   5066: 
1.235     brouard  5067:  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  5068: 
                   5069: {
                   5070:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5071:      to initial status i, ei. .
1.126     brouard  5072:   */
                   5073:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5074:   int nhstepma, nstepma; /* Decreasing with age */
                   5075:   double age, agelim, hf;
                   5076:   double ***p3matp, ***p3matm, ***varhe;
                   5077:   double **dnewm,**doldm;
                   5078:   double *xp, *xm;
                   5079:   double **gp, **gm;
                   5080:   double ***gradg, ***trgradg;
                   5081:   int theta;
                   5082: 
                   5083:   double eip, vip;
                   5084: 
                   5085:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5086:   xp=vector(1,npar);
                   5087:   xm=vector(1,npar);
                   5088:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5089:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5090:   
                   5091:   pstamp(ficresstdeij);
                   5092:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5093:   fprintf(ficresstdeij,"# Age");
                   5094:   for(i=1; i<=nlstate;i++){
                   5095:     for(j=1; j<=nlstate;j++)
                   5096:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5097:     fprintf(ficresstdeij," e%1d. ",i);
                   5098:   }
                   5099:   fprintf(ficresstdeij,"\n");
                   5100: 
                   5101:   pstamp(ficrescveij);
                   5102:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5103:   fprintf(ficrescveij,"# Age");
                   5104:   for(i=1; i<=nlstate;i++)
                   5105:     for(j=1; j<=nlstate;j++){
                   5106:       cptj= (j-1)*nlstate+i;
                   5107:       for(i2=1; i2<=nlstate;i2++)
                   5108:        for(j2=1; j2<=nlstate;j2++){
                   5109:          cptj2= (j2-1)*nlstate+i2;
                   5110:          if(cptj2 <= cptj)
                   5111:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5112:        }
                   5113:     }
                   5114:   fprintf(ficrescveij,"\n");
                   5115:   
                   5116:   if(estepm < stepm){
                   5117:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5118:   }
                   5119:   else  hstepm=estepm;   
                   5120:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5121:    * This is mainly to measure the difference between two models: for example
                   5122:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5123:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5124:    * progression in between and thus overestimating or underestimating according
                   5125:    * to the curvature of the survival function. If, for the same date, we 
                   5126:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5127:    * to compare the new estimate of Life expectancy with the same linear 
                   5128:    * hypothesis. A more precise result, taking into account a more precise
                   5129:    * curvature will be obtained if estepm is as small as stepm. */
                   5130: 
                   5131:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5132:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5133:      nhstepm is the number of hstepm from age to agelim 
                   5134:      nstepm is the number of stepm from age to agelin. 
                   5135:      Look at hpijx to understand the reason of that which relies in memory size
                   5136:      and note for a fixed period like estepm months */
                   5137:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5138:      survival function given by stepm (the optimization length). Unfortunately it
                   5139:      means that if the survival funtion is printed only each two years of age and if
                   5140:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5141:      results. So we changed our mind and took the option of the best precision.
                   5142:   */
                   5143:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5144: 
                   5145:   /* If stepm=6 months */
                   5146:   /* nhstepm age range expressed in number of stepm */
                   5147:   agelim=AGESUP;
                   5148:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5149:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5150:   /* if (stepm >= YEARM) hstepm=1;*/
                   5151:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5152:   
                   5153:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5154:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5155:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5156:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5157:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5158:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5159: 
                   5160:   for (age=bage; age<=fage; age ++){ 
                   5161:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5162:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5163:     /* if (stepm >= YEARM) hstepm=1;*/
                   5164:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5165:                
1.126     brouard  5166:     /* If stepm=6 months */
                   5167:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5168:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5169:     
                   5170:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5171:                
1.126     brouard  5172:     /* Computing  Variances of health expectancies */
                   5173:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5174:        decrease memory allocation */
                   5175:     for(theta=1; theta <=npar; theta++){
                   5176:       for(i=1; i<=npar; i++){ 
1.222     brouard  5177:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5178:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5179:       }
1.235     brouard  5180:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5181:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5182:                        
1.126     brouard  5183:       for(j=1; j<= nlstate; j++){
1.222     brouard  5184:        for(i=1; i<=nlstate; i++){
                   5185:          for(h=0; h<=nhstepm-1; h++){
                   5186:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5187:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5188:          }
                   5189:        }
1.126     brouard  5190:       }
1.218     brouard  5191:                        
1.126     brouard  5192:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5193:        for(h=0; h<=nhstepm-1; h++){
                   5194:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5195:        }
1.126     brouard  5196:     }/* End theta */
                   5197:     
                   5198:     
                   5199:     for(h=0; h<=nhstepm-1; h++)
                   5200:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5201:        for(theta=1; theta <=npar; theta++)
                   5202:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5203:     
1.218     brouard  5204:                
1.222     brouard  5205:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5206:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5207:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5208:                
1.222     brouard  5209:     printf("%d|",(int)age);fflush(stdout);
                   5210:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5211:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5212:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5213:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5214:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5215:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5216:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5217:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5218:       }
                   5219:     }
1.218     brouard  5220:                
1.126     brouard  5221:     /* Computing expectancies */
1.235     brouard  5222:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5223:     for(i=1; i<=nlstate;i++)
                   5224:       for(j=1; j<=nlstate;j++)
1.222     brouard  5225:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5226:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5227:                                        
1.222     brouard  5228:          /* 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  5229:                                        
1.222     brouard  5230:        }
1.218     brouard  5231:                
1.126     brouard  5232:     fprintf(ficresstdeij,"%3.0f",age );
                   5233:     for(i=1; i<=nlstate;i++){
                   5234:       eip=0.;
                   5235:       vip=0.;
                   5236:       for(j=1; j<=nlstate;j++){
1.222     brouard  5237:        eip += eij[i][j][(int)age];
                   5238:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5239:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5240:        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  5241:       }
                   5242:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5243:     }
                   5244:     fprintf(ficresstdeij,"\n");
1.218     brouard  5245:                
1.126     brouard  5246:     fprintf(ficrescveij,"%3.0f",age );
                   5247:     for(i=1; i<=nlstate;i++)
                   5248:       for(j=1; j<=nlstate;j++){
1.222     brouard  5249:        cptj= (j-1)*nlstate+i;
                   5250:        for(i2=1; i2<=nlstate;i2++)
                   5251:          for(j2=1; j2<=nlstate;j2++){
                   5252:            cptj2= (j2-1)*nlstate+i2;
                   5253:            if(cptj2 <= cptj)
                   5254:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5255:          }
1.126     brouard  5256:       }
                   5257:     fprintf(ficrescveij,"\n");
1.218     brouard  5258:                
1.126     brouard  5259:   }
                   5260:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5261:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5262:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5263:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5264:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5265:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5266:   printf("\n");
                   5267:   fprintf(ficlog,"\n");
1.218     brouard  5268:        
1.126     brouard  5269:   free_vector(xm,1,npar);
                   5270:   free_vector(xp,1,npar);
                   5271:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5272:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5273:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5274: }
1.218     brouard  5275:  
1.126     brouard  5276: /************ Variance ******************/
1.235     brouard  5277:  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  5278:  {
                   5279:    /* Variance of health expectancies */
                   5280:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5281:    /* double **newm;*/
                   5282:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5283:   
                   5284:    /* int movingaverage(); */
                   5285:    double **dnewm,**doldm;
                   5286:    double **dnewmp,**doldmp;
                   5287:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5288:    int k;
                   5289:    double *xp;
                   5290:    double **gp, **gm;  /* for var eij */
                   5291:    double ***gradg, ***trgradg; /*for var eij */
                   5292:    double **gradgp, **trgradgp; /* for var p point j */
                   5293:    double *gpp, *gmp; /* for var p point j */
                   5294:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5295:    double ***p3mat;
                   5296:    double age,agelim, hf;
                   5297:    /* double ***mobaverage; */
                   5298:    int theta;
                   5299:    char digit[4];
                   5300:    char digitp[25];
                   5301: 
                   5302:    char fileresprobmorprev[FILENAMELENGTH];
                   5303: 
                   5304:    if(popbased==1){
                   5305:      if(mobilav!=0)
                   5306:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5307:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5308:    }
                   5309:    else 
                   5310:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5311: 
1.218     brouard  5312:    /* if (mobilav!=0) { */
                   5313:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5314:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5315:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5316:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5317:    /*   } */
                   5318:    /* } */
                   5319: 
                   5320:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5321:    sprintf(digit,"%-d",ij);
                   5322:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5323:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5324:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5325:    strcat(fileresprobmorprev,fileresu);
                   5326:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5327:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5328:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5329:    }
                   5330:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5331:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5332:    pstamp(ficresprobmorprev);
                   5333:    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  5334:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5335:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5336:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5337:    }
                   5338:    for(j=1;j<=cptcoveff;j++) 
                   5339:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5340:    fprintf(ficresprobmorprev,"\n");
                   5341: 
1.218     brouard  5342:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5343:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5344:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5345:      for(i=1; i<=nlstate;i++)
                   5346:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5347:    }  
                   5348:    fprintf(ficresprobmorprev,"\n");
                   5349:   
                   5350:    fprintf(ficgp,"\n# Routine varevsij");
                   5351:    fprintf(ficgp,"\nunset title \n");
                   5352:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5353:    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");
                   5354:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5355:    /*   } */
                   5356:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5357:    pstamp(ficresvij);
                   5358:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5359:    if(popbased==1)
                   5360:      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);
                   5361:    else
                   5362:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5363:    fprintf(ficresvij,"# Age");
                   5364:    for(i=1; i<=nlstate;i++)
                   5365:      for(j=1; j<=nlstate;j++)
                   5366:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5367:    fprintf(ficresvij,"\n");
                   5368: 
                   5369:    xp=vector(1,npar);
                   5370:    dnewm=matrix(1,nlstate,1,npar);
                   5371:    doldm=matrix(1,nlstate,1,nlstate);
                   5372:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5373:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5374: 
                   5375:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5376:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5377:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5378:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5379:   
1.218     brouard  5380:    if(estepm < stepm){
                   5381:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5382:    }
                   5383:    else  hstepm=estepm;   
                   5384:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5385:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5386:       nhstepm is the number of hstepm from age to agelim 
                   5387:       nstepm is the number of stepm from age to agelim. 
                   5388:       Look at function hpijx to understand why because of memory size limitations, 
                   5389:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5390:       survival function given by stepm (the optimization length). Unfortunately it
                   5391:       means that if the survival funtion is printed every two years of age and if
                   5392:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5393:       results. So we changed our mind and took the option of the best precision.
                   5394:    */
                   5395:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5396:    agelim = AGESUP;
                   5397:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5398:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5399:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5400:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5401:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5402:      gp=matrix(0,nhstepm,1,nlstate);
                   5403:      gm=matrix(0,nhstepm,1,nlstate);
                   5404:                
                   5405:                
                   5406:      for(theta=1; theta <=npar; theta++){
                   5407:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5408:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5409:        }
                   5410:                        
1.235     brouard  5411:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
1.218     brouard  5412:                        
                   5413:        if (popbased==1) {
                   5414:         if(mobilav ==0){
                   5415:           for(i=1; i<=nlstate;i++)
                   5416:             prlim[i][i]=probs[(int)age][i][ij];
                   5417:         }else{ /* mobilav */ 
                   5418:           for(i=1; i<=nlstate;i++)
                   5419:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5420:         }
                   5421:        }
                   5422:                        
1.235     brouard  5423:        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  5424:        for(j=1; j<= nlstate; j++){
                   5425:         for(h=0; h<=nhstepm; h++){
                   5426:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5427:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5428:         }
                   5429:        }
                   5430:        /* Next for computing probability of death (h=1 means
                   5431:          computed over hstepm matrices product = hstepm*stepm months) 
                   5432:          as a weighted average of prlim.
                   5433:        */
                   5434:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5435:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5436:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5437:        }    
                   5438:        /* end probability of death */
                   5439:                        
                   5440:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5441:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5442:                        
1.235     brouard  5443:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nresult);
1.218     brouard  5444:                        
                   5445:        if (popbased==1) {
                   5446:         if(mobilav ==0){
                   5447:           for(i=1; i<=nlstate;i++)
                   5448:             prlim[i][i]=probs[(int)age][i][ij];
                   5449:         }else{ /* mobilav */ 
                   5450:           for(i=1; i<=nlstate;i++)
                   5451:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5452:         }
                   5453:        }
                   5454:                        
1.235     brouard  5455:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5456:                        
                   5457:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5458:         for(h=0; h<=nhstepm; h++){
                   5459:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5460:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5461:         }
                   5462:        }
                   5463:        /* This for computing probability of death (h=1 means
                   5464:          computed over hstepm matrices product = hstepm*stepm months) 
                   5465:          as a weighted average of prlim.
                   5466:        */
                   5467:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5468:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5469:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5470:        }    
                   5471:        /* end probability of death */
                   5472:                        
                   5473:        for(j=1; j<= nlstate; j++) /* vareij */
                   5474:         for(h=0; h<=nhstepm; h++){
                   5475:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5476:         }
                   5477:                        
                   5478:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5479:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5480:        }
                   5481:                        
                   5482:      } /* End theta */
                   5483:                
                   5484:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5485:                
                   5486:      for(h=0; h<=nhstepm; h++) /* veij */
                   5487:        for(j=1; j<=nlstate;j++)
                   5488:         for(theta=1; theta <=npar; theta++)
                   5489:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5490:                
                   5491:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5492:        for(theta=1; theta <=npar; theta++)
                   5493:         trgradgp[j][theta]=gradgp[theta][j];
                   5494:                
                   5495:                
                   5496:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5497:      for(i=1;i<=nlstate;i++)
                   5498:        for(j=1;j<=nlstate;j++)
                   5499:         vareij[i][j][(int)age] =0.;
                   5500:                
                   5501:      for(h=0;h<=nhstepm;h++){
                   5502:        for(k=0;k<=nhstepm;k++){
                   5503:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5504:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5505:         for(i=1;i<=nlstate;i++)
                   5506:           for(j=1;j<=nlstate;j++)
                   5507:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5508:        }
                   5509:      }
                   5510:                
                   5511:      /* pptj */
                   5512:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5513:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5514:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5515:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5516:         varppt[j][i]=doldmp[j][i];
                   5517:      /* end ppptj */
                   5518:      /*  x centered again */
                   5519:                
1.235     brouard  5520:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
1.218     brouard  5521:                
                   5522:      if (popbased==1) {
                   5523:        if(mobilav ==0){
                   5524:         for(i=1; i<=nlstate;i++)
                   5525:           prlim[i][i]=probs[(int)age][i][ij];
                   5526:        }else{ /* mobilav */ 
                   5527:         for(i=1; i<=nlstate;i++)
                   5528:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5529:        }
                   5530:      }
                   5531:                
                   5532:      /* This for computing probability of death (h=1 means
                   5533:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5534:        as a weighted average of prlim.
                   5535:      */
1.235     brouard  5536:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5537:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5538:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5539:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5540:      }    
                   5541:      /* end probability of death */
                   5542:                
                   5543:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5544:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5545:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5546:        for(i=1; i<=nlstate;i++){
                   5547:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5548:        }
                   5549:      } 
                   5550:      fprintf(ficresprobmorprev,"\n");
                   5551:                
                   5552:      fprintf(ficresvij,"%.0f ",age );
                   5553:      for(i=1; i<=nlstate;i++)
                   5554:        for(j=1; j<=nlstate;j++){
                   5555:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5556:        }
                   5557:      fprintf(ficresvij,"\n");
                   5558:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5559:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5560:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5561:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5562:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5563:    } /* End age */
                   5564:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5565:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5566:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5567:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5568:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5569:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5570:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5571:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5572:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5573:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5574:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5575:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5576:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5577:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5578:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5579:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5580:    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);
                   5581:    /*  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  5582:     */
1.218     brouard  5583:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5584:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5585: 
1.218     brouard  5586:    free_vector(xp,1,npar);
                   5587:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5588:    free_matrix(dnewm,1,nlstate,1,npar);
                   5589:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5590:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5591:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5592:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5593:    fclose(ficresprobmorprev);
                   5594:    fflush(ficgp);
                   5595:    fflush(fichtm); 
                   5596:  }  /* end varevsij */
1.126     brouard  5597: 
                   5598: /************ Variance of prevlim ******************/
1.235     brouard  5599:  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  5600: {
1.205     brouard  5601:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5602:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5603: 
1.126     brouard  5604:   double **dnewm,**doldm;
                   5605:   int i, j, nhstepm, hstepm;
                   5606:   double *xp;
                   5607:   double *gp, *gm;
                   5608:   double **gradg, **trgradg;
1.208     brouard  5609:   double **mgm, **mgp;
1.126     brouard  5610:   double age,agelim;
                   5611:   int theta;
                   5612:   
                   5613:   pstamp(ficresvpl);
                   5614:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5615:   fprintf(ficresvpl,"# Age");
                   5616:   for(i=1; i<=nlstate;i++)
                   5617:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5618:   fprintf(ficresvpl,"\n");
                   5619: 
                   5620:   xp=vector(1,npar);
                   5621:   dnewm=matrix(1,nlstate,1,npar);
                   5622:   doldm=matrix(1,nlstate,1,nlstate);
                   5623:   
                   5624:   hstepm=1*YEARM; /* Every year of age */
                   5625:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5626:   agelim = AGESUP;
                   5627:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5628:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5629:     if (stepm >= YEARM) hstepm=1;
                   5630:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5631:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5632:     mgp=matrix(1,npar,1,nlstate);
                   5633:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5634:     gp=vector(1,nlstate);
                   5635:     gm=vector(1,nlstate);
                   5636: 
                   5637:     for(theta=1; theta <=npar; theta++){
                   5638:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5639:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5640:       }
1.209     brouard  5641:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5642:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5643:       else
1.235     brouard  5644:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5645:       for(i=1;i<=nlstate;i++){
1.126     brouard  5646:        gp[i] = prlim[i][i];
1.208     brouard  5647:        mgp[theta][i] = prlim[i][i];
                   5648:       }
1.126     brouard  5649:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5650:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5651:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5652:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5653:       else
1.235     brouard  5654:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5655:       for(i=1;i<=nlstate;i++){
1.126     brouard  5656:        gm[i] = prlim[i][i];
1.208     brouard  5657:        mgm[theta][i] = prlim[i][i];
                   5658:       }
1.126     brouard  5659:       for(i=1;i<=nlstate;i++)
                   5660:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5661:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5662:     } /* End theta */
                   5663: 
                   5664:     trgradg =matrix(1,nlstate,1,npar);
                   5665: 
                   5666:     for(j=1; j<=nlstate;j++)
                   5667:       for(theta=1; theta <=npar; theta++)
                   5668:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5669:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5670:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5671:     /*   for(j=1; j<=nlstate;j++){ */
                   5672:     /*         printf(" %d ",j); */
                   5673:     /*         for(theta=1; theta <=npar; theta++) */
                   5674:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5675:     /*         printf("\n "); */
                   5676:     /*   } */
                   5677:     /* } */
                   5678:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5679:     /*   printf("\n gradg %d ",(int)age); */
                   5680:     /*   for(j=1; j<=nlstate;j++){ */
                   5681:     /*         printf("%d ",j); */
                   5682:     /*         for(theta=1; theta <=npar; theta++) */
                   5683:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5684:     /*         printf("\n "); */
                   5685:     /*   } */
                   5686:     /* } */
1.126     brouard  5687: 
                   5688:     for(i=1;i<=nlstate;i++)
                   5689:       varpl[i][(int)age] =0.;
1.209     brouard  5690:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5691:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5692:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5693:     }else{
1.126     brouard  5694:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5695:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5696:     }
1.126     brouard  5697:     for(i=1;i<=nlstate;i++)
                   5698:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5699: 
                   5700:     fprintf(ficresvpl,"%.0f ",age );
                   5701:     for(i=1; i<=nlstate;i++)
                   5702:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5703:     fprintf(ficresvpl,"\n");
                   5704:     free_vector(gp,1,nlstate);
                   5705:     free_vector(gm,1,nlstate);
1.208     brouard  5706:     free_matrix(mgm,1,npar,1,nlstate);
                   5707:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5708:     free_matrix(gradg,1,npar,1,nlstate);
                   5709:     free_matrix(trgradg,1,nlstate,1,npar);
                   5710:   } /* End age */
                   5711: 
                   5712:   free_vector(xp,1,npar);
                   5713:   free_matrix(doldm,1,nlstate,1,npar);
                   5714:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5715: 
                   5716: }
                   5717: 
                   5718: /************ Variance of one-step probabilities  ******************/
                   5719: 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  5720:  {
                   5721:    int i, j=0,  k1, l1, tj;
                   5722:    int k2, l2, j1,  z1;
                   5723:    int k=0, l;
                   5724:    int first=1, first1, first2;
                   5725:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5726:    double **dnewm,**doldm;
                   5727:    double *xp;
                   5728:    double *gp, *gm;
                   5729:    double **gradg, **trgradg;
                   5730:    double **mu;
                   5731:    double age, cov[NCOVMAX+1];
                   5732:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5733:    int theta;
                   5734:    char fileresprob[FILENAMELENGTH];
                   5735:    char fileresprobcov[FILENAMELENGTH];
                   5736:    char fileresprobcor[FILENAMELENGTH];
                   5737:    double ***varpij;
                   5738: 
                   5739:    strcpy(fileresprob,"PROB_"); 
                   5740:    strcat(fileresprob,fileres);
                   5741:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5742:      printf("Problem with resultfile: %s\n", fileresprob);
                   5743:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5744:    }
                   5745:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5746:    strcat(fileresprobcov,fileresu);
                   5747:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5748:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5749:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5750:    }
                   5751:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5752:    strcat(fileresprobcor,fileresu);
                   5753:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5754:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5755:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5756:    }
                   5757:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5758:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5759:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5760:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5761:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5762:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5763:    pstamp(ficresprob);
                   5764:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5765:    fprintf(ficresprob,"# Age");
                   5766:    pstamp(ficresprobcov);
                   5767:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5768:    fprintf(ficresprobcov,"# Age");
                   5769:    pstamp(ficresprobcor);
                   5770:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5771:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5772: 
                   5773: 
1.222     brouard  5774:    for(i=1; i<=nlstate;i++)
                   5775:      for(j=1; j<=(nlstate+ndeath);j++){
                   5776:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5777:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5778:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5779:      }  
                   5780:    /* fprintf(ficresprob,"\n");
                   5781:       fprintf(ficresprobcov,"\n");
                   5782:       fprintf(ficresprobcor,"\n");
                   5783:    */
                   5784:    xp=vector(1,npar);
                   5785:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5786:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5787:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5788:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5789:    first=1;
                   5790:    fprintf(ficgp,"\n# Routine varprob");
                   5791:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5792:    fprintf(fichtm,"\n");
                   5793: 
                   5794:    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);
                   5795:    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);
                   5796:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5797: and drawn. It helps understanding how is the covariance between two incidences.\
                   5798:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5799:    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  5800: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5801: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5802: standard deviations wide on each axis. <br>\
                   5803:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5804:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5805: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5806: 
1.222     brouard  5807:    cov[1]=1;
                   5808:    /* tj=cptcoveff; */
1.225     brouard  5809:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5810:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5811:    j1=0;
1.224     brouard  5812:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5813:      if  (cptcovn>0) {
                   5814:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5815:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5816:        fprintf(ficresprob, "**********\n#\n");
                   5817:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5818:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5819:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5820:                        
1.222     brouard  5821:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5822:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5823:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5824:                        
                   5825:                        
1.222     brouard  5826:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5827:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5828:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5829:                        
1.222     brouard  5830:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5831:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5832:        fprintf(ficresprobcor, "**********\n#");    
                   5833:        if(invalidvarcomb[j1]){
                   5834:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5835:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5836:         continue;
                   5837:        }
                   5838:      }
                   5839:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5840:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5841:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5842:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5843:      for (age=bage; age<=fage; age ++){ 
                   5844:        cov[2]=age;
                   5845:        if(nagesqr==1)
                   5846:         cov[3]= age*age;
                   5847:        for (k=1; k<=cptcovn;k++) {
                   5848:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5849:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5850:                                                                    * 1  1 1 1 1
                   5851:                                                                    * 2  2 1 1 1
                   5852:                                                                    * 3  1 2 1 1
                   5853:                                                                    */
                   5854:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5855:        }
                   5856:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5857:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5858:        for (k=1; k<=cptcovprod;k++)
                   5859:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5860:                        
                   5861:                        
1.222     brouard  5862:        for(theta=1; theta <=npar; theta++){
                   5863:         for(i=1; i<=npar; i++)
                   5864:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5865:                                
1.222     brouard  5866:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5867:                                
1.222     brouard  5868:         k=0;
                   5869:         for(i=1; i<= (nlstate); i++){
                   5870:           for(j=1; j<=(nlstate+ndeath);j++){
                   5871:             k=k+1;
                   5872:             gp[k]=pmmij[i][j];
                   5873:           }
                   5874:         }
1.220     brouard  5875:                                
1.222     brouard  5876:         for(i=1; i<=npar; i++)
                   5877:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5878:                                
1.222     brouard  5879:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5880:         k=0;
                   5881:         for(i=1; i<=(nlstate); i++){
                   5882:           for(j=1; j<=(nlstate+ndeath);j++){
                   5883:             k=k+1;
                   5884:             gm[k]=pmmij[i][j];
                   5885:           }
                   5886:         }
1.220     brouard  5887:                                
1.222     brouard  5888:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5889:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5890:        }
1.126     brouard  5891: 
1.222     brouard  5892:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5893:         for(theta=1; theta <=npar; theta++)
                   5894:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5895:                        
1.222     brouard  5896:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5897:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5898:                        
1.222     brouard  5899:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5900:                        
1.222     brouard  5901:        k=0;
                   5902:        for(i=1; i<=(nlstate); i++){
                   5903:         for(j=1; j<=(nlstate+ndeath);j++){
                   5904:           k=k+1;
                   5905:           mu[k][(int) age]=pmmij[i][j];
                   5906:         }
                   5907:        }
                   5908:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5909:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5910:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5911:                        
1.222     brouard  5912:        /*printf("\n%d ",(int)age);
                   5913:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5914:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5915:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5916:         }*/
1.220     brouard  5917:                        
1.222     brouard  5918:        fprintf(ficresprob,"\n%d ",(int)age);
                   5919:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5920:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5921:                        
1.222     brouard  5922:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5923:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5924:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5925:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5926:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5927:        }
                   5928:        i=0;
                   5929:        for (k=1; k<=(nlstate);k++){
                   5930:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5931:           i++;
                   5932:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5933:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5934:           for (j=1; j<=i;j++){
                   5935:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5936:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5937:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5938:           }
                   5939:         }
                   5940:        }/* end of loop for state */
                   5941:      } /* end of loop for age */
                   5942:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5943:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5944:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5945:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5946:     
                   5947:      /* Confidence intervalle of pij  */
                   5948:      /*
                   5949:        fprintf(ficgp,"\nunset parametric;unset label");
                   5950:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5951:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5952:        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);
                   5953:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5954:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5955:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5956:      */
                   5957:                
                   5958:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5959:      first1=1;first2=2;
                   5960:      for (k2=1; k2<=(nlstate);k2++){
                   5961:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5962:         if(l2==k2) continue;
                   5963:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5964:         for (k1=1; k1<=(nlstate);k1++){
                   5965:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5966:             if(l1==k1) continue;
                   5967:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5968:             if(i<=j) continue;
                   5969:             for (age=bage; age<=fage; age ++){ 
                   5970:               if ((int)age %5==0){
                   5971:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5972:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5973:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5974:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5975:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5976:                 c12=cv12/sqrt(v1*v2);
                   5977:                 /* Computing eigen value of matrix of covariance */
                   5978:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5979:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5980:                 if ((lc2 <0) || (lc1 <0) ){
                   5981:                   if(first2==1){
                   5982:                     first1=0;
                   5983:                     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);
                   5984:                   }
                   5985:                   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);
                   5986:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5987:                   /* lc2=fabs(lc2); */
                   5988:                 }
1.220     brouard  5989:                                                                
1.222     brouard  5990:                 /* Eigen vectors */
                   5991:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5992:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5993:                 v21=(lc1-v1)/cv12*v11;
                   5994:                 v12=-v21;
                   5995:                 v22=v11;
                   5996:                 tnalp=v21/v11;
                   5997:                 if(first1==1){
                   5998:                   first1=0;
                   5999:                   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);
                   6000:                 }
                   6001:                 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);
                   6002:                 /*printf(fignu*/
                   6003:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6004:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6005:                 if(first==1){
                   6006:                   first=0;
                   6007:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6008:                   fprintf(ficgp,"\nset parametric;unset label");
                   6009:                   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);
                   6010:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6011:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6012:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6013: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6014:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6015:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6016:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6017:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6018:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6019:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6020:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6021:                   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",      \
                   6022:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6023:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6024:                 }else{
                   6025:                   first=0;
                   6026:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6027:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6028:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6029:                   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", \
                   6030:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6031:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6032:                 }/* if first */
                   6033:               } /* age mod 5 */
                   6034:             } /* end loop age */
                   6035:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6036:             first=1;
                   6037:           } /*l12 */
                   6038:         } /* k12 */
                   6039:        } /*l1 */
                   6040:      }/* k1 */
                   6041:    }  /* loop on combination of covariates j1 */
                   6042:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6043:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6044:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6045:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6046:    free_vector(xp,1,npar);
                   6047:    fclose(ficresprob);
                   6048:    fclose(ficresprobcov);
                   6049:    fclose(ficresprobcor);
                   6050:    fflush(ficgp);
                   6051:    fflush(fichtmcov);
                   6052:  }
1.126     brouard  6053: 
                   6054: 
                   6055: /******************* Printing html file ***********/
1.201     brouard  6056: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6057:                  int lastpass, int stepm, int weightopt, char model[],\
                   6058:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6059:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6060:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6061:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6062:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6063: 
                   6064:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6065:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6066: </ul>");
1.237     brouard  6067:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6068: </ul>", model);
1.214     brouard  6069:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6070:    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",
                   6071:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6072:    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  6073:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6074:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6075:    fprintf(fichtm,"\
                   6076:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6077:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6078:    fprintf(fichtm,"\
1.217     brouard  6079:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6080:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6081:    fprintf(fichtm,"\
1.126     brouard  6082:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6083:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6084:    fprintf(fichtm,"\
1.217     brouard  6085:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6086:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6087:    fprintf(fichtm,"\
1.211     brouard  6088:  - (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  6089:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6090:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6091:    if(prevfcast==1){
                   6092:      fprintf(fichtm,"\
                   6093:  - Prevalence projections by age and states:                           \
1.201     brouard  6094:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6095:    }
1.126     brouard  6096: 
1.222     brouard  6097:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6098: 
1.225     brouard  6099:    m=pow(2,cptcoveff);
1.222     brouard  6100:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6101: 
1.222     brouard  6102:    jj1=0;
1.237     brouard  6103: 
                   6104:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.222     brouard  6105:    for(k1=1; k1<=m;k1++){
1.237     brouard  6106:      if(TKresult[nres]!= k1)
                   6107:        continue;
1.220     brouard  6108: 
1.222     brouard  6109:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6110:      jj1++;
                   6111:      if (cptcovn > 0) {
                   6112:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6113:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6114:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6115:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6116:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6117:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6118:        }
1.237     brouard  6119:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6120:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6121:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6122:       }
                   6123:        
1.230     brouard  6124:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6125:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6126:        if(invalidvarcomb[k1]){
                   6127:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6128:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6129:         continue;
                   6130:        }
                   6131:      }
                   6132:      /* aij, bij */
                   6133:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
1.211     brouard  6134: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222     brouard  6135:      /* Pij */
                   6136:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  6137: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222     brouard  6138:      /* Quasi-incidences */
                   6139:      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  6140:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6141:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   6142: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
1.201     brouard  6143: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222     brouard  6144:      /* Survival functions (period) in state j */
                   6145:      for(cpt=1; cpt<=nlstate;cpt++){
                   6146:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
1.201     brouard  6147: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
1.222     brouard  6148:      }
                   6149:      /* State specific survival functions (period) */
                   6150:      for(cpt=1; cpt<=nlstate;cpt++){
                   6151:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6152:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  6153:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
1.222     brouard  6154:      }
                   6155:      /* Period (stable) prevalence in each health state */
                   6156:      for(cpt=1; cpt<=nlstate;cpt++){
                   6157:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
1.201     brouard  6158: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
1.222     brouard  6159:      }
                   6160:      if(backcast==1){
                   6161:        /* Period (stable) back prevalence in each health state */
                   6162:        for(cpt=1; cpt<=nlstate;cpt++){
                   6163:         fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
1.217     brouard  6164: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
1.222     brouard  6165:        }
1.217     brouard  6166:      }
1.222     brouard  6167:      if(prevfcast==1){
                   6168:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6169:        for(cpt=1; cpt<=nlstate;cpt++){
                   6170:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
1.213     brouard  6171: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
1.222     brouard  6172:        }
                   6173:      }
1.220     brouard  6174:         
1.222     brouard  6175:      for(cpt=1; cpt<=nlstate;cpt++) {
                   6176:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
1.201     brouard  6177: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.222     brouard  6178:      }
                   6179:      /* } /\* end i1 *\/ */
                   6180:    }/* End k1 */
                   6181:    fprintf(fichtm,"</ul>");
1.126     brouard  6182: 
1.222     brouard  6183:    fprintf(fichtm,"\
1.126     brouard  6184: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6185:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6186:  - 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  6187: But because parameters are usually highly correlated (a higher incidence of disability \
                   6188: and a higher incidence of recovery can give very close observed transition) it might \
                   6189: be very useful to look not only at linear confidence intervals estimated from the \
                   6190: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6191: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6192: covariance matrix of the one-step probabilities. \
                   6193: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6194: 
1.222     brouard  6195:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6196:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6197:    fprintf(fichtm,"\
1.126     brouard  6198:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6199:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6200: 
1.222     brouard  6201:    fprintf(fichtm,"\
1.126     brouard  6202:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6203:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6204:    fprintf(fichtm,"\
1.126     brouard  6205:  - 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): \
                   6206:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6207:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6208:    fprintf(fichtm,"\
1.126     brouard  6209:  - (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): \
                   6210:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6211:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6212:    fprintf(fichtm,"\
1.128     brouard  6213:  - 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  6214:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6215:    fprintf(fichtm,"\
1.128     brouard  6216:  - 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  6217:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6218:    fprintf(fichtm,"\
1.126     brouard  6219:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6220:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6221: 
                   6222: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6223: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6224: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6225: /*     <br>",fileres,fileres,fileres,fileres); */
                   6226: /*  else  */
                   6227: /*    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  6228:    fflush(fichtm);
                   6229:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6230: 
1.225     brouard  6231:    m=pow(2,cptcoveff);
1.222     brouard  6232:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6233: 
1.222     brouard  6234:    jj1=0;
1.237     brouard  6235: 
                   6236:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.222     brouard  6237:    for(k1=1; k1<=m;k1++){
1.237     brouard  6238:      if(TKresult[nres]!= k1)
                   6239:        continue;
1.222     brouard  6240:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6241:      jj1++;
1.126     brouard  6242:      if (cptcovn > 0) {
                   6243:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6244:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6245:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6246:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6247:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6248:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6249:       }
                   6250: 
1.126     brouard  6251:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6252: 
1.222     brouard  6253:        if(invalidvarcomb[k1]){
                   6254:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6255:         continue;
                   6256:        }
1.126     brouard  6257:      }
                   6258:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6259:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   6260: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  6261: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  6262:      }
                   6263:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6264: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6265: true period expectancies (those weighted with period prevalences are also\
                   6266:  drawn in addition to the population based expectancies computed using\
1.218     brouard  6267:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  6268: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222     brouard  6269:      /* } /\* end i1 *\/ */
                   6270:    }/* End k1 */
                   6271:    fprintf(fichtm,"</ul>");
                   6272:    fflush(fichtm);
1.126     brouard  6273: }
                   6274: 
                   6275: /******************* Gnuplot file **************/
1.223     brouard  6276: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6277: 
                   6278:   char dirfileres[132],optfileres[132];
1.223     brouard  6279:   char gplotcondition[132];
1.237     brouard  6280:   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  6281:   int lv=0, vlv=0, kl=0;
1.130     brouard  6282:   int ng=0;
1.201     brouard  6283:   int vpopbased;
1.223     brouard  6284:   int ioffset; /* variable offset for columns */
1.235     brouard  6285:   int nres=0; /* Index of resultline */
1.219     brouard  6286: 
1.126     brouard  6287: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6288: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6289: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6290: /*   } */
                   6291: 
                   6292:   /*#ifdef windows */
                   6293:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6294:   /*#endif */
1.225     brouard  6295:   m=pow(2,cptcoveff);
1.126     brouard  6296: 
1.202     brouard  6297:   /* Contribution to likelihood */
                   6298:   /* Plot the probability implied in the likelihood */
1.223     brouard  6299:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6300:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6301:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6302:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6303: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6304:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6305: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6306:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6307:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6308:   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));
                   6309:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6310:   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));
                   6311:   for (i=1; i<= nlstate ; i ++) {
                   6312:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6313:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6314:     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);
                   6315:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6316:       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);
                   6317:     }
                   6318:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6319:   }
                   6320:   /* 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 */               
                   6321:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6322:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6323:   fprintf(ficgp,"\nset out;unset log\n");
                   6324:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6325: 
1.126     brouard  6326:   strcpy(dirfileres,optionfilefiname);
                   6327:   strcpy(optfileres,"vpl");
1.223     brouard  6328:   /* 1eme*/
1.238     brouard  6329:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6330:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6331:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6332:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6333:        if(TKresult[nres]!= k1)
                   6334:          continue;
                   6335:        /* We are interested in selected combination by the resultline */
                   6336:        printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
                   6337:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6338:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6339:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6340:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6341:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6342:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6343:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6344:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   6345:          printf(" V%d=%d ",Tvaraff[k],vlv);
                   6346:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6347:        }
                   6348:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6349:          printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6350:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6351:        }       
                   6352:        printf("\n#\n");
                   6353:        fprintf(ficgp,"\n#\n");
                   6354:        if(invalidvarcomb[k1]){
                   6355:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6356:          continue;
                   6357:        }
1.235     brouard  6358:       
1.238     brouard  6359:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   6360:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.240   ! brouard  6361:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.235     brouard  6362:       
1.238     brouard  6363:        for (i=1; i<= nlstate ; i ++) {
                   6364:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6365:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6366:        }
                   6367:        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
                   6368:        for (i=1; i<= nlstate ; i ++) {
                   6369:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6370:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6371:        } 
                   6372:        fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
                   6373:        for (i=1; i<= nlstate ; i ++) {
                   6374:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6375:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6376:        }  
                   6377:        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));
                   6378:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6379:          /* 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); */
                   6380:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
                   6381:          if(cptcoveff ==0){
                   6382:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",        2+(cpt-1),  cpt );
                   6383:          }else{
                   6384:            kl=0;
                   6385:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6386:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6387:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6388:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6389:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6390:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6391:              kl++;
1.238     brouard  6392:              /* 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 *\/ */
                   6393:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6394:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6395:              /* ''  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*/
                   6396:              if(k==cptcoveff){
                   6397:                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   6398:                        4+(cpt-1),  cpt );  /* 4 or 6 ?*/
                   6399:              }else{
                   6400:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6401:                kl++;
                   6402:              }
                   6403:            } /* end covariate */
                   6404:          } /* end if no covariate */
                   6405:        } /* end if backcast */
                   6406:        fprintf(ficgp,"\nset out \n");
                   6407:       } /* nres */
1.201     brouard  6408:     } /* k1 */
                   6409:   } /* cpt */
1.235     brouard  6410: 
                   6411:   
1.126     brouard  6412:   /*2 eme*/
1.238     brouard  6413:   for (k1=1; k1<= m ; k1 ++){  
                   6414:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6415:       if(TKresult[nres]!= k1)
                   6416:        continue;
                   6417:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6418:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6419:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6420:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6421:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6422:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6423:        vlv= nbcode[Tvaraff[k]][lv];
                   6424:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6425:       }
1.237     brouard  6426:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6427:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6428:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6429:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6430:       }
1.211     brouard  6431:       fprintf(ficgp,"\n#\n");
1.223     brouard  6432:       if(invalidvarcomb[k1]){
                   6433:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6434:        continue;
                   6435:       }
1.219     brouard  6436:                        
1.238     brouard  6437:       fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   6438:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6439:        if(vpopbased==0)
                   6440:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6441:        else
                   6442:          fprintf(ficgp,"\nreplot ");
                   6443:        for (i=1; i<= nlstate+1 ; i ++) {
                   6444:          k=2*i;
                   6445:          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);
                   6446:          for (j=1; j<= nlstate+1 ; j ++) {
                   6447:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6448:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6449:          }   
                   6450:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6451:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6452:          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);
                   6453:          for (j=1; j<= nlstate+1 ; j ++) {
                   6454:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6455:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6456:          }   
                   6457:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6458:          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);
                   6459:          for (j=1; j<= nlstate+1 ; j ++) {
                   6460:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6461:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6462:          }   
                   6463:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6464:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6465:        } /* state */
                   6466:       } /* vpopbased */
                   6467:       fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   6468:     } /* end nres */
                   6469:   } /* k1 end 2 eme*/
                   6470:        
                   6471:        
                   6472:   /*3eme*/
                   6473:   for (k1=1; k1<= m ; k1 ++){
                   6474:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.240   ! brouard  6475:       if(TKresult[nres]!= k1)
1.238     brouard  6476:        continue;
                   6477: 
                   6478:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6479:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6480:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6481:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6482:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6483:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6484:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6485:          vlv= nbcode[Tvaraff[k]][lv];
                   6486:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6487:        }
                   6488:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6489:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6490:        }       
                   6491:        fprintf(ficgp,"\n#\n");
                   6492:        if(invalidvarcomb[k1]){
                   6493:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6494:          continue;
                   6495:        }
                   6496:                        
                   6497:        /*       k=2+nlstate*(2*cpt-2); */
                   6498:        k=2+(nlstate+1)*(cpt-1);
                   6499:        fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
                   6500:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6501: 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  6502:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6503:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6504:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6505:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6506:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6507:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6508:                                
1.238     brouard  6509:        */
                   6510:        for (i=1; i< nlstate ; i ++) {
                   6511:          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);
                   6512:          /*    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  6513:                                
1.238     brouard  6514:        } 
                   6515:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6516:       }
                   6517:     } /* end nres */
                   6518:   } /* end kl 3eme */
1.126     brouard  6519:   
1.223     brouard  6520:   /* 4eme */
1.201     brouard  6521:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6522:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6523:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6524:       if(TKresult[nres]!= k1)
1.223     brouard  6525:        continue;
1.238     brouard  6526:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6527:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6528:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6529:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6530:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6531:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6532:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6533:          vlv= nbcode[Tvaraff[k]][lv];
                   6534:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6535:        }
                   6536:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6537:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6538:        }       
                   6539:        fprintf(ficgp,"\n#\n");
                   6540:        if(invalidvarcomb[k1]){
                   6541:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6542:          continue;
1.223     brouard  6543:        }
1.238     brouard  6544:       
                   6545:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   6546:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6547: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6548:        k=3;
                   6549:        for (i=1; i<= nlstate ; i ++){
                   6550:          if(i==1){
                   6551:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6552:          }else{
                   6553:            fprintf(ficgp,", '' ");
                   6554:          }
                   6555:          l=(nlstate+ndeath)*(i-1)+1;
                   6556:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6557:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6558:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6559:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6560:        } /* nlstate */
                   6561:        fprintf(ficgp,"\nset out\n");
                   6562:       } /* end cpt state*/ 
                   6563:     } /* end nres */
                   6564:   } /* end covariate k1 */  
                   6565: 
1.220     brouard  6566: /* 5eme */
1.201     brouard  6567:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6568:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6569:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6570:       if(TKresult[nres]!= k1)
1.227     brouard  6571:        continue;
1.238     brouard  6572:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6573:        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);
                   6574:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6575:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6576:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6577:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6578:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6579:          vlv= nbcode[Tvaraff[k]][lv];
                   6580:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6581:        }
                   6582:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6583:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6584:        }       
                   6585:        fprintf(ficgp,"\n#\n");
                   6586:        if(invalidvarcomb[k1]){
                   6587:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6588:          continue;
                   6589:        }
1.227     brouard  6590:       
1.238     brouard  6591:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   6592:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6593: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6594:        k=3;
                   6595:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6596:          if(j==1)
                   6597:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6598:          else
                   6599:            fprintf(ficgp,", '' ");
                   6600:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6601:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6602:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6603:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6604:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6605:        } /* nlstate */
                   6606:        fprintf(ficgp,", '' ");
                   6607:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6608:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6609:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6610:          if(j < nlstate)
                   6611:            fprintf(ficgp,"$%d +",k+l);
                   6612:          else
                   6613:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6614:        }
                   6615:        fprintf(ficgp,"\nset out\n");
                   6616:       } /* end cpt state*/ 
                   6617:     } /* end covariate */  
                   6618:   } /* end nres */
1.227     brouard  6619:   
1.220     brouard  6620: /* 6eme */
1.202     brouard  6621:   /* CV preval stable (period) for each covariate */
1.237     brouard  6622:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6623:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6624:     if(TKresult[nres]!= k1)
                   6625:       continue;
1.153     brouard  6626:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6627:       
1.211     brouard  6628:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6629:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6630:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6631:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6632:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6633:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6634:        vlv= nbcode[Tvaraff[k]][lv];
                   6635:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6636:       }
1.237     brouard  6637:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6638:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6639:       }        
1.211     brouard  6640:       fprintf(ficgp,"\n#\n");
1.223     brouard  6641:       if(invalidvarcomb[k1]){
1.227     brouard  6642:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6643:        continue;
1.223     brouard  6644:       }
1.227     brouard  6645:       
1.201     brouard  6646:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6647:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6648: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6649:       k=3; /* Offset */
1.153     brouard  6650:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6651:        if(i==1)
                   6652:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6653:        else
                   6654:          fprintf(ficgp,", '' ");
                   6655:        l=(nlstate+ndeath)*(i-1)+1;
                   6656:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6657:        for (j=2; j<= nlstate ; j ++)
                   6658:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6659:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6660:       } /* nlstate */
1.201     brouard  6661:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6662:     } /* end cpt state*/ 
                   6663:   } /* end covariate */  
1.227     brouard  6664:   
                   6665:   
1.220     brouard  6666: /* 7eme */
1.218     brouard  6667:   if(backcast == 1){
1.217     brouard  6668:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6669:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6670:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6671:       if(TKresult[nres]!= k1)
                   6672:        continue;
1.218     brouard  6673:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6674:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6675:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6676:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6677:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6678:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6679:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6680:          vlv= nbcode[Tvaraff[k]][lv];
                   6681:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6682:        }
1.237     brouard  6683:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6684:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6685:        }       
1.227     brouard  6686:        fprintf(ficgp,"\n#\n");
                   6687:        if(invalidvarcomb[k1]){
                   6688:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6689:          continue;
                   6690:        }
                   6691:        
                   6692:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6693:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6694: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6695:        k=3; /* Offset */
                   6696:        for (i=1; i<= nlstate ; i ++){
                   6697:          if(i==1)
                   6698:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6699:          else
                   6700:            fprintf(ficgp,", '' ");
                   6701:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6702:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6703:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6704:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6705:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6706:          /* for (j=2; j<= nlstate ; j ++) */
                   6707:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6708:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6709:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6710:        } /* nlstate */
                   6711:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6712:       } /* end cpt state*/ 
                   6713:     } /* end covariate */  
                   6714:   } /* End if backcast */
                   6715:   
1.223     brouard  6716:   /* 8eme */
1.218     brouard  6717:   if(prevfcast==1){
                   6718:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6719:     
1.237     brouard  6720:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6721:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6722:       if(TKresult[nres]!= k1)
                   6723:        continue;
1.211     brouard  6724:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6725:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6726:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6727:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6728:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6729:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6730:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6731:          vlv= nbcode[Tvaraff[k]][lv];
                   6732:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6733:        }
1.237     brouard  6734:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6735:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6736:        }       
1.227     brouard  6737:        fprintf(ficgp,"\n#\n");
                   6738:        if(invalidvarcomb[k1]){
                   6739:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6740:          continue;
                   6741:        }
                   6742:        
                   6743:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6744:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6745:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  6746: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6747:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6748:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6749:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6750:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6751:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6752:          if(i==1){
                   6753:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6754:          }else{
                   6755:            fprintf(ficgp,",\\\n '' ");
                   6756:          }
                   6757:          if(cptcoveff ==0){ /* No covariate */
                   6758:            ioffset=2; /* Age is in 2 */
                   6759:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6760:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6761:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6762:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6763:            fprintf(ficgp," u %d:(", ioffset); 
                   6764:            if(i==nlstate+1)
                   6765:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6766:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6767:            else
                   6768:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6769:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6770:          }else{ /* more than 2 covariates */
                   6771:            if(cptcoveff ==1){
                   6772:              ioffset=4; /* Age is in 4 */
                   6773:            }else{
                   6774:              ioffset=6; /* Age is in 6 */
                   6775:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6776:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6777:            }   
                   6778:            fprintf(ficgp," u %d:(",ioffset); 
                   6779:            kl=0;
                   6780:            strcpy(gplotcondition,"(");
                   6781:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6782:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6783:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6784:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6785:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6786:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6787:              kl++;
                   6788:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6789:              kl++;
                   6790:              if(k <cptcoveff && cptcoveff>1)
                   6791:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6792:            }
                   6793:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6794:            /* 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 *\/ */
                   6795:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6796:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6797:            /* ''  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*/
                   6798:            if(i==nlstate+1){
                   6799:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6800:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6801:            }else{
                   6802:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6803:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6804:            }
                   6805:          } /* end if covariate */
                   6806:        } /* nlstate */
                   6807:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6808:       } /* end cpt state*/
                   6809:     } /* end covariate */
                   6810:   } /* End if prevfcast */
1.227     brouard  6811:   
                   6812:   
1.238     brouard  6813:   /* 9eme writing MLE parameters */
                   6814:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6815:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6816:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6817:     for(k=1; k <=(nlstate+ndeath); k++){
                   6818:       if (k != i) {
1.227     brouard  6819:        fprintf(ficgp,"#   current state %d\n",k);
                   6820:        for(j=1; j <=ncovmodel; j++){
                   6821:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6822:          jk++; 
                   6823:        }
                   6824:        fprintf(ficgp,"\n");
1.126     brouard  6825:       }
                   6826:     }
1.223     brouard  6827:   }
1.187     brouard  6828:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6829:   
1.145     brouard  6830:   /*goto avoid;*/
1.238     brouard  6831:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   6832:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6833:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6834:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6835:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6836:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6837:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6838:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6839:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6840:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6841:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6842:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6843:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6844:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6845:   fprintf(ficgp,"#\n");
1.223     brouard  6846:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  6847:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6848:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  6849:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6850:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6851:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6852:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6853:       if(TKresult[nres]!= jk)
                   6854:        continue;
                   6855:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6856:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6857:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6858:       }        
                   6859:       fprintf(ficgp,"\n#\n");
1.223     brouard  6860:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6861:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6862:       if (ng==1){
                   6863:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6864:        fprintf(ficgp,"\nunset log y");
                   6865:       }else if (ng==2){
                   6866:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6867:        fprintf(ficgp,"\nset log y");
                   6868:       }else if (ng==3){
                   6869:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6870:        fprintf(ficgp,"\nset log y");
                   6871:       }else
                   6872:        fprintf(ficgp,"\nunset title ");
                   6873:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6874:       i=1;
                   6875:       for(k2=1; k2<=nlstate; k2++) {
                   6876:        k3=i;
                   6877:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6878:          if (k != k2){
                   6879:            switch( ng) {
                   6880:            case 1:
                   6881:              if(nagesqr==0)
                   6882:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6883:              else /* nagesqr =1 */
                   6884:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6885:              break;
                   6886:            case 2: /* ng=2 */
                   6887:              if(nagesqr==0)
                   6888:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6889:              else /* nagesqr =1 */
                   6890:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6891:              break;
                   6892:            case 3:
                   6893:              if(nagesqr==0)
                   6894:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6895:              else /* nagesqr =1 */
                   6896:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6897:              break;
                   6898:            }
                   6899:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  6900:            ijp=1; /* product no age */
                   6901:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   6902:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  6903:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  6904:              if(j==Tage[ij]) { /* Product by age */
                   6905:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  6906:                  if(DummyV[j]==0){
1.237     brouard  6907:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   6908:                  }else{ /* quantitative */
                   6909:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   6910:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6911:                  }
                   6912:                  ij++;
                   6913:                }
                   6914:              }else if(j==Tprod[ijp]) { /* */ 
                   6915:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   6916:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  6917:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   6918:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  6919:                      /* 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)]); */
                   6920:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   6921:                    }else{ /* Vn is dummy and Vm is quanti */
                   6922:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   6923:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6924:                    }
                   6925:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  6926:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  6927:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   6928:                    }else{ /* Both quanti */
                   6929:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6930:                    }
                   6931:                  }
1.238     brouard  6932:                  ijp++;
1.237     brouard  6933:                }
                   6934:              } else{  /* simple covariate */
                   6935:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   6936:                if(Dummy[j]==0){
                   6937:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   6938:                }else{ /* quantitative */
                   6939:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  6940:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6941:                }
1.237     brouard  6942:              } /* end simple */
                   6943:            } /* end j */
1.223     brouard  6944:          }else{
                   6945:            i=i-ncovmodel;
                   6946:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6947:              fprintf(ficgp," (1.");
                   6948:          }
1.227     brouard  6949:          
1.223     brouard  6950:          if(ng != 1){
                   6951:            fprintf(ficgp,")/(1");
1.227     brouard  6952:            
1.223     brouard  6953:            for(k1=1; k1 <=nlstate; k1++){ 
                   6954:              if(nagesqr==0)
                   6955:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6956:              else /* nagesqr =1 */
                   6957:                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  6958:               
1.223     brouard  6959:              ij=1;
                   6960:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  6961:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6962:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  6963:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6964:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6965:                    ij++;
                   6966:                  }
                   6967:                }
                   6968:                else
1.225     brouard  6969:                  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  6970:              }
                   6971:              fprintf(ficgp,")");
                   6972:            }
                   6973:            fprintf(ficgp,")");
                   6974:            if(ng ==2)
                   6975:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6976:            else /* ng= 3 */
                   6977:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6978:          }else{ /* end ng <> 1 */
                   6979:            if( k !=k2) /* logit p11 is hard to draw */
                   6980:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   6981:          }
                   6982:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6983:            fprintf(ficgp,",");
                   6984:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6985:            fprintf(ficgp,",");
                   6986:          i=i+ncovmodel;
                   6987:        } /* end k */
                   6988:       } /* end k2 */
                   6989:       fprintf(ficgp,"\n set out\n");
                   6990:     } /* end jk */
                   6991:   } /* end ng */
                   6992:   /* avoid: */
                   6993:   fflush(ficgp); 
1.126     brouard  6994: }  /* end gnuplot */
                   6995: 
                   6996: 
                   6997: /*************** Moving average **************/
1.219     brouard  6998: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  6999:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7000:    
1.222     brouard  7001:    int i, cpt, cptcod;
                   7002:    int modcovmax =1;
                   7003:    int mobilavrange, mob;
                   7004:    int iage=0;
                   7005: 
                   7006:    double sum=0.;
                   7007:    double age;
                   7008:    double *sumnewp, *sumnewm;
                   7009:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7010:   
                   7011:   
1.225     brouard  7012:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7013:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7014: 
                   7015:    sumnewp = vector(1,ncovcombmax);
                   7016:    sumnewm = vector(1,ncovcombmax);
                   7017:    agemingood = vector(1,ncovcombmax); 
                   7018:    agemaxgood = vector(1,ncovcombmax);
                   7019: 
                   7020:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7021:      sumnewm[cptcod]=0.;
                   7022:      sumnewp[cptcod]=0.;
                   7023:      agemingood[cptcod]=0;
                   7024:      agemaxgood[cptcod]=0;
                   7025:    }
                   7026:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7027:   
                   7028:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7029:      if(mobilav==1) mobilavrange=5; /* default */
                   7030:      else mobilavrange=mobilav;
                   7031:      for (age=bage; age<=fage; age++)
                   7032:        for (i=1; i<=nlstate;i++)
                   7033:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7034:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7035:      /* We keep the original values on the extreme ages bage, fage and for 
                   7036:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7037:        we use a 5 terms etc. until the borders are no more concerned. 
                   7038:      */ 
                   7039:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7040:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7041:         for (i=1; i<=nlstate;i++){
                   7042:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7043:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7044:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7045:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7046:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7047:             }
                   7048:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7049:           }
                   7050:         }
                   7051:        }/* end age */
                   7052:      }/* end mob */
                   7053:    }else
                   7054:      return -1;
                   7055:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7056:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7057:      if(invalidvarcomb[cptcod]){
                   7058:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7059:        continue;
                   7060:      }
1.219     brouard  7061: 
1.222     brouard  7062:      agemingood[cptcod]=fage-(mob-1)/2;
                   7063:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7064:        sumnewm[cptcod]=0.;
                   7065:        for (i=1; i<=nlstate;i++){
                   7066:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7067:        }
                   7068:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7069:         agemingood[cptcod]=age;
                   7070:        }else{ /* bad */
                   7071:         for (i=1; i<=nlstate;i++){
                   7072:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7073:         } /* i */
                   7074:        } /* end bad */
                   7075:      }/* age */
                   7076:      sum=0.;
                   7077:      for (i=1; i<=nlstate;i++){
                   7078:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7079:      }
                   7080:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7081:        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);
                   7082:        /* for (i=1; i<=nlstate;i++){ */
                   7083:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7084:        /* } /\* i *\/ */
                   7085:      } /* end bad */
                   7086:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7087:      /* From youngest, finding the oldest wrong */
                   7088:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7089:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7090:        sumnewm[cptcod]=0.;
                   7091:        for (i=1; i<=nlstate;i++){
                   7092:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7093:        }
                   7094:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7095:         agemaxgood[cptcod]=age;
                   7096:        }else{ /* bad */
                   7097:         for (i=1; i<=nlstate;i++){
                   7098:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7099:         } /* i */
                   7100:        } /* end bad */
                   7101:      }/* age */
                   7102:      sum=0.;
                   7103:      for (i=1; i<=nlstate;i++){
                   7104:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7105:      }
                   7106:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7107:        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);
                   7108:        /* for (i=1; i<=nlstate;i++){ */
                   7109:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7110:        /* } /\* i *\/ */
                   7111:      } /* end bad */
                   7112:                
                   7113:      for (age=bage; age<=fage; age++){
1.235     brouard  7114:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7115:        sumnewp[cptcod]=0.;
                   7116:        sumnewm[cptcod]=0.;
                   7117:        for (i=1; i<=nlstate;i++){
                   7118:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7119:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7120:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7121:        }
                   7122:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7123:      }
                   7124:      /* printf("\n"); */
                   7125:      /* } */
                   7126:      /* brutal averaging */
                   7127:      for (i=1; i<=nlstate;i++){
                   7128:        for (age=1; age<=bage; age++){
                   7129:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7130:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7131:        }       
                   7132:        for (age=fage; age<=AGESUP; age++){
                   7133:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7134:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7135:        }
                   7136:      } /* end i status */
                   7137:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7138:        for (age=1; age<=AGESUP; age++){
                   7139:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7140:         mobaverage[(int)age][i][cptcod]=0.;
                   7141:        }
                   7142:      }
                   7143:    }/* end cptcod */
                   7144:    free_vector(sumnewm,1, ncovcombmax);
                   7145:    free_vector(sumnewp,1, ncovcombmax);
                   7146:    free_vector(agemaxgood,1, ncovcombmax);
                   7147:    free_vector(agemingood,1, ncovcombmax);
                   7148:    return 0;
                   7149:  }/* End movingaverage */
1.218     brouard  7150:  
1.126     brouard  7151: 
                   7152: /************** Forecasting ******************/
1.235     brouard  7153:  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  7154:   /* proj1, year, month, day of starting projection 
                   7155:      agemin, agemax range of age
                   7156:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7157:      anproj2 year of en of projection (same day and month as proj1).
                   7158:   */
1.235     brouard  7159:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7160:   double agec; /* generic age */
                   7161:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7162:   double *popeffectif,*popcount;
                   7163:   double ***p3mat;
1.218     brouard  7164:   /* double ***mobaverage; */
1.126     brouard  7165:   char fileresf[FILENAMELENGTH];
                   7166: 
                   7167:   agelim=AGESUP;
1.211     brouard  7168:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7169:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7170:      We still use firstpass and lastpass as another selection.
                   7171:   */
1.214     brouard  7172:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7173:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7174:  
1.201     brouard  7175:   strcpy(fileresf,"F_"); 
                   7176:   strcat(fileresf,fileresu);
1.126     brouard  7177:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7178:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7179:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7180:   }
1.235     brouard  7181:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7182:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7183: 
1.225     brouard  7184:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7185: 
                   7186: 
                   7187:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7188:   if (stepm<=12) stepsize=1;
                   7189:   if(estepm < stepm){
                   7190:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7191:   }
                   7192:   else  hstepm=estepm;   
                   7193: 
                   7194:   hstepm=hstepm/stepm; 
                   7195:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7196:                                fractional in yp1 */
                   7197:   anprojmean=yp;
                   7198:   yp2=modf((yp1*12),&yp);
                   7199:   mprojmean=yp;
                   7200:   yp1=modf((yp2*30.5),&yp);
                   7201:   jprojmean=yp;
                   7202:   if(jprojmean==0) jprojmean=1;
                   7203:   if(mprojmean==0) jprojmean=1;
                   7204: 
1.227     brouard  7205:   i1=pow(2,cptcoveff);
1.126     brouard  7206:   if (cptcovn < 1){i1=1;}
                   7207:   
                   7208:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7209:   
                   7210:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7211:   
1.126     brouard  7212: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7213:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7214:   for(k=1; k<=i1;k++){
                   7215:     if(TKresult[nres]!= k)
                   7216:       continue;
1.227     brouard  7217:     if(invalidvarcomb[k]){
                   7218:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7219:       continue;
                   7220:     }
                   7221:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7222:     for(j=1;j<=cptcoveff;j++) {
                   7223:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7224:     }
1.235     brouard  7225:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7226:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7227:     }
1.227     brouard  7228:     fprintf(ficresf," yearproj age");
                   7229:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7230:       for(i=1; i<=nlstate;i++)               
                   7231:        fprintf(ficresf," p%d%d",i,j);
                   7232:       fprintf(ficresf," wp.%d",j);
                   7233:     }
                   7234:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7235:       fprintf(ficresf,"\n");
                   7236:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7237:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7238:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7239:        nhstepm = nhstepm/hstepm; 
                   7240:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7241:        oldm=oldms;savm=savms;
1.235     brouard  7242:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7243:        
                   7244:        for (h=0; h<=nhstepm; h++){
                   7245:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7246:            fprintf(ficresf,"\n");
                   7247:            for(j=1;j<=cptcoveff;j++) 
                   7248:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7249:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7250:          } 
                   7251:          for(j=1; j<=nlstate+ndeath;j++) {
                   7252:            ppij=0.;
                   7253:            for(i=1; i<=nlstate;i++) {
                   7254:              if (mobilav==1) 
                   7255:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7256:              else {
                   7257:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7258:              }
                   7259:              if (h*hstepm/YEARM*stepm== yearp) {
                   7260:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7261:              }
                   7262:            } /* end i */
                   7263:            if (h*hstepm/YEARM*stepm==yearp) {
                   7264:              fprintf(ficresf," %.3f", ppij);
                   7265:            }
                   7266:          }/* end j */
                   7267:        } /* end h */
                   7268:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7269:       } /* end agec */
                   7270:     } /* end yearp */
                   7271:   } /* end  k */
1.219     brouard  7272:        
1.126     brouard  7273:   fclose(ficresf);
1.215     brouard  7274:   printf("End of Computing forecasting \n");
                   7275:   fprintf(ficlog,"End of Computing forecasting\n");
                   7276: 
1.126     brouard  7277: }
                   7278: 
1.218     brouard  7279: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7280: /* 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  7281: /*   /\* back1, year, month, day of starting backection  */
                   7282: /*      agemin, agemax range of age */
                   7283: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7284: /*      anback2 year of en of backection (same day and month as back1). */
                   7285: /*   *\/ */
                   7286: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7287: /*   double agec; /\* generic age *\/ */
                   7288: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7289: /*   double *popeffectif,*popcount; */
                   7290: /*   double ***p3mat; */
                   7291: /*   /\* double ***mobaverage; *\/ */
                   7292: /*   char fileresfb[FILENAMELENGTH]; */
                   7293:        
                   7294: /*   agelim=AGESUP; */
                   7295: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7296: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7297: /*      We still use firstpass and lastpass as another selection. */
                   7298: /*   *\/ */
                   7299: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7300: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7301: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7302:        
                   7303: /*   strcpy(fileresfb,"FB_");  */
                   7304: /*   strcat(fileresfb,fileresu); */
                   7305: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7306: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7307: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7308: /*   } */
                   7309: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7310: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7311:        
1.225     brouard  7312: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7313:        
                   7314: /*   /\* if (mobilav!=0) { *\/ */
                   7315: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7316: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7317: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7318: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7319: /*   /\*   } *\/ */
                   7320: /*   /\* } *\/ */
                   7321:        
                   7322: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7323: /*   if (stepm<=12) stepsize=1; */
                   7324: /*   if(estepm < stepm){ */
                   7325: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7326: /*   } */
                   7327: /*   else  hstepm=estepm;    */
                   7328:        
                   7329: /*   hstepm=hstepm/stepm;  */
                   7330: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7331: /*                                fractional in yp1 *\/ */
                   7332: /*   anprojmean=yp; */
                   7333: /*   yp2=modf((yp1*12),&yp); */
                   7334: /*   mprojmean=yp; */
                   7335: /*   yp1=modf((yp2*30.5),&yp); */
                   7336: /*   jprojmean=yp; */
                   7337: /*   if(jprojmean==0) jprojmean=1; */
                   7338: /*   if(mprojmean==0) jprojmean=1; */
                   7339:        
1.225     brouard  7340: /*   i1=cptcoveff; */
1.218     brouard  7341: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7342:   
1.218     brouard  7343: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7344:   
1.218     brouard  7345: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7346:        
                   7347: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7348: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7349: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7350: /*       k=k+1; */
                   7351: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7352: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7353: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7354: /*       } */
                   7355: /*       fprintf(ficresfb," yearbproj age"); */
                   7356: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7357: /*                             for(i=1; i<=nlstate;i++)               */
                   7358: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7359: /*                             fprintf(ficresfb," p.%d",j); */
                   7360: /*       } */
                   7361: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7362: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7363: /*                             fprintf(ficresfb,"\n"); */
                   7364: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7365: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7366: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7367: /*                                     nhstepm = nhstepm/hstepm;  */
                   7368: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7369: /*                                     oldm=oldms;savm=savms; */
                   7370: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7371: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7372: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7373: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7374: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7375: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7376: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7377: /*                                             }  */
                   7378: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7379: /*                                                     ppij=0.; */
                   7380: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7381: /*                                                             if (mobilav==1)  */
                   7382: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7383: /*                                                             else { */
                   7384: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7385: /*                                                             } */
                   7386: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7387: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7388: /*                                                             } */
                   7389: /*                                                     } /\* end i *\/ */
                   7390: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7391: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7392: /*                                                     } */
                   7393: /*                                             }/\* end j *\/ */
                   7394: /*                                     } /\* end h *\/ */
                   7395: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7396: /*                             } /\* end agec *\/ */
                   7397: /*       } /\* end yearp *\/ */
                   7398: /*     } /\* end cptcod *\/ */
                   7399: /*   } /\* end  cptcov *\/ */
                   7400:        
                   7401: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7402:        
                   7403: /*   fclose(ficresfb); */
                   7404: /*   printf("End of Computing Back forecasting \n"); */
                   7405: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7406:        
1.218     brouard  7407: /* } */
1.217     brouard  7408: 
1.126     brouard  7409: /************** Forecasting *****not tested NB*************/
1.227     brouard  7410: /* 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  7411:   
1.227     brouard  7412: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7413: /*   int *popage; */
                   7414: /*   double calagedatem, agelim, kk1, kk2; */
                   7415: /*   double *popeffectif,*popcount; */
                   7416: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7417: /*   /\* double ***mobaverage; *\/ */
                   7418: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7419: 
1.227     brouard  7420: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7421: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7422: /*   agelim=AGESUP; */
                   7423: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7424:   
1.227     brouard  7425: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7426:   
                   7427:   
1.227     brouard  7428: /*   strcpy(filerespop,"POP_");  */
                   7429: /*   strcat(filerespop,fileresu); */
                   7430: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7431: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7432: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7433: /*   } */
                   7434: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7435: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7436: 
1.227     brouard  7437: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7438: 
1.227     brouard  7439: /*   /\* if (mobilav!=0) { *\/ */
                   7440: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7441: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7442: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7443: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7444: /*   /\*   } *\/ */
                   7445: /*   /\* } *\/ */
1.126     brouard  7446: 
1.227     brouard  7447: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7448: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7449:   
1.227     brouard  7450: /*   agelim=AGESUP; */
1.126     brouard  7451:   
1.227     brouard  7452: /*   hstepm=1; */
                   7453: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7454:        
1.227     brouard  7455: /*   if (popforecast==1) { */
                   7456: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7457: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7458: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7459: /*     }  */
                   7460: /*     popage=ivector(0,AGESUP); */
                   7461: /*     popeffectif=vector(0,AGESUP); */
                   7462: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7463:     
1.227     brouard  7464: /*     i=1;    */
                   7465: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7466:     
1.227     brouard  7467: /*     imx=i; */
                   7468: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7469: /*   } */
1.218     brouard  7470:   
1.227     brouard  7471: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7472: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7473: /*       k=k+1; */
                   7474: /*       fprintf(ficrespop,"\n#******"); */
                   7475: /*       for(j=1;j<=cptcoveff;j++) { */
                   7476: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7477: /*       } */
                   7478: /*       fprintf(ficrespop,"******\n"); */
                   7479: /*       fprintf(ficrespop,"# Age"); */
                   7480: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7481: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7482:       
1.227     brouard  7483: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7484: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7485:        
1.227     brouard  7486: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7487: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7488: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7489:          
1.227     brouard  7490: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7491: /*       oldm=oldms;savm=savms; */
                   7492: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7493:          
1.227     brouard  7494: /*       for (h=0; h<=nhstepm; h++){ */
                   7495: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7496: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7497: /*         }  */
                   7498: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7499: /*           kk1=0.;kk2=0; */
                   7500: /*           for(i=1; i<=nlstate;i++) {               */
                   7501: /*             if (mobilav==1)  */
                   7502: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7503: /*             else { */
                   7504: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7505: /*             } */
                   7506: /*           } */
                   7507: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7508: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7509: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7510: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7511: /*           } */
                   7512: /*         } */
                   7513: /*         for(i=1; i<=nlstate;i++){ */
                   7514: /*           kk1=0.; */
                   7515: /*           for(j=1; j<=nlstate;j++){ */
                   7516: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7517: /*           } */
                   7518: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7519: /*         } */
1.218     brouard  7520:            
1.227     brouard  7521: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7522: /*           for(j=1; j<=nlstate;j++)  */
                   7523: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7524: /*       } */
                   7525: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7526: /*     } */
                   7527: /*       } */
1.218     brouard  7528:       
1.227     brouard  7529: /*       /\******\/ */
1.218     brouard  7530:       
1.227     brouard  7531: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7532: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7533: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7534: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7535: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7536:          
1.227     brouard  7537: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7538: /*       oldm=oldms;savm=savms; */
                   7539: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7540: /*       for (h=0; h<=nhstepm; h++){ */
                   7541: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7542: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7543: /*         }  */
                   7544: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7545: /*           kk1=0.;kk2=0; */
                   7546: /*           for(i=1; i<=nlstate;i++) {               */
                   7547: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7548: /*           } */
                   7549: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7550: /*         } */
                   7551: /*       } */
                   7552: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7553: /*     } */
                   7554: /*       } */
                   7555: /*     }  */
                   7556: /*   } */
1.218     brouard  7557:   
1.227     brouard  7558: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7559:   
1.227     brouard  7560: /*   if (popforecast==1) { */
                   7561: /*     free_ivector(popage,0,AGESUP); */
                   7562: /*     free_vector(popeffectif,0,AGESUP); */
                   7563: /*     free_vector(popcount,0,AGESUP); */
                   7564: /*   } */
                   7565: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7566: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7567: /*   fclose(ficrespop); */
                   7568: /* } /\* End of popforecast *\/ */
1.218     brouard  7569:  
1.126     brouard  7570: int fileappend(FILE *fichier, char *optionfich)
                   7571: {
                   7572:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7573:     printf("Problem with file: %s\n", optionfich);
                   7574:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7575:     return (0);
                   7576:   }
                   7577:   fflush(fichier);
                   7578:   return (1);
                   7579: }
                   7580: 
                   7581: 
                   7582: /**************** function prwizard **********************/
                   7583: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7584: {
                   7585: 
                   7586:   /* Wizard to print covariance matrix template */
                   7587: 
1.164     brouard  7588:   char ca[32], cb[32];
                   7589:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7590:   int numlinepar;
                   7591: 
                   7592:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7593:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7594:   for(i=1; i <=nlstate; i++){
                   7595:     jj=0;
                   7596:     for(j=1; j <=nlstate+ndeath; j++){
                   7597:       if(j==i) continue;
                   7598:       jj++;
                   7599:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7600:       printf("%1d%1d",i,j);
                   7601:       fprintf(ficparo,"%1d%1d",i,j);
                   7602:       for(k=1; k<=ncovmodel;k++){
                   7603:        /*        printf(" %lf",param[i][j][k]); */
                   7604:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7605:        printf(" 0.");
                   7606:        fprintf(ficparo," 0.");
                   7607:       }
                   7608:       printf("\n");
                   7609:       fprintf(ficparo,"\n");
                   7610:     }
                   7611:   }
                   7612:   printf("# Scales (for hessian or gradient estimation)\n");
                   7613:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7614:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7615:   for(i=1; i <=nlstate; i++){
                   7616:     jj=0;
                   7617:     for(j=1; j <=nlstate+ndeath; j++){
                   7618:       if(j==i) continue;
                   7619:       jj++;
                   7620:       fprintf(ficparo,"%1d%1d",i,j);
                   7621:       printf("%1d%1d",i,j);
                   7622:       fflush(stdout);
                   7623:       for(k=1; k<=ncovmodel;k++){
                   7624:        /*      printf(" %le",delti3[i][j][k]); */
                   7625:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7626:        printf(" 0.");
                   7627:        fprintf(ficparo," 0.");
                   7628:       }
                   7629:       numlinepar++;
                   7630:       printf("\n");
                   7631:       fprintf(ficparo,"\n");
                   7632:     }
                   7633:   }
                   7634:   printf("# Covariance matrix\n");
                   7635: /* # 121 Var(a12)\n\ */
                   7636: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7637: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7638: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7639: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7640: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7641: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7642: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7643:   fflush(stdout);
                   7644:   fprintf(ficparo,"# Covariance matrix\n");
                   7645:   /* # 121 Var(a12)\n\ */
                   7646:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7647:   /* #   ...\n\ */
                   7648:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7649:   
                   7650:   for(itimes=1;itimes<=2;itimes++){
                   7651:     jj=0;
                   7652:     for(i=1; i <=nlstate; i++){
                   7653:       for(j=1; j <=nlstate+ndeath; j++){
                   7654:        if(j==i) continue;
                   7655:        for(k=1; k<=ncovmodel;k++){
                   7656:          jj++;
                   7657:          ca[0]= k+'a'-1;ca[1]='\0';
                   7658:          if(itimes==1){
                   7659:            printf("#%1d%1d%d",i,j,k);
                   7660:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7661:          }else{
                   7662:            printf("%1d%1d%d",i,j,k);
                   7663:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7664:            /*  printf(" %.5le",matcov[i][j]); */
                   7665:          }
                   7666:          ll=0;
                   7667:          for(li=1;li <=nlstate; li++){
                   7668:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7669:              if(lj==li) continue;
                   7670:              for(lk=1;lk<=ncovmodel;lk++){
                   7671:                ll++;
                   7672:                if(ll<=jj){
                   7673:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7674:                  if(ll<jj){
                   7675:                    if(itimes==1){
                   7676:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7677:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7678:                    }else{
                   7679:                      printf(" 0.");
                   7680:                      fprintf(ficparo," 0.");
                   7681:                    }
                   7682:                  }else{
                   7683:                    if(itimes==1){
                   7684:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7685:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7686:                    }else{
                   7687:                      printf(" 0.");
                   7688:                      fprintf(ficparo," 0.");
                   7689:                    }
                   7690:                  }
                   7691:                }
                   7692:              } /* end lk */
                   7693:            } /* end lj */
                   7694:          } /* end li */
                   7695:          printf("\n");
                   7696:          fprintf(ficparo,"\n");
                   7697:          numlinepar++;
                   7698:        } /* end k*/
                   7699:       } /*end j */
                   7700:     } /* end i */
                   7701:   } /* end itimes */
                   7702: 
                   7703: } /* end of prwizard */
                   7704: /******************* Gompertz Likelihood ******************************/
                   7705: double gompertz(double x[])
                   7706: { 
                   7707:   double A,B,L=0.0,sump=0.,num=0.;
                   7708:   int i,n=0; /* n is the size of the sample */
                   7709: 
1.220     brouard  7710:   for (i=1;i<=imx ; i++) {
1.126     brouard  7711:     sump=sump+weight[i];
                   7712:     /*    sump=sump+1;*/
                   7713:     num=num+1;
                   7714:   }
                   7715:  
                   7716:  
                   7717:   /* for (i=0; i<=imx; i++) 
                   7718:      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]);*/
                   7719: 
                   7720:   for (i=1;i<=imx ; i++)
                   7721:     {
                   7722:       if (cens[i] == 1 && wav[i]>1)
                   7723:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7724:       
                   7725:       if (cens[i] == 0 && wav[i]>1)
                   7726:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7727:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7728:       
                   7729:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7730:       if (wav[i] > 1 ) { /* ??? */
                   7731:        L=L+A*weight[i];
                   7732:        /*      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]);*/
                   7733:       }
                   7734:     }
                   7735: 
                   7736:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7737:  
                   7738:   return -2*L*num/sump;
                   7739: }
                   7740: 
1.136     brouard  7741: #ifdef GSL
                   7742: /******************* Gompertz_f Likelihood ******************************/
                   7743: double gompertz_f(const gsl_vector *v, void *params)
                   7744: { 
                   7745:   double A,B,LL=0.0,sump=0.,num=0.;
                   7746:   double *x= (double *) v->data;
                   7747:   int i,n=0; /* n is the size of the sample */
                   7748: 
                   7749:   for (i=0;i<=imx-1 ; i++) {
                   7750:     sump=sump+weight[i];
                   7751:     /*    sump=sump+1;*/
                   7752:     num=num+1;
                   7753:   }
                   7754:  
                   7755:  
                   7756:   /* for (i=0; i<=imx; i++) 
                   7757:      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]);*/
                   7758:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7759:   for (i=1;i<=imx ; i++)
                   7760:     {
                   7761:       if (cens[i] == 1 && wav[i]>1)
                   7762:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7763:       
                   7764:       if (cens[i] == 0 && wav[i]>1)
                   7765:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7766:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7767:       
                   7768:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7769:       if (wav[i] > 1 ) { /* ??? */
                   7770:        LL=LL+A*weight[i];
                   7771:        /*      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]);*/
                   7772:       }
                   7773:     }
                   7774: 
                   7775:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7776:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7777:  
                   7778:   return -2*LL*num/sump;
                   7779: }
                   7780: #endif
                   7781: 
1.126     brouard  7782: /******************* Printing html file ***********/
1.201     brouard  7783: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7784:                  int lastpass, int stepm, int weightopt, char model[],\
                   7785:                  int imx,  double p[],double **matcov,double agemortsup){
                   7786:   int i,k;
                   7787: 
                   7788:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7789:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7790:   for (i=1;i<=2;i++) 
                   7791:     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  7792:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7793:   fprintf(fichtm,"</ul>");
                   7794: 
                   7795: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7796: 
                   7797:  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>");
                   7798: 
                   7799:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7800:    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]);
                   7801: 
                   7802:  
                   7803:   fflush(fichtm);
                   7804: }
                   7805: 
                   7806: /******************* Gnuplot file **************/
1.201     brouard  7807: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7808: 
                   7809:   char dirfileres[132],optfileres[132];
1.164     brouard  7810: 
1.126     brouard  7811:   int ng;
                   7812: 
                   7813: 
                   7814:   /*#ifdef windows */
                   7815:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7816:     /*#endif */
                   7817: 
                   7818: 
                   7819:   strcpy(dirfileres,optionfilefiname);
                   7820:   strcpy(optfileres,"vpl");
1.199     brouard  7821:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7822:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7823:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7824:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7825:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7826: 
                   7827: } 
                   7828: 
1.136     brouard  7829: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7830: {
1.126     brouard  7831: 
1.136     brouard  7832:   /*-------- data file ----------*/
                   7833:   FILE *fic;
                   7834:   char dummy[]="                         ";
1.240   ! brouard  7835:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  7836:   int lstra;
1.136     brouard  7837:   int linei, month, year,iout;
                   7838:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7839:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7840:   char *stratrunc;
1.223     brouard  7841: 
1.240   ! brouard  7842:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
        !          7843:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  7844: 
1.240   ! brouard  7845:   for(v=1; v <=ncovcol;v++){
        !          7846:     DummyV[v]=0;
        !          7847:     FixedV[v]=0;
        !          7848:   }
        !          7849:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
        !          7850:     DummyV[v]=1;
        !          7851:     FixedV[v]=0;
        !          7852:   }
        !          7853:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
        !          7854:     DummyV[v]=0;
        !          7855:     FixedV[v]=1;
        !          7856:   }
        !          7857:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
        !          7858:     DummyV[v]=1;
        !          7859:     FixedV[v]=1;
        !          7860:   }
        !          7861:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
        !          7862:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
        !          7863:     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]);
        !          7864:   }
1.126     brouard  7865: 
1.136     brouard  7866:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7867:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7868:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7869:   }
1.126     brouard  7870: 
1.136     brouard  7871:   i=1;
                   7872:   linei=0;
                   7873:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7874:     linei=linei+1;
                   7875:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7876:       if(line[j] == '\t')
                   7877:        line[j] = ' ';
                   7878:     }
                   7879:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7880:       ;
                   7881:     };
                   7882:     line[j+1]=0;  /* Trims blanks at end of line */
                   7883:     if(line[0]=='#'){
                   7884:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7885:       printf("Comment line\n%s\n",line);
                   7886:       continue;
                   7887:     }
                   7888:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7889:     strcpy(line, linetmp);
1.223     brouard  7890:     
                   7891:     /* Loops on waves */
                   7892:     for (j=maxwav;j>=1;j--){
                   7893:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  7894:        cutv(stra, strb, line, ' '); 
                   7895:        if(strb[0]=='.') { /* Missing value */
                   7896:          lval=-1;
                   7897:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   7898:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   7899:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   7900:            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);
                   7901:            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);
                   7902:            return 1;
                   7903:          }
                   7904:        }else{
                   7905:          errno=0;
                   7906:          /* what_kind_of_number(strb); */
                   7907:          dval=strtod(strb,&endptr); 
                   7908:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7909:          /* if(strb != endptr && *endptr == '\0') */
                   7910:          /*    dval=dlval; */
                   7911:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7912:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7913:            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);
                   7914:            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);
                   7915:            return 1;
                   7916:          }
                   7917:          cotqvar[j][iv][i]=dval; 
                   7918:          cotvar[j][ntv+iv][i]=dval; 
                   7919:        }
                   7920:        strcpy(line,stra);
1.223     brouard  7921:       }/* end loop ntqv */
1.225     brouard  7922:       
1.223     brouard  7923:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  7924:        cutv(stra, strb, line, ' '); 
                   7925:        if(strb[0]=='.') { /* Missing value */
                   7926:          lval=-1;
                   7927:        }else{
                   7928:          errno=0;
                   7929:          lval=strtol(strb,&endptr,10); 
                   7930:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7931:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7932:            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);
                   7933:            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);
                   7934:            return 1;
                   7935:          }
                   7936:        }
                   7937:        if(lval <-1 || lval >1){
                   7938:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7939:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7940:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  7941:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7942:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7943:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  7944:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  7945:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  7946:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  7947:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7948:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7949:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  7950:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7951:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7952:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  7953:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  7954:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  7955:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  7956:          return 1;
                   7957:        }
                   7958:        cotvar[j][iv][i]=(double)(lval);
                   7959:        strcpy(line,stra);
1.223     brouard  7960:       }/* end loop ntv */
1.225     brouard  7961:       
1.223     brouard  7962:       /* Statuses  at wave */
1.137     brouard  7963:       cutv(stra, strb, line, ' '); 
1.223     brouard  7964:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  7965:        lval=-1;
1.136     brouard  7966:       }else{
1.238     brouard  7967:        errno=0;
                   7968:        lval=strtol(strb,&endptr,10); 
                   7969:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7970:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7971:          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);
                   7972:          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);
                   7973:          return 1;
                   7974:        }
1.136     brouard  7975:       }
1.225     brouard  7976:       
1.136     brouard  7977:       s[j][i]=lval;
1.225     brouard  7978:       
1.223     brouard  7979:       /* Date of Interview */
1.136     brouard  7980:       strcpy(line,stra);
                   7981:       cutv(stra, strb,line,' ');
1.169     brouard  7982:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7983:       }
1.169     brouard  7984:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  7985:        month=99;
                   7986:        year=9999;
1.136     brouard  7987:       }else{
1.225     brouard  7988:        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);
                   7989:        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);
                   7990:        return 1;
1.136     brouard  7991:       }
                   7992:       anint[j][i]= (double) year; 
                   7993:       mint[j][i]= (double)month; 
                   7994:       strcpy(line,stra);
1.223     brouard  7995:     } /* End loop on waves */
1.225     brouard  7996:     
1.223     brouard  7997:     /* Date of death */
1.136     brouard  7998:     cutv(stra, strb,line,' '); 
1.169     brouard  7999:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8000:     }
1.169     brouard  8001:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8002:       month=99;
                   8003:       year=9999;
                   8004:     }else{
1.141     brouard  8005:       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  8006:       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);
                   8007:       return 1;
1.136     brouard  8008:     }
                   8009:     andc[i]=(double) year; 
                   8010:     moisdc[i]=(double) month; 
                   8011:     strcpy(line,stra);
                   8012:     
1.223     brouard  8013:     /* Date of birth */
1.136     brouard  8014:     cutv(stra, strb,line,' '); 
1.169     brouard  8015:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8016:     }
1.169     brouard  8017:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8018:       month=99;
                   8019:       year=9999;
                   8020:     }else{
1.141     brouard  8021:       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);
                   8022:       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  8023:       return 1;
1.136     brouard  8024:     }
                   8025:     if (year==9999) {
1.141     brouard  8026:       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);
                   8027:       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  8028:       return 1;
                   8029:       
1.136     brouard  8030:     }
                   8031:     annais[i]=(double)(year);
                   8032:     moisnais[i]=(double)(month); 
                   8033:     strcpy(line,stra);
1.225     brouard  8034:     
1.223     brouard  8035:     /* Sample weight */
1.136     brouard  8036:     cutv(stra, strb,line,' '); 
                   8037:     errno=0;
                   8038:     dval=strtod(strb,&endptr); 
                   8039:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8040:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8041:       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  8042:       fflush(ficlog);
                   8043:       return 1;
                   8044:     }
                   8045:     weight[i]=dval; 
                   8046:     strcpy(line,stra);
1.225     brouard  8047:     
1.223     brouard  8048:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8049:       cutv(stra, strb, line, ' '); 
                   8050:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8051:        lval=-1;
1.223     brouard  8052:       }else{
1.225     brouard  8053:        errno=0;
                   8054:        /* what_kind_of_number(strb); */
                   8055:        dval=strtod(strb,&endptr);
                   8056:        /* if(strb != endptr && *endptr == '\0') */
                   8057:        /*   dval=dlval; */
                   8058:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8059:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8060:          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);
                   8061:          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);
                   8062:          return 1;
                   8063:        }
                   8064:        coqvar[iv][i]=dval; 
1.226     brouard  8065:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8066:       }
                   8067:       strcpy(line,stra);
                   8068:     }/* end loop nqv */
1.136     brouard  8069:     
1.223     brouard  8070:     /* Covariate values */
1.136     brouard  8071:     for (j=ncovcol;j>=1;j--){
                   8072:       cutv(stra, strb,line,' '); 
1.223     brouard  8073:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8074:        lval=-1;
1.136     brouard  8075:       }else{
1.225     brouard  8076:        errno=0;
                   8077:        lval=strtol(strb,&endptr,10); 
                   8078:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8079:          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);
                   8080:          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);
                   8081:          return 1;
                   8082:        }
1.136     brouard  8083:       }
                   8084:       if(lval <-1 || lval >1){
1.225     brouard  8085:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8086:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8087:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8088:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8089:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8090:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8091:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8092:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8093:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8094:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8095:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8096:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8097:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8098:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8099:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8100:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8101:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8102:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8103:        return 1;
1.136     brouard  8104:       }
                   8105:       covar[j][i]=(double)(lval);
                   8106:       strcpy(line,stra);
                   8107:     }  
                   8108:     lstra=strlen(stra);
1.225     brouard  8109:     
1.136     brouard  8110:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8111:       stratrunc = &(stra[lstra-9]);
                   8112:       num[i]=atol(stratrunc);
                   8113:     }
                   8114:     else
                   8115:       num[i]=atol(stra);
                   8116:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8117:       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;}*/
                   8118:     
                   8119:     i=i+1;
                   8120:   } /* End loop reading  data */
1.225     brouard  8121:   
1.136     brouard  8122:   *imax=i-1; /* Number of individuals */
                   8123:   fclose(fic);
1.225     brouard  8124:   
1.136     brouard  8125:   return (0);
1.164     brouard  8126:   /* endread: */
1.225     brouard  8127:   printf("Exiting readdata: ");
                   8128:   fclose(fic);
                   8129:   return (1);
1.223     brouard  8130: }
1.126     brouard  8131: 
1.234     brouard  8132: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8133:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8134:   while (*p2 == ' ')
1.234     brouard  8135:     p2++; 
                   8136:   /* while ((*p1++ = *p2++) !=0) */
                   8137:   /*   ; */
                   8138:   /* do */
                   8139:   /*   while (*p2 == ' ') */
                   8140:   /*     p2++; */
                   8141:   /* while (*p1++ == *p2++); */
                   8142:   *stri=p2; 
1.145     brouard  8143: }
                   8144: 
1.235     brouard  8145: int decoderesult ( char resultline[], int nres)
1.230     brouard  8146: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8147: {
1.235     brouard  8148:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8149:   char resultsav[MAXLINE];
1.234     brouard  8150:   int resultmodel[MAXLINE];
                   8151:   int modelresult[MAXLINE];
1.230     brouard  8152:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8153: 
1.234     brouard  8154:   removefirstspace(&resultline);
1.233     brouard  8155:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8156: 
                   8157:   if (strstr(resultline,"v") !=0){
                   8158:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8159:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8160:     return 1;
                   8161:   }
                   8162:   trimbb(resultsav, resultline);
                   8163:   if (strlen(resultsav) >1){
                   8164:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8165:   }
1.234     brouard  8166:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8167:     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);
                   8168:     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);
                   8169:   }
                   8170:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8171:     if(nbocc(resultsav,'=') >1){
                   8172:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8173:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8174:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8175:     }else
                   8176:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8177:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8178:     
1.230     brouard  8179:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8180:     Tvarsel[k]=atoi(strc);
                   8181:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8182:     /* cptcovsel++;     */
                   8183:     if (nbocc(stra,'=') >0)
                   8184:       strcpy(resultsav,stra); /* and analyzes it */
                   8185:   }
1.235     brouard  8186:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8187:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8188:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8189:       match=0;
1.236     brouard  8190:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8191:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8192:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8193:          match=1;
                   8194:          break;
                   8195:        }
                   8196:       }
                   8197:       if(match == 0){
                   8198:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8199:       }
                   8200:     }
                   8201:   }
1.235     brouard  8202:   /* Checking for missing or useless values in comparison of current model needs */
                   8203:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8204:     match=0;
1.235     brouard  8205:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8206:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8207:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8208:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8209:          ++match;
                   8210:        }
                   8211:       }
                   8212:     }
                   8213:     if(match == 0){
                   8214:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8215:     }else if(match > 1){
                   8216:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8217:     }
                   8218:   }
1.235     brouard  8219:       
1.234     brouard  8220:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8221:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8222:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8223:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8224:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8225:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8226:   /*    1 0 0 0 */
                   8227:   /*    2 1 0 0 */
                   8228:   /*    3 0 1 0 */ 
                   8229:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8230:   /*    5 0 0 1 */
                   8231:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8232:   /*    7 0 1 1 */
                   8233:   /*    8 1 1 1 */
1.237     brouard  8234:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8235:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8236:   /* V5*age V5 known which value for nres?  */
                   8237:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8238:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8239:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8240:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8241:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8242:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8243:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8244:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8245:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8246:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8247:       k4++;;
                   8248:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8249:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8250:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8251:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8252:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8253:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8254:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8255:       k4q++;;
                   8256:     }
                   8257:   }
1.234     brouard  8258:   
1.235     brouard  8259:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8260:   return (0);
                   8261: }
1.235     brouard  8262: 
1.230     brouard  8263: int decodemodel( char model[], int lastobs)
                   8264:  /**< This routine decodes the model and returns:
1.224     brouard  8265:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8266:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8267:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8268:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8269:        * - cptcovage number of covariates with age*products =2
                   8270:        * - cptcovs number of simple covariates
                   8271:        * - 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
                   8272:        *     which is a new column after the 9 (ncovcol) variables. 
                   8273:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8274:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8275:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8276:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8277:        */
1.136     brouard  8278: {
1.238     brouard  8279:   int i, j, k, ks, v;
1.227     brouard  8280:   int  j1, k1, k2, k3, k4;
1.136     brouard  8281:   char modelsav[80];
1.145     brouard  8282:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8283:   char *strpt;
1.136     brouard  8284: 
1.145     brouard  8285:   /*removespace(model);*/
1.136     brouard  8286:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8287:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8288:     if (strstr(model,"AGE") !=0){
1.192     brouard  8289:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8290:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8291:       return 1;
                   8292:     }
1.141     brouard  8293:     if (strstr(model,"v") !=0){
                   8294:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8295:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8296:       return 1;
                   8297:     }
1.187     brouard  8298:     strcpy(modelsav,model); 
                   8299:     if ((strpt=strstr(model,"age*age")) !=0){
                   8300:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8301:       if(strpt != model){
1.234     brouard  8302:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8303:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8304:  corresponding column of parameters.\n",model);
1.234     brouard  8305:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8306:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8307:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8308:        return 1;
1.225     brouard  8309:       }
1.187     brouard  8310:       nagesqr=1;
                   8311:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8312:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8313:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8314:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8315:       else 
1.234     brouard  8316:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8317:     }else
                   8318:       nagesqr=0;
                   8319:     if (strlen(modelsav) >1){
                   8320:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8321:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8322:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8323:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8324:                     * cst, age and age*age 
                   8325:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8326:       /* including age products which are counted in cptcovage.
                   8327:        * but the covariates which are products must be treated 
                   8328:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8329:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8330:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8331:       
                   8332:       
1.187     brouard  8333:       /*   Design
                   8334:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8335:        *  <          ncovcol=8                >
                   8336:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8337:        *   k=  1    2      3       4     5       6      7        8
                   8338:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8339:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8340:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8341:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8342:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8343:        *  Tage[++cptcovage]=k
                   8344:        *       if products, new covar are created after ncovcol with k1
                   8345:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8346:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8347:        *  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
                   8348:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8349:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8350:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8351:        *  <          ncovcol=8                >
                   8352:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8353:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8354:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8355:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8356:        * p Tprod[1]@2={                         6, 5}
                   8357:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8358:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8359:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8360:        *How to reorganize?
                   8361:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8362:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8363:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8364:        * Struct []
                   8365:        */
1.225     brouard  8366:       
1.187     brouard  8367:       /* This loop fills the array Tvar from the string 'model'.*/
                   8368:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8369:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8370:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8371:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8372:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8373:       /*       k=1 Tvar[1]=2 (from V2) */
                   8374:       /*       k=5 Tvar[5] */
                   8375:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8376:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8377:       /*       } */
1.198     brouard  8378:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8379:       /*
                   8380:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8381:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8382:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8383:       }
1.187     brouard  8384:       cptcovage=0;
                   8385:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8386:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8387:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8388:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8389:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8390:        /*scanf("%d",i);*/
                   8391:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8392:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8393:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8394:            /* covar is not filled and then is empty */
                   8395:            cptcovprod--;
                   8396:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8397:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8398:            Typevar[k]=1;  /* 1 for age product */
                   8399:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8400:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8401:            /*printf("stre=%s ", stre);*/
                   8402:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8403:            cptcovprod--;
                   8404:            cutl(stre,strb,strc,'V');
                   8405:            Tvar[k]=atoi(stre);
                   8406:            Typevar[k]=1;  /* 1 for age product */
                   8407:            cptcovage++;
                   8408:            Tage[cptcovage]=k;
                   8409:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8410:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8411:            cptcovn++;
                   8412:            cptcovprodnoage++;k1++;
                   8413:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8414:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8415:                                                because this model-covariate is a construction we invent a new column
                   8416:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8417:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8418:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8419:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8420:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8421:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8422:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8423:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8424:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8425:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8426:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8427:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8428:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8429:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8430:            for (i=1; i<=lastobs;i++){
                   8431:              /* Computes the new covariate which is a product of
                   8432:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8433:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8434:            }
                   8435:          } /* End age is not in the model */
                   8436:        } /* End if model includes a product */
                   8437:        else { /* no more sum */
                   8438:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8439:          /*  scanf("%d",i);*/
                   8440:          cutl(strd,strc,strb,'V');
                   8441:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8442:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8443:          Tvar[k]=atoi(strd);
                   8444:          Typevar[k]=0;  /* 0 for simple covariates */
                   8445:        }
                   8446:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8447:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8448:                                  scanf("%d",i);*/
1.187     brouard  8449:       } /* end of loop + on total covariates */
                   8450:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8451:   } /* end if strlen(model == 0) */
1.136     brouard  8452:   
                   8453:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8454:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8455:   
1.136     brouard  8456:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8457:      printf("cptcovprod=%d ", cptcovprod);
                   8458:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8459:      scanf("%d ",i);*/
                   8460: 
                   8461: 
1.230     brouard  8462: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8463:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8464: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8465:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8466:    k =           1    2   3     4       5       6      7      8        9
                   8467:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8468:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8469:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8470:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8471:          Tmodelind[combination of covar]=k;
1.225     brouard  8472: */  
                   8473: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8474:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8475:   /* 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  8476:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8477:   printf("Model=%s\n\
                   8478: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8479: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8480: 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);
                   8481:   fprintf(ficlog,"Model=%s\n\
                   8482: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8483: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8484: 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  8485:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8486:   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 */
                   8487:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8488:       Fixed[k]= 0;
                   8489:       Dummy[k]= 0;
1.225     brouard  8490:       ncoveff++;
1.232     brouard  8491:       ncovf++;
1.234     brouard  8492:       nsd++;
                   8493:       modell[k].maintype= FTYPE;
                   8494:       TvarsD[nsd]=Tvar[k];
                   8495:       TvarsDind[nsd]=k;
                   8496:       TvarF[ncovf]=Tvar[k];
                   8497:       TvarFind[ncovf]=k;
                   8498:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8499:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8500:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8501:       Fixed[k]= 0;
                   8502:       Dummy[k]= 0;
                   8503:       ncoveff++;
                   8504:       ncovf++;
                   8505:       modell[k].maintype= FTYPE;
                   8506:       TvarF[ncovf]=Tvar[k];
                   8507:       TvarFind[ncovf]=k;
1.230     brouard  8508:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8509:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240   ! brouard  8510:     }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  8511:       Fixed[k]= 0;
                   8512:       Dummy[k]= 1;
1.230     brouard  8513:       nqfveff++;
1.234     brouard  8514:       modell[k].maintype= FTYPE;
                   8515:       modell[k].subtype= FQ;
                   8516:       nsq++;
                   8517:       TvarsQ[nsq]=Tvar[k];
                   8518:       TvarsQind[nsq]=k;
1.232     brouard  8519:       ncovf++;
1.234     brouard  8520:       TvarF[ncovf]=Tvar[k];
                   8521:       TvarFind[ncovf]=k;
1.231     brouard  8522:       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  8523:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.234     brouard  8524:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying variables */
1.227     brouard  8525:       Fixed[k]= 1;
                   8526:       Dummy[k]= 0;
1.225     brouard  8527:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8528:       modell[k].maintype= VTYPE;
                   8529:       modell[k].subtype= VD;
                   8530:       nsd++;
                   8531:       TvarsD[nsd]=Tvar[k];
                   8532:       TvarsDind[nsd]=k;
                   8533:       ncovv++; /* Only simple time varying variables */
                   8534:       TvarV[ncovv]=Tvar[k];
                   8535:       TvarVind[ncovv]=k;
1.231     brouard  8536:       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 */
                   8537:       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  8538:       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);
                   8539:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8540:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8541:       Fixed[k]= 1;
                   8542:       Dummy[k]= 1;
                   8543:       nqtveff++;
                   8544:       modell[k].maintype= VTYPE;
                   8545:       modell[k].subtype= VQ;
                   8546:       ncovv++; /* Only simple time varying variables */
                   8547:       nsq++;
                   8548:       TvarsQ[nsq]=Tvar[k];
                   8549:       TvarsQind[nsq]=k;
                   8550:       TvarV[ncovv]=Tvar[k];
                   8551:       TvarVind[ncovv]=k;
1.231     brouard  8552:       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 */
                   8553:       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  8554:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8555:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8556:       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  8557:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8558:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8559:       ncova++;
                   8560:       TvarA[ncova]=Tvar[k];
                   8561:       TvarAind[ncova]=k;
1.231     brouard  8562:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240   ! brouard  8563:        Fixed[k]= 2;
        !          8564:        Dummy[k]= 2;
        !          8565:        modell[k].maintype= ATYPE;
        !          8566:        modell[k].subtype= APFD;
        !          8567:        /* ncoveff++; */
1.227     brouard  8568:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240   ! brouard  8569:        Fixed[k]= 2;
        !          8570:        Dummy[k]= 3;
        !          8571:        modell[k].maintype= ATYPE;
        !          8572:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
        !          8573:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8574:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240   ! brouard  8575:        Fixed[k]= 3;
        !          8576:        Dummy[k]= 2;
        !          8577:        modell[k].maintype= ATYPE;
        !          8578:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
        !          8579:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8580:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240   ! brouard  8581:        Fixed[k]= 3;
        !          8582:        Dummy[k]= 3;
        !          8583:        modell[k].maintype= ATYPE;
        !          8584:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
        !          8585:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8586:       }
                   8587:     }else if (Typevar[k] == 2) {  /* product without age */
                   8588:       k1=Tposprod[k];
                   8589:       if(Tvard[k1][1] <=ncovcol){
1.240   ! brouard  8590:        if(Tvard[k1][2] <=ncovcol){
        !          8591:          Fixed[k]= 1;
        !          8592:          Dummy[k]= 0;
        !          8593:          modell[k].maintype= FTYPE;
        !          8594:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
        !          8595:          ncovf++; /* Fixed variables without age */
        !          8596:          TvarF[ncovf]=Tvar[k];
        !          8597:          TvarFind[ncovf]=k;
        !          8598:        }else if(Tvard[k1][2] <=ncovcol+nqv){
        !          8599:          Fixed[k]= 0;  /* or 2 ?*/
        !          8600:          Dummy[k]= 1;
        !          8601:          modell[k].maintype= FTYPE;
        !          8602:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
        !          8603:          ncovf++; /* Varying variables without age */
        !          8604:          TvarF[ncovf]=Tvar[k];
        !          8605:          TvarFind[ncovf]=k;
        !          8606:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
        !          8607:          Fixed[k]= 1;
        !          8608:          Dummy[k]= 0;
        !          8609:          modell[k].maintype= VTYPE;
        !          8610:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
        !          8611:          ncovv++; /* Varying variables without age */
        !          8612:          TvarV[ncovv]=Tvar[k];
        !          8613:          TvarVind[ncovv]=k;
        !          8614:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
        !          8615:          Fixed[k]= 1;
        !          8616:          Dummy[k]= 1;
        !          8617:          modell[k].maintype= VTYPE;
        !          8618:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
        !          8619:          ncovv++; /* Varying variables without age */
        !          8620:          TvarV[ncovv]=Tvar[k];
        !          8621:          TvarVind[ncovv]=k;
        !          8622:        }
1.227     brouard  8623:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240   ! brouard  8624:        if(Tvard[k1][2] <=ncovcol){
        !          8625:          Fixed[k]= 0;  /* or 2 ?*/
        !          8626:          Dummy[k]= 1;
        !          8627:          modell[k].maintype= FTYPE;
        !          8628:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
        !          8629:          ncovf++; /* Fixed variables without age */
        !          8630:          TvarF[ncovf]=Tvar[k];
        !          8631:          TvarFind[ncovf]=k;
        !          8632:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
        !          8633:          Fixed[k]= 1;
        !          8634:          Dummy[k]= 1;
        !          8635:          modell[k].maintype= VTYPE;
        !          8636:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
        !          8637:          ncovv++; /* Varying variables without age */
        !          8638:          TvarV[ncovv]=Tvar[k];
        !          8639:          TvarVind[ncovv]=k;
        !          8640:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
        !          8641:          Fixed[k]= 1;
        !          8642:          Dummy[k]= 1;
        !          8643:          modell[k].maintype= VTYPE;
        !          8644:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
        !          8645:          ncovv++; /* Varying variables without age */
        !          8646:          TvarV[ncovv]=Tvar[k];
        !          8647:          TvarVind[ncovv]=k;
        !          8648:          ncovv++; /* Varying variables without age */
        !          8649:          TvarV[ncovv]=Tvar[k];
        !          8650:          TvarVind[ncovv]=k;
        !          8651:        }
1.227     brouard  8652:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240   ! brouard  8653:        if(Tvard[k1][2] <=ncovcol){
        !          8654:          Fixed[k]= 1;
        !          8655:          Dummy[k]= 1;
        !          8656:          modell[k].maintype= VTYPE;
        !          8657:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
        !          8658:          ncovv++; /* Varying variables without age */
        !          8659:          TvarV[ncovv]=Tvar[k];
        !          8660:          TvarVind[ncovv]=k;
        !          8661:        }else if(Tvard[k1][2] <=ncovcol+nqv){
        !          8662:          Fixed[k]= 1;
        !          8663:          Dummy[k]= 1;
        !          8664:          modell[k].maintype= VTYPE;
        !          8665:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
        !          8666:          ncovv++; /* Varying variables without age */
        !          8667:          TvarV[ncovv]=Tvar[k];
        !          8668:          TvarVind[ncovv]=k;
        !          8669:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
        !          8670:          Fixed[k]= 1;
        !          8671:          Dummy[k]= 0;
        !          8672:          modell[k].maintype= VTYPE;
        !          8673:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
        !          8674:          ncovv++; /* Varying variables without age */
        !          8675:          TvarV[ncovv]=Tvar[k];
        !          8676:          TvarVind[ncovv]=k;
        !          8677:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
        !          8678:          Fixed[k]= 1;
        !          8679:          Dummy[k]= 1;
        !          8680:          modell[k].maintype= VTYPE;
        !          8681:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
        !          8682:          ncovv++; /* Varying variables without age */
        !          8683:          TvarV[ncovv]=Tvar[k];
        !          8684:          TvarVind[ncovv]=k;
        !          8685:        }
1.227     brouard  8686:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240   ! brouard  8687:        if(Tvard[k1][2] <=ncovcol){
        !          8688:          Fixed[k]= 1;
        !          8689:          Dummy[k]= 1;
        !          8690:          modell[k].maintype= VTYPE;
        !          8691:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
        !          8692:          ncovv++; /* Varying variables without age */
        !          8693:          TvarV[ncovv]=Tvar[k];
        !          8694:          TvarVind[ncovv]=k;
        !          8695:        }else if(Tvard[k1][2] <=ncovcol+nqv){
        !          8696:          Fixed[k]= 1;
        !          8697:          Dummy[k]= 1;
        !          8698:          modell[k].maintype= VTYPE;
        !          8699:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
        !          8700:          ncovv++; /* Varying variables without age */
        !          8701:          TvarV[ncovv]=Tvar[k];
        !          8702:          TvarVind[ncovv]=k;
        !          8703:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
        !          8704:          Fixed[k]= 1;
        !          8705:          Dummy[k]= 1;
        !          8706:          modell[k].maintype= VTYPE;
        !          8707:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
        !          8708:          ncovv++; /* Varying variables without age */
        !          8709:          TvarV[ncovv]=Tvar[k];
        !          8710:          TvarVind[ncovv]=k;
        !          8711:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
        !          8712:          Fixed[k]= 1;
        !          8713:          Dummy[k]= 1;
        !          8714:          modell[k].maintype= VTYPE;
        !          8715:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
        !          8716:          ncovv++; /* Varying variables without age */
        !          8717:          TvarV[ncovv]=Tvar[k];
        !          8718:          TvarVind[ncovv]=k;
        !          8719:        }
1.227     brouard  8720:       }else{
1.240   ! brouard  8721:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
        !          8722:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
        !          8723:       } /*end k1*/
1.225     brouard  8724:     }else{
1.226     brouard  8725:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8726:       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  8727:     }
1.227     brouard  8728:     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  8729:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8730:     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]);
                   8731:   }
                   8732:   /* Searching for doublons in the model */
                   8733:   for(k1=1; k1<= cptcovt;k1++){
                   8734:     for(k2=1; k2 <k1;k2++){
                   8735:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8736:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8737:          if(Tvar[k1]==Tvar[k2]){
                   8738:            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]]);
                   8739:            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);
                   8740:            return(1);
                   8741:          }
                   8742:        }else if (Typevar[k1] ==2){
                   8743:          k3=Tposprod[k1];
                   8744:          k4=Tposprod[k2];
                   8745:          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])) ){
                   8746:            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]]);
                   8747:            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);
                   8748:            return(1);
                   8749:          }
                   8750:        }
1.227     brouard  8751:       }
                   8752:     }
1.225     brouard  8753:   }
                   8754:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8755:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8756:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8757:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8758:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8759:   /*endread:*/
1.225     brouard  8760:   printf("Exiting decodemodel: ");
                   8761:   return (1);
1.136     brouard  8762: }
                   8763: 
1.169     brouard  8764: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8765: {
                   8766:   int i, m;
1.218     brouard  8767:   int firstone=0;
                   8768:   
1.136     brouard  8769:   for (i=1; i<=imx; i++) {
                   8770:     for(m=2; (m<= maxwav); m++) {
                   8771:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8772:        anint[m][i]=9999;
1.216     brouard  8773:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8774:          s[m][i]=-1;
1.136     brouard  8775:       }
                   8776:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8777:        *nberr = *nberr + 1;
1.218     brouard  8778:        if(firstone == 0){
                   8779:          firstone=1;
                   8780:        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);
                   8781:        }
                   8782:        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  8783:        s[m][i]=-1;
                   8784:       }
                   8785:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8786:        (*nberr)++;
1.136     brouard  8787:        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]); 
                   8788:        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]); 
                   8789:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8790:       }
                   8791:     }
                   8792:   }
                   8793: 
                   8794:   for (i=1; i<=imx; i++)  {
                   8795:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8796:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8797:       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  8798:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8799:          if(agedc[i]>0){
                   8800:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8801:              agev[m][i]=agedc[i];
1.214     brouard  8802:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8803:            }else {
1.136     brouard  8804:              if ((int)andc[i]!=9999){
                   8805:                nbwarn++;
                   8806:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8807:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8808:                agev[m][i]=-1;
                   8809:              }
                   8810:            }
1.169     brouard  8811:          } /* agedc > 0 */
1.214     brouard  8812:        } /* end if */
1.136     brouard  8813:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8814:                                 years but with the precision of a month */
                   8815:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8816:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8817:            agev[m][i]=1;
                   8818:          else if(agev[m][i] < *agemin){ 
                   8819:            *agemin=agev[m][i];
                   8820:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8821:          }
                   8822:          else if(agev[m][i] >*agemax){
                   8823:            *agemax=agev[m][i];
1.156     brouard  8824:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8825:          }
                   8826:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8827:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8828:        } /* en if 9*/
1.136     brouard  8829:        else { /* =9 */
1.214     brouard  8830:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8831:          agev[m][i]=1;
                   8832:          s[m][i]=-1;
                   8833:        }
                   8834:       }
1.214     brouard  8835:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8836:        agev[m][i]=1;
1.214     brouard  8837:       else{
                   8838:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8839:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8840:        agev[m][i]=0;
                   8841:       }
                   8842:     } /* End for lastpass */
                   8843:   }
1.136     brouard  8844:     
                   8845:   for (i=1; i<=imx; i++)  {
                   8846:     for(m=firstpass; (m<=lastpass); m++){
                   8847:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8848:        (*nberr)++;
1.136     brouard  8849:        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);     
                   8850:        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);     
                   8851:        return 1;
                   8852:       }
                   8853:     }
                   8854:   }
                   8855: 
                   8856:   /*for (i=1; i<=imx; i++){
                   8857:   for (m=firstpass; (m<lastpass); m++){
                   8858:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8859: }
                   8860: 
                   8861: }*/
                   8862: 
                   8863: 
1.139     brouard  8864:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8865:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8866: 
                   8867:   return (0);
1.164     brouard  8868:  /* endread:*/
1.136     brouard  8869:     printf("Exiting calandcheckages: ");
                   8870:     return (1);
                   8871: }
                   8872: 
1.172     brouard  8873: #if defined(_MSC_VER)
                   8874: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8875: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8876: //#include "stdafx.h"
                   8877: //#include <stdio.h>
                   8878: //#include <tchar.h>
                   8879: //#include <windows.h>
                   8880: //#include <iostream>
                   8881: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8882: 
                   8883: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8884: 
                   8885: BOOL IsWow64()
                   8886: {
                   8887:        BOOL bIsWow64 = FALSE;
                   8888: 
                   8889:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8890:        //  (HANDLE, PBOOL);
                   8891: 
                   8892:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8893: 
                   8894:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8895:        const char funcName[] = "IsWow64Process";
                   8896:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8897:                GetProcAddress(module, funcName);
                   8898: 
                   8899:        if (NULL != fnIsWow64Process)
                   8900:        {
                   8901:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8902:                        &bIsWow64))
                   8903:                        //throw std::exception("Unknown error");
                   8904:                        printf("Unknown error\n");
                   8905:        }
                   8906:        return bIsWow64 != FALSE;
                   8907: }
                   8908: #endif
1.177     brouard  8909: 
1.191     brouard  8910: void syscompilerinfo(int logged)
1.167     brouard  8911:  {
                   8912:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8913:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8914:    /* /GS /W3 /Gy
                   8915:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8916:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8917:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8918:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8919:    */ 
                   8920:    /* 64 bits */
1.185     brouard  8921:    /*
                   8922:      /GS /W3 /Gy
                   8923:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8924:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8925:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8926:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8927:    /* Optimization are useless and O3 is slower than O2 */
                   8928:    /*
                   8929:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8930:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8931:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8932:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8933:    */
1.186     brouard  8934:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8935:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8936:       /PDB:"visual studio
                   8937:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8938:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8939:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8940:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   8941:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   8942:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   8943:       uiAccess='false'"
                   8944:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   8945:       /NOLOGO /TLBID:1
                   8946:    */
1.177     brouard  8947: #if defined __INTEL_COMPILER
1.178     brouard  8948: #if defined(__GNUC__)
                   8949:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   8950: #endif
1.177     brouard  8951: #elif defined(__GNUC__) 
1.179     brouard  8952: #ifndef  __APPLE__
1.174     brouard  8953: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  8954: #endif
1.177     brouard  8955:    struct utsname sysInfo;
1.178     brouard  8956:    int cross = CROSS;
                   8957:    if (cross){
                   8958:           printf("Cross-");
1.191     brouard  8959:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  8960:    }
1.174     brouard  8961: #endif
                   8962: 
1.171     brouard  8963: #include <stdint.h>
1.178     brouard  8964: 
1.191     brouard  8965:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  8966: #if defined(__clang__)
1.191     brouard  8967:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  8968: #endif
                   8969: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  8970:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  8971: #endif
                   8972: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  8973:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  8974: #endif
                   8975: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  8976:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  8977: #endif
                   8978: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  8979:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  8980: #endif
                   8981: #if defined(_MSC_VER)
1.191     brouard  8982:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  8983: #endif
                   8984: #if defined(__PGI)
1.191     brouard  8985:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  8986: #endif
                   8987: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  8988:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  8989: #endif
1.191     brouard  8990:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  8991:    
1.167     brouard  8992: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   8993: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   8994:     // Windows (x64 and x86)
1.191     brouard  8995:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  8996: #elif __unix__ // all unices, not all compilers
                   8997:     // Unix
1.191     brouard  8998:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  8999: #elif __linux__
                   9000:     // linux
1.191     brouard  9001:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9002: #elif __APPLE__
1.174     brouard  9003:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9004:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9005: #endif
                   9006: 
                   9007: /*  __MINGW32__          */
                   9008: /*  __CYGWIN__  */
                   9009: /* __MINGW64__  */
                   9010: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9011: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9012: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9013: /* _WIN64  // Defined for applications for Win64. */
                   9014: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9015: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9016: 
1.167     brouard  9017: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9018:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9019: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9020:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9021: #else
1.191     brouard  9022:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9023: #endif
                   9024: 
1.169     brouard  9025: #if defined(__GNUC__)
                   9026: # if defined(__GNUC_PATCHLEVEL__)
                   9027: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9028:                             + __GNUC_MINOR__ * 100 \
                   9029:                             + __GNUC_PATCHLEVEL__)
                   9030: # else
                   9031: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9032:                             + __GNUC_MINOR__ * 100)
                   9033: # endif
1.174     brouard  9034:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9035:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9036: 
                   9037:    if (uname(&sysInfo) != -1) {
                   9038:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9039:         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  9040:    }
                   9041:    else
                   9042:       perror("uname() error");
1.179     brouard  9043:    //#ifndef __INTEL_COMPILER 
                   9044: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9045:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9046:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9047: #endif
1.169     brouard  9048: #endif
1.172     brouard  9049: 
                   9050:    //   void main()
                   9051:    //   {
1.169     brouard  9052: #if defined(_MSC_VER)
1.174     brouard  9053:    if (IsWow64()){
1.191     brouard  9054:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9055:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9056:    }
                   9057:    else{
1.191     brouard  9058:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9059:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9060:    }
1.172     brouard  9061:    //     printf("\nPress Enter to continue...");
                   9062:    //     getchar();
                   9063:    //   }
                   9064: 
1.169     brouard  9065: #endif
                   9066:    
1.167     brouard  9067: 
1.219     brouard  9068: }
1.136     brouard  9069: 
1.219     brouard  9070: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9071:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9072:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9073:   /* double ftolpl = 1.e-10; */
1.180     brouard  9074:   double age, agebase, agelim;
1.203     brouard  9075:   double tot;
1.180     brouard  9076: 
1.202     brouard  9077:   strcpy(filerespl,"PL_");
                   9078:   strcat(filerespl,fileresu);
                   9079:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9080:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9081:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9082:   }
1.227     brouard  9083:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9084:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9085:   pstamp(ficrespl);
1.203     brouard  9086:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9087:   fprintf(ficrespl,"#Age ");
                   9088:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9089:   fprintf(ficrespl,"\n");
1.180     brouard  9090:   
1.219     brouard  9091:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9092: 
1.219     brouard  9093:   agebase=ageminpar;
                   9094:   agelim=agemaxpar;
1.180     brouard  9095: 
1.227     brouard  9096:   /* i1=pow(2,ncoveff); */
1.234     brouard  9097:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9098:   if (cptcovn < 1){i1=1;}
1.180     brouard  9099: 
1.238     brouard  9100:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9101:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9102:       if(TKresult[nres]!= k)
                   9103:        continue;
1.235     brouard  9104: 
1.238     brouard  9105:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9106:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9107:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9108:       /* k=k+1; */
                   9109:       /* to clean */
                   9110:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9111:       fprintf(ficrespl,"#******");
                   9112:       printf("#******");
                   9113:       fprintf(ficlog,"#******");
                   9114:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9115:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9116:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9117:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9118:       }
                   9119:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9120:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9121:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9122:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9123:       }
                   9124:       fprintf(ficrespl,"******\n");
                   9125:       printf("******\n");
                   9126:       fprintf(ficlog,"******\n");
                   9127:       if(invalidvarcomb[k]){
                   9128:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9129:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9130:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9131:        continue;
                   9132:       }
1.219     brouard  9133: 
1.238     brouard  9134:       fprintf(ficrespl,"#Age ");
                   9135:       for(j=1;j<=cptcoveff;j++) {
                   9136:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9137:       }
                   9138:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9139:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9140:     
1.238     brouard  9141:       for (age=agebase; age<=agelim; age++){
                   9142:        /* for (age=agebase; age<=agebase; age++){ */
                   9143:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9144:        fprintf(ficrespl,"%.0f ",age );
                   9145:        for(j=1;j<=cptcoveff;j++)
                   9146:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9147:        tot=0.;
                   9148:        for(i=1; i<=nlstate;i++){
                   9149:          tot +=  prlim[i][i];
                   9150:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9151:        }
                   9152:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9153:       } /* Age */
                   9154:       /* was end of cptcod */
                   9155:     } /* cptcov */
                   9156:   } /* nres */
1.219     brouard  9157:   return 0;
1.180     brouard  9158: }
                   9159: 
1.218     brouard  9160: 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){
                   9161:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9162:        
                   9163:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9164:    * at any age between ageminpar and agemaxpar
                   9165:         */
1.235     brouard  9166:   int i, j, k, i1, nres=0 ;
1.217     brouard  9167:   /* double ftolpl = 1.e-10; */
                   9168:   double age, agebase, agelim;
                   9169:   double tot;
1.218     brouard  9170:   /* double ***mobaverage; */
                   9171:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9172: 
                   9173:   strcpy(fileresplb,"PLB_");
                   9174:   strcat(fileresplb,fileresu);
                   9175:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9176:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9177:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9178:   }
                   9179:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9180:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9181:   pstamp(ficresplb);
                   9182:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9183:   fprintf(ficresplb,"#Age ");
                   9184:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9185:   fprintf(ficresplb,"\n");
                   9186:   
1.218     brouard  9187:   
                   9188:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9189:   
                   9190:   agebase=ageminpar;
                   9191:   agelim=agemaxpar;
                   9192:   
                   9193:   
1.227     brouard  9194:   i1=pow(2,cptcoveff);
1.218     brouard  9195:   if (cptcovn < 1){i1=1;}
1.227     brouard  9196:   
1.238     brouard  9197:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9198:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9199:       if(TKresult[nres]!= k)
                   9200:        continue;
                   9201:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9202:       fprintf(ficresplb,"#******");
                   9203:       printf("#******");
                   9204:       fprintf(ficlog,"#******");
                   9205:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9206:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9207:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9208:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9209:       }
                   9210:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9211:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9212:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9213:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9214:       }
                   9215:       fprintf(ficresplb,"******\n");
                   9216:       printf("******\n");
                   9217:       fprintf(ficlog,"******\n");
                   9218:       if(invalidvarcomb[k]){
                   9219:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9220:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9221:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9222:        continue;
                   9223:       }
1.218     brouard  9224:     
1.238     brouard  9225:       fprintf(ficresplb,"#Age ");
                   9226:       for(j=1;j<=cptcoveff;j++) {
                   9227:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9228:       }
                   9229:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9230:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9231:     
                   9232:     
1.238     brouard  9233:       for (age=agebase; age<=agelim; age++){
                   9234:        /* for (age=agebase; age<=agebase; age++){ */
                   9235:        if(mobilavproj > 0){
                   9236:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9237:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9238:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
                   9239:        }else if (mobilavproj == 0){
                   9240:          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);
                   9241:          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);
                   9242:          exit(1);
                   9243:        }else{
                   9244:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9245:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
                   9246:        }
                   9247:        fprintf(ficresplb,"%.0f ",age );
                   9248:        for(j=1;j<=cptcoveff;j++)
                   9249:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9250:        tot=0.;
                   9251:        for(i=1; i<=nlstate;i++){
                   9252:          tot +=  bprlim[i][i];
                   9253:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9254:        }
                   9255:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9256:       } /* Age */
                   9257:       /* was end of cptcod */
                   9258:     } /* end of any combination */
                   9259:   } /* end of nres */  
1.218     brouard  9260:   /* hBijx(p, bage, fage); */
                   9261:   /* fclose(ficrespijb); */
                   9262:   
                   9263:   return 0;
1.217     brouard  9264: }
1.218     brouard  9265:  
1.180     brouard  9266: int hPijx(double *p, int bage, int fage){
                   9267:     /*------------- h Pij x at various ages ------------*/
                   9268: 
                   9269:   int stepsize;
                   9270:   int agelim;
                   9271:   int hstepm;
                   9272:   int nhstepm;
1.235     brouard  9273:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9274: 
                   9275:   double agedeb;
                   9276:   double ***p3mat;
                   9277: 
1.201     brouard  9278:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9279:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9280:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9281:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9282:     }
                   9283:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9284:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9285:   
                   9286:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9287:     /*if (stepm<=24) stepsize=2;*/
                   9288: 
                   9289:     agelim=AGESUP;
                   9290:     hstepm=stepsize*YEARM; /* Every year of age */
                   9291:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9292:                
1.180     brouard  9293:     /* hstepm=1;   aff par mois*/
                   9294:     pstamp(ficrespij);
                   9295:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9296:     i1= pow(2,cptcoveff);
1.218     brouard  9297:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9298:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9299:                /*      k=k+1;  */
1.235     brouard  9300:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9301:     for(k=1; k<=i1;k++){
                   9302:       if(TKresult[nres]!= k)
                   9303:        continue;
1.183     brouard  9304:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9305:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9306:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9307:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9308:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9309:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9310:       }
1.183     brouard  9311:       fprintf(ficrespij,"******\n");
                   9312:       
                   9313:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9314:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9315:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9316:        
                   9317:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9318:        
1.183     brouard  9319:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9320:        oldm=oldms;savm=savms;
1.235     brouard  9321:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9322:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9323:        for(i=1; i<=nlstate;i++)
                   9324:          for(j=1; j<=nlstate+ndeath;j++)
                   9325:            fprintf(ficrespij," %1d-%1d",i,j);
                   9326:        fprintf(ficrespij,"\n");
                   9327:        for (h=0; h<=nhstepm; h++){
                   9328:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9329:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9330:          for(i=1; i<=nlstate;i++)
                   9331:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9332:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9333:          fprintf(ficrespij,"\n");
                   9334:        }
1.183     brouard  9335:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9336:        fprintf(ficrespij,"\n");
                   9337:       }
1.180     brouard  9338:       /*}*/
                   9339:     }
1.218     brouard  9340:     return 0;
1.180     brouard  9341: }
1.218     brouard  9342:  
                   9343:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9344:     /*------------- h Bij x at various ages ------------*/
                   9345: 
                   9346:   int stepsize;
1.218     brouard  9347:   /* int agelim; */
                   9348:        int ageminl;
1.217     brouard  9349:   int hstepm;
                   9350:   int nhstepm;
1.238     brouard  9351:   int h, i, i1, j, k, nres;
1.218     brouard  9352:        
1.217     brouard  9353:   double agedeb;
                   9354:   double ***p3mat;
1.218     brouard  9355:        
                   9356:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9357:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9358:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9359:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9360:   }
                   9361:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9362:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9363:   
                   9364:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9365:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9366:   
1.218     brouard  9367:   /* agelim=AGESUP; */
                   9368:   ageminl=30;
                   9369:   hstepm=stepsize*YEARM; /* Every year of age */
                   9370:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9371:   
                   9372:   /* hstepm=1;   aff par mois*/
                   9373:   pstamp(ficrespijb);
                   9374:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9375:   i1= pow(2,cptcoveff);
1.218     brouard  9376:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9377:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9378:   /*   k=k+1;  */
1.238     brouard  9379:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9380:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9381:       if(TKresult[nres]!= k)
                   9382:        continue;
                   9383:       fprintf(ficrespijb,"\n#****** ");
                   9384:       for(j=1;j<=cptcoveff;j++)
                   9385:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9386:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9387:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9388:       }
                   9389:       fprintf(ficrespijb,"******\n");
                   9390:       if(invalidvarcomb[k]){
                   9391:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9392:        continue;
                   9393:       }
                   9394:       
                   9395:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9396:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9397:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9398:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9399:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9400:        
                   9401:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9402:        
                   9403:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9404:        /* oldm=oldms;savm=savms; */
                   9405:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9406:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9407:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9408:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9409:        for(i=1; i<=nlstate;i++)
                   9410:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9411:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9412:        fprintf(ficrespijb,"\n");
1.238     brouard  9413:        for (h=0; h<=nhstepm; h++){
                   9414:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9415:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9416:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9417:          for(i=1; i<=nlstate;i++)
                   9418:            for(j=1; j<=nlstate+ndeath;j++)
                   9419:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9420:          fprintf(ficrespijb,"\n");
                   9421:        }
                   9422:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9423:        fprintf(ficrespijb,"\n");
                   9424:       } /* end age deb */
                   9425:     } /* end combination */
                   9426:   } /* end nres */
1.218     brouard  9427:   return 0;
                   9428:  } /*  hBijx */
1.217     brouard  9429: 
1.180     brouard  9430: 
1.136     brouard  9431: /***********************************************/
                   9432: /**************** Main Program *****************/
                   9433: /***********************************************/
                   9434: 
                   9435: int main(int argc, char *argv[])
                   9436: {
                   9437: #ifdef GSL
                   9438:   const gsl_multimin_fminimizer_type *T;
                   9439:   size_t iteri = 0, it;
                   9440:   int rval = GSL_CONTINUE;
                   9441:   int status = GSL_SUCCESS;
                   9442:   double ssval;
                   9443: #endif
                   9444:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9445:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9446:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9447:   int jj, ll, li, lj, lk;
1.136     brouard  9448:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9449:   int num_filled;
1.136     brouard  9450:   int itimes;
                   9451:   int NDIM=2;
                   9452:   int vpopbased=0;
1.235     brouard  9453:   int nres=0;
1.136     brouard  9454: 
1.164     brouard  9455:   char ca[32], cb[32];
1.136     brouard  9456:   /*  FILE *fichtm; *//* Html File */
                   9457:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9458:   struct stat info;
1.191     brouard  9459:   double agedeb=0.;
1.194     brouard  9460: 
                   9461:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9462:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9463: 
1.165     brouard  9464:   double fret;
1.191     brouard  9465:   double dum=0.; /* Dummy variable */
1.136     brouard  9466:   double ***p3mat;
1.218     brouard  9467:   /* double ***mobaverage; */
1.164     brouard  9468: 
                   9469:   char line[MAXLINE];
1.197     brouard  9470:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9471: 
1.234     brouard  9472:   char  modeltemp[MAXLINE];
1.230     brouard  9473:   char resultline[MAXLINE];
                   9474:   
1.136     brouard  9475:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9476:   char *tok, *val; /* pathtot */
1.136     brouard  9477:   int firstobs=1, lastobs=10;
1.195     brouard  9478:   int c,  h , cpt, c2;
1.191     brouard  9479:   int jl=0;
                   9480:   int i1, j1, jk, stepsize=0;
1.194     brouard  9481:   int count=0;
                   9482: 
1.164     brouard  9483:   int *tab; 
1.136     brouard  9484:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9485:   int backcast=0;
1.136     brouard  9486:   int mobilav=0,popforecast=0;
1.191     brouard  9487:   int hstepm=0, nhstepm=0;
1.136     brouard  9488:   int agemortsup;
                   9489:   float  sumlpop=0.;
                   9490:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9491:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9492: 
1.191     brouard  9493:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9494:   double ftolpl=FTOL;
                   9495:   double **prlim;
1.217     brouard  9496:   double **bprlim;
1.136     brouard  9497:   double ***param; /* Matrix of parameters */
                   9498:   double  *p;
                   9499:   double **matcov; /* Matrix of covariance */
1.203     brouard  9500:   double **hess; /* Hessian matrix */
1.136     brouard  9501:   double ***delti3; /* Scale */
                   9502:   double *delti; /* Scale */
                   9503:   double ***eij, ***vareij;
                   9504:   double **varpl; /* Variances of prevalence limits by age */
                   9505:   double *epj, vepp;
1.164     brouard  9506: 
1.136     brouard  9507:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9508:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9509: 
1.136     brouard  9510:   double **ximort;
1.145     brouard  9511:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9512:   int *dcwave;
                   9513: 
1.164     brouard  9514:   char z[1]="c";
1.136     brouard  9515: 
                   9516:   /*char  *strt;*/
                   9517:   char strtend[80];
1.126     brouard  9518: 
1.164     brouard  9519: 
1.126     brouard  9520: /*   setlocale (LC_ALL, ""); */
                   9521: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9522: /*   textdomain (PACKAGE); */
                   9523: /*   setlocale (LC_CTYPE, ""); */
                   9524: /*   setlocale (LC_MESSAGES, ""); */
                   9525: 
                   9526:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9527:   rstart_time = time(NULL);  
                   9528:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9529:   start_time = *localtime(&rstart_time);
1.126     brouard  9530:   curr_time=start_time;
1.157     brouard  9531:   /*tml = *localtime(&start_time.tm_sec);*/
                   9532:   /* strcpy(strstart,asctime(&tml)); */
                   9533:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9534: 
                   9535: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9536: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9537: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9538: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9539: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9540: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9541: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9542: /*   strt=asctime(&tmg); */
                   9543: /*   printf("Time(after) =%s",strstart);  */
                   9544: /*  (void) time (&time_value);
                   9545: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9546: *  tm = *localtime(&time_value);
                   9547: *  strstart=asctime(&tm);
                   9548: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9549: */
                   9550: 
                   9551:   nberr=0; /* Number of errors and warnings */
                   9552:   nbwarn=0;
1.184     brouard  9553: #ifdef WIN32
                   9554:   _getcwd(pathcd, size);
                   9555: #else
1.126     brouard  9556:   getcwd(pathcd, size);
1.184     brouard  9557: #endif
1.191     brouard  9558:   syscompilerinfo(0);
1.196     brouard  9559:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9560:   if(argc <=1){
                   9561:     printf("\nEnter the parameter file name: ");
1.205     brouard  9562:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9563:       printf("ERROR Empty parameter file name\n");
                   9564:       goto end;
                   9565:     }
1.126     brouard  9566:     i=strlen(pathr);
                   9567:     if(pathr[i-1]=='\n')
                   9568:       pathr[i-1]='\0';
1.156     brouard  9569:     i=strlen(pathr);
1.205     brouard  9570:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9571:       pathr[i-1]='\0';
1.205     brouard  9572:     }
                   9573:     i=strlen(pathr);
                   9574:     if( i==0 ){
                   9575:       printf("ERROR Empty parameter file name\n");
                   9576:       goto end;
                   9577:     }
                   9578:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9579:       printf("Pathr |%s|\n",pathr);
                   9580:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9581:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9582:       strcpy (pathtot, val);
                   9583:       if(pathr[0] == '\0') break; /* Dirty */
                   9584:     }
                   9585:   }
                   9586:   else{
                   9587:     strcpy(pathtot,argv[1]);
                   9588:   }
                   9589:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9590:   /*cygwin_split_path(pathtot,path,optionfile);
                   9591:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9592:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9593: 
                   9594:   /* Split argv[0], imach program to get pathimach */
                   9595:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9596:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9597:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9598:  /*   strcpy(pathimach,argv[0]); */
                   9599:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9600:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9601:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9602: #ifdef WIN32
                   9603:   _chdir(path); /* Can be a relative path */
                   9604:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9605: #else
1.126     brouard  9606:   chdir(path); /* Can be a relative path */
1.184     brouard  9607:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9608: #endif
                   9609:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9610:   strcpy(command,"mkdir ");
                   9611:   strcat(command,optionfilefiname);
                   9612:   if((outcmd=system(command)) != 0){
1.169     brouard  9613:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9614:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9615:     /* fclose(ficlog); */
                   9616: /*     exit(1); */
                   9617:   }
                   9618: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9619: /*     perror("mkdir"); */
                   9620: /*   } */
                   9621: 
                   9622:   /*-------- arguments in the command line --------*/
                   9623: 
1.186     brouard  9624:   /* Main Log file */
1.126     brouard  9625:   strcat(filelog, optionfilefiname);
                   9626:   strcat(filelog,".log");    /* */
                   9627:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9628:     printf("Problem with logfile %s\n",filelog);
                   9629:     goto end;
                   9630:   }
                   9631:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9632:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9633:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9634:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9635:  path=%s \n\
                   9636:  optionfile=%s\n\
                   9637:  optionfilext=%s\n\
1.156     brouard  9638:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9639: 
1.197     brouard  9640:   syscompilerinfo(1);
1.167     brouard  9641: 
1.126     brouard  9642:   printf("Local time (at start):%s",strstart);
                   9643:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9644:   fflush(ficlog);
                   9645: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9646: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9647: 
                   9648:   /* */
                   9649:   strcpy(fileres,"r");
                   9650:   strcat(fileres, optionfilefiname);
1.201     brouard  9651:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9652:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9653:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9654: 
1.186     brouard  9655:   /* Main ---------arguments file --------*/
1.126     brouard  9656: 
                   9657:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9658:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9659:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9660:     fflush(ficlog);
1.149     brouard  9661:     /* goto end; */
                   9662:     exit(70); 
1.126     brouard  9663:   }
                   9664: 
                   9665: 
                   9666: 
                   9667:   strcpy(filereso,"o");
1.201     brouard  9668:   strcat(filereso,fileresu);
1.126     brouard  9669:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9670:     printf("Problem with Output resultfile: %s\n", filereso);
                   9671:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9672:     fflush(ficlog);
                   9673:     goto end;
                   9674:   }
                   9675: 
                   9676:   /* Reads comments: lines beginning with '#' */
                   9677:   numlinepar=0;
1.197     brouard  9678: 
                   9679:     /* First parameter line */
                   9680:   while(fgets(line, MAXLINE, ficpar)) {
                   9681:     /* If line starts with a # it is a comment */
                   9682:     if (line[0] == '#') {
                   9683:       numlinepar++;
                   9684:       fputs(line,stdout);
                   9685:       fputs(line,ficparo);
                   9686:       fputs(line,ficlog);
                   9687:       continue;
                   9688:     }else
                   9689:       break;
                   9690:   }
                   9691:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9692:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9693:     if (num_filled != 5) {
                   9694:       printf("Should be 5 parameters\n");
                   9695:     }
1.126     brouard  9696:     numlinepar++;
1.197     brouard  9697:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9698:   }
                   9699:   /* Second parameter line */
                   9700:   while(fgets(line, MAXLINE, ficpar)) {
                   9701:     /* If line starts with a # it is a comment */
                   9702:     if (line[0] == '#') {
                   9703:       numlinepar++;
                   9704:       fputs(line,stdout);
                   9705:       fputs(line,ficparo);
                   9706:       fputs(line,ficlog);
                   9707:       continue;
                   9708:     }else
                   9709:       break;
                   9710:   }
1.223     brouard  9711:   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", \
                   9712:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9713:     if (num_filled != 11) {
                   9714:       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  9715:       printf("but line=%s\n",line);
1.197     brouard  9716:     }
1.223     brouard  9717:     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  9718:   }
1.203     brouard  9719:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9720:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9721:   /* Third parameter line */
                   9722:   while(fgets(line, MAXLINE, ficpar)) {
                   9723:     /* If line starts with a # it is a comment */
                   9724:     if (line[0] == '#') {
                   9725:       numlinepar++;
                   9726:       fputs(line,stdout);
                   9727:       fputs(line,ficparo);
                   9728:       fputs(line,ficlog);
                   9729:       continue;
                   9730:     }else
                   9731:       break;
                   9732:   }
1.201     brouard  9733:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9734:     if (num_filled == 0)
                   9735:             model[0]='\0';
                   9736:     else if (num_filled != 1){
1.197     brouard  9737:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9738:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9739:       model[0]='\0';
                   9740:       goto end;
                   9741:     }
                   9742:     else{
                   9743:       if (model[0]=='+'){
                   9744:        for(i=1; i<=strlen(model);i++)
                   9745:          modeltemp[i-1]=model[i];
1.201     brouard  9746:        strcpy(model,modeltemp); 
1.197     brouard  9747:       }
                   9748:     }
1.199     brouard  9749:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9750:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9751:   }
                   9752:   /* 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); */
                   9753:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9754:   /* 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  9755:   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);
                   9756:   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  9757:   fflush(ficlog);
1.190     brouard  9758:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9759:   if(model[0]=='#'){
1.187     brouard  9760:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9761:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9762:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9763:     if(mle != -1){
                   9764:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9765:       exit(1);
                   9766:     }
                   9767:   }
1.126     brouard  9768:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9769:     ungetc(c,ficpar);
                   9770:     fgets(line, MAXLINE, ficpar);
                   9771:     numlinepar++;
1.195     brouard  9772:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9773:       z[0]=line[1];
                   9774:     }
                   9775:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9776:     fputs(line, stdout);
                   9777:     //puts(line);
1.126     brouard  9778:     fputs(line,ficparo);
                   9779:     fputs(line,ficlog);
                   9780:   }
                   9781:   ungetc(c,ficpar);
                   9782: 
                   9783:    
1.145     brouard  9784:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9785:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9786:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9787:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9788:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9789:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9790:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9791:   */
                   9792:   if (strlen(model)>1) 
1.187     brouard  9793:     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  9794:   else
1.187     brouard  9795:     ncovmodel=2; /* Constant and age */
1.133     brouard  9796:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9797:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9798:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9799:     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);
                   9800:     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);
                   9801:     fflush(stdout);
                   9802:     fclose (ficlog);
                   9803:     goto end;
                   9804:   }
1.126     brouard  9805:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9806:   delti=delti3[1][1];
                   9807:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9808:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9809:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9810:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9811:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9812:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9813:     fclose (ficparo);
                   9814:     fclose (ficlog);
                   9815:     goto end;
                   9816:     exit(0);
1.220     brouard  9817:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9818:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9819:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9820:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9821:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9822:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9823:     hess=matrix(1,npar,1,npar);
1.220     brouard  9824:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9825:     /* Read guessed parameters */
1.126     brouard  9826:     /* Reads comments: lines beginning with '#' */
                   9827:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9828:       ungetc(c,ficpar);
                   9829:       fgets(line, MAXLINE, ficpar);
                   9830:       numlinepar++;
1.141     brouard  9831:       fputs(line,stdout);
1.126     brouard  9832:       fputs(line,ficparo);
                   9833:       fputs(line,ficlog);
                   9834:     }
                   9835:     ungetc(c,ficpar);
                   9836:     
                   9837:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9838:     for(i=1; i <=nlstate; i++){
1.234     brouard  9839:       j=0;
1.126     brouard  9840:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9841:        if(jj==i) continue;
                   9842:        j++;
                   9843:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9844:        if ((i1 != i) || (j1 != jj)){
                   9845:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9846: It might be a problem of design; if ncovcol and the model are correct\n \
                   9847: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9848:          exit(1);
                   9849:        }
                   9850:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9851:        if(mle==1)
                   9852:          printf("%1d%1d",i,jj);
                   9853:        fprintf(ficlog,"%1d%1d",i,jj);
                   9854:        for(k=1; k<=ncovmodel;k++){
                   9855:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9856:          if(mle==1){
                   9857:            printf(" %lf",param[i][j][k]);
                   9858:            fprintf(ficlog," %lf",param[i][j][k]);
                   9859:          }
                   9860:          else
                   9861:            fprintf(ficlog," %lf",param[i][j][k]);
                   9862:          fprintf(ficparo," %lf",param[i][j][k]);
                   9863:        }
                   9864:        fscanf(ficpar,"\n");
                   9865:        numlinepar++;
                   9866:        if(mle==1)
                   9867:          printf("\n");
                   9868:        fprintf(ficlog,"\n");
                   9869:        fprintf(ficparo,"\n");
1.126     brouard  9870:       }
                   9871:     }  
                   9872:     fflush(ficlog);
1.234     brouard  9873:     
1.145     brouard  9874:     /* Reads scales values */
1.126     brouard  9875:     p=param[1][1];
                   9876:     
                   9877:     /* Reads comments: lines beginning with '#' */
                   9878:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9879:       ungetc(c,ficpar);
                   9880:       fgets(line, MAXLINE, ficpar);
                   9881:       numlinepar++;
1.141     brouard  9882:       fputs(line,stdout);
1.126     brouard  9883:       fputs(line,ficparo);
                   9884:       fputs(line,ficlog);
                   9885:     }
                   9886:     ungetc(c,ficpar);
                   9887: 
                   9888:     for(i=1; i <=nlstate; i++){
                   9889:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9890:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9891:        if ( (i1-i) * (j1-j) != 0){
                   9892:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9893:          exit(1);
                   9894:        }
                   9895:        printf("%1d%1d",i,j);
                   9896:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9897:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9898:        for(k=1; k<=ncovmodel;k++){
                   9899:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9900:          printf(" %le",delti3[i][j][k]);
                   9901:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9902:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9903:        }
                   9904:        fscanf(ficpar,"\n");
                   9905:        numlinepar++;
                   9906:        printf("\n");
                   9907:        fprintf(ficparo,"\n");
                   9908:        fprintf(ficlog,"\n");
1.126     brouard  9909:       }
                   9910:     }
                   9911:     fflush(ficlog);
1.234     brouard  9912:     
1.145     brouard  9913:     /* Reads covariance matrix */
1.126     brouard  9914:     delti=delti3[1][1];
1.220     brouard  9915:                
                   9916:                
1.126     brouard  9917:     /* 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  9918:                
1.126     brouard  9919:     /* Reads comments: lines beginning with '#' */
                   9920:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9921:       ungetc(c,ficpar);
                   9922:       fgets(line, MAXLINE, ficpar);
                   9923:       numlinepar++;
1.141     brouard  9924:       fputs(line,stdout);
1.126     brouard  9925:       fputs(line,ficparo);
                   9926:       fputs(line,ficlog);
                   9927:     }
                   9928:     ungetc(c,ficpar);
1.220     brouard  9929:                
1.126     brouard  9930:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9931:     hess=matrix(1,npar,1,npar);
1.131     brouard  9932:     for(i=1; i <=npar; i++)
                   9933:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9934:                
1.194     brouard  9935:     /* Scans npar lines */
1.126     brouard  9936:     for(i=1; i <=npar; i++){
1.226     brouard  9937:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  9938:       if(count != 3){
1.226     brouard  9939:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9940: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9941: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9942:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9943: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9944: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9945:        exit(1);
1.220     brouard  9946:       }else{
1.226     brouard  9947:        if(mle==1)
                   9948:          printf("%1d%1d%d",i1,j1,jk);
                   9949:       }
                   9950:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   9951:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  9952:       for(j=1; j <=i; j++){
1.226     brouard  9953:        fscanf(ficpar," %le",&matcov[i][j]);
                   9954:        if(mle==1){
                   9955:          printf(" %.5le",matcov[i][j]);
                   9956:        }
                   9957:        fprintf(ficlog," %.5le",matcov[i][j]);
                   9958:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  9959:       }
                   9960:       fscanf(ficpar,"\n");
                   9961:       numlinepar++;
                   9962:       if(mle==1)
1.220     brouard  9963:                                printf("\n");
1.126     brouard  9964:       fprintf(ficlog,"\n");
                   9965:       fprintf(ficparo,"\n");
                   9966:     }
1.194     brouard  9967:     /* End of read covariance matrix npar lines */
1.126     brouard  9968:     for(i=1; i <=npar; i++)
                   9969:       for(j=i+1;j<=npar;j++)
1.226     brouard  9970:        matcov[i][j]=matcov[j][i];
1.126     brouard  9971:     
                   9972:     if(mle==1)
                   9973:       printf("\n");
                   9974:     fprintf(ficlog,"\n");
                   9975:     
                   9976:     fflush(ficlog);
                   9977:     
                   9978:     /*-------- Rewriting parameter file ----------*/
                   9979:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   9980:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   9981:     strcat(rfileres,".");    /* */
                   9982:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   9983:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  9984:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   9985:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  9986:     }
                   9987:     fprintf(ficres,"#%s\n",version);
                   9988:   }    /* End of mle != -3 */
1.218     brouard  9989:   
1.186     brouard  9990:   /*  Main data
                   9991:    */
1.126     brouard  9992:   n= lastobs;
                   9993:   num=lvector(1,n);
                   9994:   moisnais=vector(1,n);
                   9995:   annais=vector(1,n);
                   9996:   moisdc=vector(1,n);
                   9997:   andc=vector(1,n);
1.220     brouard  9998:   weight=vector(1,n);
1.126     brouard  9999:   agedc=vector(1,n);
                   10000:   cod=ivector(1,n);
1.220     brouard  10001:   for(i=1;i<=n;i++){
1.234     brouard  10002:     num[i]=0;
                   10003:     moisnais[i]=0;
                   10004:     annais[i]=0;
                   10005:     moisdc[i]=0;
                   10006:     andc[i]=0;
                   10007:     agedc[i]=0;
                   10008:     cod[i]=0;
                   10009:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10010:   }
1.126     brouard  10011:   mint=matrix(1,maxwav,1,n);
                   10012:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10013:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10014:   tab=ivector(1,NCOVMAX);
1.144     brouard  10015:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10016:   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  10017: 
1.136     brouard  10018:   /* Reads data from file datafile */
                   10019:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10020:     goto end;
                   10021: 
                   10022:   /* Calculation of the number of parameters from char model */
1.234     brouard  10023:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10024:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10025:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10026:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10027:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10028:   */
                   10029:   
                   10030:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10031:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10032:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10033:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10034:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10035:   TvarF=ivector(1,NCOVMAX); /*  */
                   10036:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10037:   TvarV=ivector(1,NCOVMAX); /*  */
                   10038:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10039:   TvarA=ivector(1,NCOVMAX); /*  */
                   10040:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10041:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10042:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10043:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10044:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10045:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10046:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10047:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10048:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10049: 
1.230     brouard  10050:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10051:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10052:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10053:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10054:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10055:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10056:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10057:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10058:   */
                   10059:   /* For model-covariate k tells which data-covariate to use but
                   10060:     because this model-covariate is a construction we invent a new column
                   10061:     ncovcol + k1
                   10062:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10063:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10064:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10065:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10066:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10067:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10068:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10069:   */
1.145     brouard  10070:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10071:   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  10072:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10073:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10074:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10075:                         4 covariates (3 plus signs)
                   10076:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10077:                      */  
1.230     brouard  10078:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10079:                                * individual dummy, fixed or varying:
                   10080:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10081:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10082:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10083:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10084:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10085:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10086:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10087:                                * individual quantitative, fixed or varying:
                   10088:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10089:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10090:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10091: /* Main decodemodel */
                   10092: 
1.187     brouard  10093: 
1.223     brouard  10094:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10095:     goto end;
                   10096: 
1.137     brouard  10097:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10098:     nbwarn++;
                   10099:     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); 
                   10100:     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); 
                   10101:   }
1.136     brouard  10102:     /*  if(mle==1){*/
1.137     brouard  10103:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10104:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10105:   }
                   10106: 
                   10107:     /*-calculation of age at interview from date of interview and age at death -*/
                   10108:   agev=matrix(1,maxwav,1,imx);
                   10109: 
                   10110:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10111:     goto end;
                   10112: 
1.126     brouard  10113: 
1.136     brouard  10114:   agegomp=(int)agemin;
                   10115:   free_vector(moisnais,1,n);
                   10116:   free_vector(annais,1,n);
1.126     brouard  10117:   /* free_matrix(mint,1,maxwav,1,n);
                   10118:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10119:   /* free_vector(moisdc,1,n); */
                   10120:   /* free_vector(andc,1,n); */
1.145     brouard  10121:   /* */
                   10122:   
1.126     brouard  10123:   wav=ivector(1,imx);
1.214     brouard  10124:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10125:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10126:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10127:   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.*/
                   10128:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10129:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10130:    
                   10131:   /* Concatenates waves */
1.214     brouard  10132:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10133:      Death is a valid wave (if date is known).
                   10134:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10135:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10136:      and mw[mi+1][i]. dh depends on stepm.
                   10137:   */
                   10138: 
1.126     brouard  10139:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  10140:   /* */
                   10141:  
1.215     brouard  10142:   free_vector(moisdc,1,n);
                   10143:   free_vector(andc,1,n);
                   10144: 
1.126     brouard  10145:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10146:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10147:   ncodemax[1]=1;
1.145     brouard  10148:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10149:   cptcoveff=0;
1.220     brouard  10150:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10151:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10152:   }
                   10153:   
                   10154:   ncovcombmax=pow(2,cptcoveff);
                   10155:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10156:   for(i=1;i<ncovcombmax;i++)
                   10157:     invalidvarcomb[i]=0;
                   10158:   
1.211     brouard  10159:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10160:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10161:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10162:   
1.200     brouard  10163:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10164:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10165:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10166:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10167:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10168:    * (currently 0 or 1) in the data.
                   10169:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10170:    * corresponding modality (h,j).
                   10171:    */
                   10172: 
1.145     brouard  10173:   h=0;
                   10174:   /*if (cptcovn > 0) */
1.126     brouard  10175:   m=pow(2,cptcoveff);
                   10176:  
1.144     brouard  10177:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10178:           * For k=4 covariates, h goes from 1 to m=2**k
                   10179:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10180:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10181:           *     h\k   1     2     3     4
1.143     brouard  10182:           *______________________________  
                   10183:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10184:           *     2     2     1     1     1
                   10185:           *     3 i=2 1     2     1     1
                   10186:           *     4     2     2     1     1
                   10187:           *     5 i=3 1 i=2 1     2     1
                   10188:           *     6     2     1     2     1
                   10189:           *     7 i=4 1     2     2     1
                   10190:           *     8     2     2     2     1
1.197     brouard  10191:           *     9 i=5 1 i=3 1 i=2 1     2
                   10192:           *    10     2     1     1     2
                   10193:           *    11 i=6 1     2     1     2
                   10194:           *    12     2     2     1     2
                   10195:           *    13 i=7 1 i=4 1     2     2    
                   10196:           *    14     2     1     2     2
                   10197:           *    15 i=8 1     2     2     2
                   10198:           *    16     2     2     2     2
1.143     brouard  10199:           */
1.212     brouard  10200:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10201:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10202:      * and the value of each covariate?
                   10203:      * V1=1, V2=1, V3=2, V4=1 ?
                   10204:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10205:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10206:      * In order to get the real value in the data, we use nbcode
                   10207:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10208:      * We are keeping this crazy system in order to be able (in the future?) 
                   10209:      * to have more than 2 values (0 or 1) for a covariate.
                   10210:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10211:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10212:      *              bbbbbbbb
                   10213:      *              76543210     
                   10214:      *   h-1        00000101 (6-1=5)
1.219     brouard  10215:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10216:      *           &
                   10217:      *     1        00000001 (1)
1.219     brouard  10218:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10219:      *          +1= 00000001 =1 
1.211     brouard  10220:      *
                   10221:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10222:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10223:      *    >>k'            11
                   10224:      *          &   00000001
                   10225:      *            = 00000001
                   10226:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10227:      * Reverse h=6 and m=16?
                   10228:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10229:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10230:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10231:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10232:      * V3=decodtabm(14,3,2**4)=2
                   10233:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10234:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10235:      *          &1 000000001
                   10236:      *           = 000000001
                   10237:      *         +1= 000000010 =2
                   10238:      *                  2211
                   10239:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10240:      *                  V3=2
1.220     brouard  10241:                 * codtabm and decodtabm are identical
1.211     brouard  10242:      */
                   10243: 
1.145     brouard  10244: 
                   10245:  free_ivector(Ndum,-1,NCOVMAX);
                   10246: 
                   10247: 
1.126     brouard  10248:     
1.186     brouard  10249:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10250:   strcpy(optionfilegnuplot,optionfilefiname);
                   10251:   if(mle==-3)
1.201     brouard  10252:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10253:   strcat(optionfilegnuplot,".gp");
                   10254: 
                   10255:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10256:     printf("Problem with file %s",optionfilegnuplot);
                   10257:   }
                   10258:   else{
1.204     brouard  10259:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10260:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10261:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10262:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10263:   }
                   10264:   /*  fclose(ficgp);*/
1.186     brouard  10265: 
                   10266: 
                   10267:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10268: 
                   10269:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10270:   if(mle==-3)
1.201     brouard  10271:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10272:   strcat(optionfilehtm,".htm");
                   10273:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10274:     printf("Problem with %s \n",optionfilehtm);
                   10275:     exit(0);
1.126     brouard  10276:   }
                   10277: 
                   10278:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10279:   strcat(optionfilehtmcov,"-cov.htm");
                   10280:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10281:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10282:   }
                   10283:   else{
                   10284:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10285: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10286: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10287:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10288:   }
                   10289: 
1.213     brouard  10290:   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  10291: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10292: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10293: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10294: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10295: \n\
                   10296: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10297:  <ul><li><h4>Parameter files</h4>\n\
                   10298:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10299:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10300:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10301:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10302:  - Date and time at start: %s</ul>\n",\
                   10303:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10304:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10305:          fileres,fileres,\
                   10306:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10307:   fflush(fichtm);
                   10308: 
                   10309:   strcpy(pathr,path);
                   10310:   strcat(pathr,optionfilefiname);
1.184     brouard  10311: #ifdef WIN32
                   10312:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10313: #else
1.126     brouard  10314:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10315: #endif
                   10316:          
1.126     brouard  10317:   
1.220     brouard  10318:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10319:                 and for any valid combination of covariates
1.126     brouard  10320:      and prints on file fileres'p'. */
1.227     brouard  10321:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10322:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10323: 
                   10324:   fprintf(fichtm,"\n");
                   10325:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10326: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10327: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10328:          imx,agemin,agemax,jmin,jmax,jmean);
                   10329:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10330:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10331:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10332:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10333:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10334: 
1.126     brouard  10335:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10336:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10337:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10338: 
                   10339:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10340:   /* For mortality only */
1.126     brouard  10341:   if (mle==-3){
1.136     brouard  10342:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10343:                for(i=1;i<=NDIM;i++)
                   10344:                        for(j=1;j<=NDIM;j++)
                   10345:                                ximort[i][j]=0.;
1.186     brouard  10346:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10347:     cens=ivector(1,n);
                   10348:     ageexmed=vector(1,n);
                   10349:     agecens=vector(1,n);
                   10350:     dcwave=ivector(1,n);
1.223     brouard  10351:                
1.126     brouard  10352:     for (i=1; i<=imx; i++){
                   10353:       dcwave[i]=-1;
                   10354:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10355:        if (s[m][i]>nlstate) {
                   10356:          dcwave[i]=m;
                   10357:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10358:          break;
                   10359:        }
1.126     brouard  10360:     }
1.226     brouard  10361:     
1.126     brouard  10362:     for (i=1; i<=imx; i++) {
                   10363:       if (wav[i]>0){
1.226     brouard  10364:        ageexmed[i]=agev[mw[1][i]][i];
                   10365:        j=wav[i];
                   10366:        agecens[i]=1.; 
                   10367:        
                   10368:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10369:          agecens[i]=agev[mw[j][i]][i];
                   10370:          cens[i]= 1;
                   10371:        }else if (ageexmed[i]< 1) 
                   10372:          cens[i]= -1;
                   10373:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10374:          cens[i]=0 ;
1.126     brouard  10375:       }
                   10376:       else cens[i]=-1;
                   10377:     }
                   10378:     
                   10379:     for (i=1;i<=NDIM;i++) {
                   10380:       for (j=1;j<=NDIM;j++)
1.226     brouard  10381:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10382:     }
                   10383:     
1.145     brouard  10384:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10385:     /*printf("%lf %lf", p[1], p[2]);*/
                   10386:     
                   10387:     
1.136     brouard  10388: #ifdef GSL
                   10389:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10390: #else
1.126     brouard  10391:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10392: #endif
1.201     brouard  10393:     strcpy(filerespow,"POW-MORT_"); 
                   10394:     strcat(filerespow,fileresu);
1.126     brouard  10395:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10396:       printf("Problem with resultfile: %s\n", filerespow);
                   10397:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10398:     }
1.136     brouard  10399: #ifdef GSL
                   10400:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10401: #else
1.126     brouard  10402:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10403: #endif
1.126     brouard  10404:     /*  for (i=1;i<=nlstate;i++)
                   10405:        for(j=1;j<=nlstate+ndeath;j++)
                   10406:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10407:     */
                   10408:     fprintf(ficrespow,"\n");
1.136     brouard  10409: #ifdef GSL
                   10410:     /* gsl starts here */ 
                   10411:     T = gsl_multimin_fminimizer_nmsimplex;
                   10412:     gsl_multimin_fminimizer *sfm = NULL;
                   10413:     gsl_vector *ss, *x;
                   10414:     gsl_multimin_function minex_func;
                   10415: 
                   10416:     /* Initial vertex size vector */
                   10417:     ss = gsl_vector_alloc (NDIM);
                   10418:     
                   10419:     if (ss == NULL){
                   10420:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10421:     }
                   10422:     /* Set all step sizes to 1 */
                   10423:     gsl_vector_set_all (ss, 0.001);
                   10424: 
                   10425:     /* Starting point */
1.126     brouard  10426:     
1.136     brouard  10427:     x = gsl_vector_alloc (NDIM);
                   10428:     
                   10429:     if (x == NULL){
                   10430:       gsl_vector_free(ss);
                   10431:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10432:     }
                   10433:   
                   10434:     /* Initialize method and iterate */
                   10435:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10436:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10437:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10438:     gsl_vector_set(x, 0, p[1]);
                   10439:     gsl_vector_set(x, 1, p[2]);
                   10440: 
                   10441:     minex_func.f = &gompertz_f;
                   10442:     minex_func.n = NDIM;
                   10443:     minex_func.params = (void *)&p; /* ??? */
                   10444:     
                   10445:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10446:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10447:     
                   10448:     printf("Iterations beginning .....\n\n");
                   10449:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10450: 
                   10451:     iteri=0;
                   10452:     while (rval == GSL_CONTINUE){
                   10453:       iteri++;
                   10454:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10455:       
                   10456:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10457:       fflush(0);
                   10458:       
                   10459:       if (status) 
                   10460:         break;
                   10461:       
                   10462:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10463:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10464:       
                   10465:       if (rval == GSL_SUCCESS)
                   10466:         printf ("converged to a local maximum at\n");
                   10467:       
                   10468:       printf("%5d ", iteri);
                   10469:       for (it = 0; it < NDIM; it++){
                   10470:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10471:       }
                   10472:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10473:     }
                   10474:     
                   10475:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10476:     
                   10477:     gsl_vector_free(x); /* initial values */
                   10478:     gsl_vector_free(ss); /* inital step size */
                   10479:     for (it=0; it<NDIM; it++){
                   10480:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10481:       fprintf(ficrespow," %.12lf", p[it]);
                   10482:     }
                   10483:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10484: #endif
                   10485: #ifdef POWELL
                   10486:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10487: #endif  
1.126     brouard  10488:     fclose(ficrespow);
                   10489:     
1.203     brouard  10490:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10491: 
                   10492:     for(i=1; i <=NDIM; i++)
                   10493:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10494:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10495:     
                   10496:     printf("\nCovariance matrix\n ");
1.203     brouard  10497:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10498:     for(i=1; i <=NDIM; i++) {
                   10499:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10500:                                printf("%f ",matcov[i][j]);
                   10501:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10502:       }
1.203     brouard  10503:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10504:     }
                   10505:     
                   10506:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10507:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10508:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10509:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10510:     }
1.126     brouard  10511:     lsurv=vector(1,AGESUP);
                   10512:     lpop=vector(1,AGESUP);
                   10513:     tpop=vector(1,AGESUP);
                   10514:     lsurv[agegomp]=100000;
                   10515:     
                   10516:     for (k=agegomp;k<=AGESUP;k++) {
                   10517:       agemortsup=k;
                   10518:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10519:     }
                   10520:     
                   10521:     for (k=agegomp;k<agemortsup;k++)
                   10522:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10523:     
                   10524:     for (k=agegomp;k<agemortsup;k++){
                   10525:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10526:       sumlpop=sumlpop+lpop[k];
                   10527:     }
                   10528:     
                   10529:     tpop[agegomp]=sumlpop;
                   10530:     for (k=agegomp;k<(agemortsup-3);k++){
                   10531:       /*  tpop[k+1]=2;*/
                   10532:       tpop[k+1]=tpop[k]-lpop[k];
                   10533:     }
                   10534:     
                   10535:     
                   10536:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10537:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10538:       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]);
                   10539:     
                   10540:     
                   10541:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10542:                ageminpar=50;
                   10543:                agemaxpar=100;
1.194     brouard  10544:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10545:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10546: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10547: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10548:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10549: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10550: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10551:     }else{
                   10552:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10553:                        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  10554:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10555:                }
1.201     brouard  10556:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10557:                     stepm, weightopt,\
                   10558:                     model,imx,p,matcov,agemortsup);
                   10559:     
                   10560:     free_vector(lsurv,1,AGESUP);
                   10561:     free_vector(lpop,1,AGESUP);
                   10562:     free_vector(tpop,1,AGESUP);
1.220     brouard  10563:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10564:     free_ivector(cens,1,n);
                   10565:     free_vector(agecens,1,n);
                   10566:     free_ivector(dcwave,1,n);
1.220     brouard  10567: #ifdef GSL
1.136     brouard  10568: #endif
1.186     brouard  10569:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10570:   /* Standard  */
                   10571:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10572:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10573:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10574:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10575:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10576:     for (k=1; k<=npar;k++)
                   10577:       printf(" %d %8.5f",k,p[k]);
                   10578:     printf("\n");
1.205     brouard  10579:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10580:       /* mlikeli uses func not funcone */
                   10581:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10582:     }
                   10583:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10584:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10585:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10586:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10587:     }
                   10588:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10589:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10590:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10591:     for (k=1; k<=npar;k++)
                   10592:       printf(" %d %8.5f",k,p[k]);
                   10593:     printf("\n");
                   10594:     
                   10595:     /*--------- results files --------------*/
1.224     brouard  10596:     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  10597:     
                   10598:     
                   10599:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10600:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10601:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10602:     for(i=1,jk=1; i <=nlstate; i++){
                   10603:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10604:        if (k != i) {
                   10605:          printf("%d%d ",i,k);
                   10606:          fprintf(ficlog,"%d%d ",i,k);
                   10607:          fprintf(ficres,"%1d%1d ",i,k);
                   10608:          for(j=1; j <=ncovmodel; j++){
                   10609:            printf("%12.7f ",p[jk]);
                   10610:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10611:            fprintf(ficres,"%12.7f ",p[jk]);
                   10612:            jk++; 
                   10613:          }
                   10614:          printf("\n");
                   10615:          fprintf(ficlog,"\n");
                   10616:          fprintf(ficres,"\n");
                   10617:        }
1.126     brouard  10618:       }
                   10619:     }
1.203     brouard  10620:     if(mle != 0){
                   10621:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10622:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10623:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10624:       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");
                   10625:       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");
                   10626:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10627:        for(k=1; k <=(nlstate+ndeath); k++){
                   10628:          if (k != i) {
                   10629:            printf("%d%d ",i,k);
                   10630:            fprintf(ficlog,"%d%d ",i,k);
                   10631:            for(j=1; j <=ncovmodel; j++){
                   10632:              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]));
                   10633:              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]));
                   10634:              jk++; 
                   10635:            }
                   10636:            printf("\n");
                   10637:            fprintf(ficlog,"\n");
                   10638:          }
                   10639:        }
1.193     brouard  10640:       }
1.203     brouard  10641:     } /* end of hesscov and Wald tests */
1.225     brouard  10642:     
1.203     brouard  10643:     /*  */
1.126     brouard  10644:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10645:     printf("# Scales (for hessian or gradient estimation)\n");
                   10646:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10647:     for(i=1,jk=1; i <=nlstate; i++){
                   10648:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10649:        if (j!=i) {
                   10650:          fprintf(ficres,"%1d%1d",i,j);
                   10651:          printf("%1d%1d",i,j);
                   10652:          fprintf(ficlog,"%1d%1d",i,j);
                   10653:          for(k=1; k<=ncovmodel;k++){
                   10654:            printf(" %.5e",delti[jk]);
                   10655:            fprintf(ficlog," %.5e",delti[jk]);
                   10656:            fprintf(ficres," %.5e",delti[jk]);
                   10657:            jk++;
                   10658:          }
                   10659:          printf("\n");
                   10660:          fprintf(ficlog,"\n");
                   10661:          fprintf(ficres,"\n");
                   10662:        }
1.126     brouard  10663:       }
                   10664:     }
                   10665:     
                   10666:     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  10667:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10668:       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");
                   10669:     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");
                   10670:     /* # 121 Var(a12)\n\ */
                   10671:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10672:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10673:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10674:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10675:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10676:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10677:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10678:     
                   10679:     
                   10680:     /* Just to have a covariance matrix which will be more understandable
                   10681:        even is we still don't want to manage dictionary of variables
                   10682:     */
                   10683:     for(itimes=1;itimes<=2;itimes++){
                   10684:       jj=0;
                   10685:       for(i=1; i <=nlstate; i++){
1.225     brouard  10686:        for(j=1; j <=nlstate+ndeath; j++){
                   10687:          if(j==i) continue;
                   10688:          for(k=1; k<=ncovmodel;k++){
                   10689:            jj++;
                   10690:            ca[0]= k+'a'-1;ca[1]='\0';
                   10691:            if(itimes==1){
                   10692:              if(mle>=1)
                   10693:                printf("#%1d%1d%d",i,j,k);
                   10694:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10695:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10696:            }else{
                   10697:              if(mle>=1)
                   10698:                printf("%1d%1d%d",i,j,k);
                   10699:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10700:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10701:            }
                   10702:            ll=0;
                   10703:            for(li=1;li <=nlstate; li++){
                   10704:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10705:                if(lj==li) continue;
                   10706:                for(lk=1;lk<=ncovmodel;lk++){
                   10707:                  ll++;
                   10708:                  if(ll<=jj){
                   10709:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10710:                    if(ll<jj){
                   10711:                      if(itimes==1){
                   10712:                        if(mle>=1)
                   10713:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10714:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10715:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10716:                      }else{
                   10717:                        if(mle>=1)
                   10718:                          printf(" %.5e",matcov[jj][ll]); 
                   10719:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10720:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10721:                      }
                   10722:                    }else{
                   10723:                      if(itimes==1){
                   10724:                        if(mle>=1)
                   10725:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10726:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10727:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10728:                      }else{
                   10729:                        if(mle>=1)
                   10730:                          printf(" %.7e",matcov[jj][ll]); 
                   10731:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10732:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10733:                      }
                   10734:                    }
                   10735:                  }
                   10736:                } /* end lk */
                   10737:              } /* end lj */
                   10738:            } /* end li */
                   10739:            if(mle>=1)
                   10740:              printf("\n");
                   10741:            fprintf(ficlog,"\n");
                   10742:            fprintf(ficres,"\n");
                   10743:            numlinepar++;
                   10744:          } /* end k*/
                   10745:        } /*end j */
1.126     brouard  10746:       } /* end i */
                   10747:     } /* end itimes */
                   10748:     
                   10749:     fflush(ficlog);
                   10750:     fflush(ficres);
1.225     brouard  10751:     while(fgets(line, MAXLINE, ficpar)) {
                   10752:       /* If line starts with a # it is a comment */
                   10753:       if (line[0] == '#') {
                   10754:        numlinepar++;
                   10755:        fputs(line,stdout);
                   10756:        fputs(line,ficparo);
                   10757:        fputs(line,ficlog);
                   10758:        continue;
                   10759:       }else
                   10760:        break;
                   10761:     }
                   10762:     
1.209     brouard  10763:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10764:     /*   ungetc(c,ficpar); */
                   10765:     /*   fgets(line, MAXLINE, ficpar); */
                   10766:     /*   fputs(line,stdout); */
                   10767:     /*   fputs(line,ficparo); */
                   10768:     /* } */
                   10769:     /* ungetc(c,ficpar); */
1.126     brouard  10770:     
                   10771:     estepm=0;
1.209     brouard  10772:     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  10773:       
                   10774:       if (num_filled != 6) {
                   10775:        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);
                   10776:        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);
                   10777:        goto end;
                   10778:       }
                   10779:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10780:     }
                   10781:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10782:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10783:     
1.209     brouard  10784:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10785:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10786:     if (fage <= 2) {
                   10787:       bage = ageminpar;
                   10788:       fage = agemaxpar;
                   10789:     }
                   10790:     
                   10791:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10792:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10793:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10794:                
1.186     brouard  10795:     /* Other stuffs, more or less useful */    
1.126     brouard  10796:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10797:       ungetc(c,ficpar);
                   10798:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10799:       fputs(line,stdout);
1.126     brouard  10800:       fputs(line,ficparo);
                   10801:     }
                   10802:     ungetc(c,ficpar);
                   10803:     
                   10804:     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);
                   10805:     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);
                   10806:     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);
                   10807:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10808:     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);
                   10809:     
                   10810:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10811:       ungetc(c,ficpar);
                   10812:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10813:       fputs(line,stdout);
1.126     brouard  10814:       fputs(line,ficparo);
                   10815:     }
                   10816:     ungetc(c,ficpar);
                   10817:     
                   10818:     
                   10819:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10820:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10821:     
                   10822:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10823:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10824:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10825:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10826:     
                   10827:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10828:       ungetc(c,ficpar);
                   10829:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10830:       fputs(line,stdout);
1.238     brouard  10831:       fputs(line,ficres);
1.126     brouard  10832:       fputs(line,ficparo);
                   10833:     }
                   10834:     ungetc(c,ficpar);
                   10835:     
                   10836:     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);
                   10837:     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);
                   10838:     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);
                   10839:     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);
                   10840:     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);
                   10841:     /* day and month of proj2 are not used but only year anproj2.*/
                   10842:     
1.217     brouard  10843:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10844:       ungetc(c,ficpar);
                   10845:       fgets(line, MAXLINE, ficpar);
                   10846:       fputs(line,stdout);
                   10847:       fputs(line,ficparo);
1.238     brouard  10848:       fputs(line,ficres);
1.217     brouard  10849:     }
                   10850:     ungetc(c,ficpar);
                   10851:     
                   10852:     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  10853:     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);
                   10854:     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);
                   10855:     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  10856:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10857:     
1.230     brouard  10858:     /* Results */
1.235     brouard  10859:     nresult=0;
1.230     brouard  10860:     while(fgets(line, MAXLINE, ficpar)) {
                   10861:       /* If line starts with a # it is a comment */
                   10862:       if (line[0] == '#') {
                   10863:        numlinepar++;
                   10864:        fputs(line,stdout);
                   10865:        fputs(line,ficparo);
                   10866:        fputs(line,ficlog);
1.238     brouard  10867:        fputs(line,ficres);
1.230     brouard  10868:        continue;
                   10869:       }else
                   10870:        break;
                   10871:     }
1.240   ! brouard  10872:     if (!feof(ficpar))
1.230     brouard  10873:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240   ! brouard  10874:       if (num_filled == 0){
1.230     brouard  10875:        resultline[0]='\0';
1.240   ! brouard  10876:       break;
        !          10877:       } else if (num_filled != 1){
1.230     brouard  10878:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10879:       }
1.235     brouard  10880:       nresult++; /* Sum of resultlines */
                   10881:       printf("Result %d: result=%s\n",nresult, resultline);
                   10882:       if(nresult > MAXRESULTLINES){
                   10883:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10884:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10885:        goto end;
                   10886:       }
                   10887:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  10888:       fprintf(ficparo,"result: %s\n",resultline);
                   10889:       fprintf(ficres,"result: %s\n",resultline);
                   10890:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  10891:       while(fgets(line, MAXLINE, ficpar)) {
                   10892:        /* If line starts with a # it is a comment */
                   10893:        if (line[0] == '#') {
                   10894:          numlinepar++;
                   10895:          fputs(line,stdout);
                   10896:          fputs(line,ficparo);
1.238     brouard  10897:          fputs(line,ficres);
1.230     brouard  10898:          fputs(line,ficlog);
                   10899:          continue;
                   10900:        }else
                   10901:          break;
                   10902:       }
                   10903:       if (feof(ficpar))
                   10904:        break;
                   10905:       else{ /* Processess output results for this combination of covariate values */
                   10906:       }                                   
1.240   ! brouard  10907:     } /* end while */
1.230     brouard  10908: 
                   10909: 
1.126     brouard  10910:     
1.230     brouard  10911:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10912:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10913:     
                   10914:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10915:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10916:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10917: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10918: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10919:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10920: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10921: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10922:     }else{
1.218     brouard  10923:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10924:     }
                   10925:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10926:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10927:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10928:                
1.225     brouard  10929:     /*------------ free_vector  -------------*/
                   10930:     /*  chdir(path); */
1.220     brouard  10931:                
1.215     brouard  10932:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10933:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10934:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   10935:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  10936:     free_lvector(num,1,n);
                   10937:     free_vector(agedc,1,n);
                   10938:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   10939:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   10940:     fclose(ficparo);
                   10941:     fclose(ficres);
1.220     brouard  10942:                
                   10943:                
1.186     brouard  10944:     /* Other results (useful)*/
1.220     brouard  10945:                
                   10946:                
1.126     brouard  10947:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  10948:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   10949:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  10950:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  10951:     fclose(ficrespl);
                   10952: 
                   10953:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  10954:     /*#include "hpijx.h"*/
                   10955:     hPijx(p, bage, fage);
1.145     brouard  10956:     fclose(ficrespij);
1.227     brouard  10957:     
1.220     brouard  10958:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  10959:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  10960:     k=1;
1.126     brouard  10961:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  10962:     
1.219     brouard  10963:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  10964:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  10965:     for(i=1;i<=AGESUP;i++)
1.219     brouard  10966:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  10967:        for(k=1;k<=ncovcombmax;k++)
                   10968:          probs[i][j][k]=0.;
1.219     brouard  10969:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   10970:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   10971:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  10972:       for(i=1;i<=AGESUP;i++)
                   10973:        for(j=1;j<=nlstate;j++)
                   10974:          for(k=1;k<=ncovcombmax;k++)
                   10975:            mobaverages[i][j][k]=0.;
1.219     brouard  10976:       mobaverage=mobaverages;
                   10977:       if (mobilav!=0) {
1.235     brouard  10978:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  10979:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   10980:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   10981:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   10982:        }
1.219     brouard  10983:       }
                   10984:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   10985:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10986:       else if (mobilavproj !=0) {
1.235     brouard  10987:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  10988:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   10989:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10990:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10991:        }
1.219     brouard  10992:       }
                   10993:     }/* end if moving average */
1.227     brouard  10994:     
1.126     brouard  10995:     /*---------- Forecasting ------------------*/
                   10996:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   10997:     if(prevfcast==1){
                   10998:       /*    if(stepm ==1){*/
1.225     brouard  10999:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11000:     }
1.217     brouard  11001:     if(backcast==1){
1.219     brouard  11002:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11003:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11004:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11005: 
                   11006:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11007: 
                   11008:       bprlim=matrix(1,nlstate,1,nlstate);
                   11009:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11010:       fclose(ficresplb);
                   11011: 
1.222     brouard  11012:       hBijx(p, bage, fage, mobaverage);
                   11013:       fclose(ficrespijb);
1.219     brouard  11014:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11015: 
                   11016:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11017:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11018:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11019:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11020:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11021:     }
1.217     brouard  11022:     
1.186     brouard  11023:  
                   11024:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11025: 
1.215     brouard  11026:     free_ivector(wav,1,imx);
                   11027:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11028:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11029:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11030:                
                   11031:                
1.127     brouard  11032:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11033:                
1.201     brouard  11034:     strcpy(filerese,"E_");
                   11035:     strcat(filerese,fileresu);
1.126     brouard  11036:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11037:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11038:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11039:     }
1.208     brouard  11040:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11041:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11042: 
                   11043:     pstamp(ficreseij);
1.219     brouard  11044:                
1.235     brouard  11045:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11046:     if (cptcovn < 1){i1=1;}
                   11047:     
                   11048:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11049:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11050:       if(TKresult[nres]!= k)
                   11051:        continue;
1.219     brouard  11052:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11053:       printf("\n#****** ");
1.225     brouard  11054:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11055:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11056:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11057:       }
                   11058:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11059:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11060:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11061:       }
                   11062:       fprintf(ficreseij,"******\n");
1.235     brouard  11063:       printf("******\n");
1.219     brouard  11064:       
                   11065:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11066:       oldm=oldms;savm=savms;
1.235     brouard  11067:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11068:       
1.219     brouard  11069:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11070:     }
                   11071:     fclose(ficreseij);
1.208     brouard  11072:     printf("done evsij\n");fflush(stdout);
                   11073:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11074:                
1.227     brouard  11075:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11076:                
                   11077:                
1.201     brouard  11078:     strcpy(filerest,"T_");
                   11079:     strcat(filerest,fileresu);
1.127     brouard  11080:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11081:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11082:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11083:     }
1.208     brouard  11084:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11085:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11086:                
1.126     brouard  11087: 
1.201     brouard  11088:     strcpy(fileresstde,"STDE_");
                   11089:     strcat(fileresstde,fileresu);
1.126     brouard  11090:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11091:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11092:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11093:     }
1.227     brouard  11094:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11095:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11096: 
1.201     brouard  11097:     strcpy(filerescve,"CVE_");
                   11098:     strcat(filerescve,fileresu);
1.126     brouard  11099:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11100:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11101:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11102:     }
1.227     brouard  11103:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11104:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11105: 
1.201     brouard  11106:     strcpy(fileresv,"V_");
                   11107:     strcat(fileresv,fileresu);
1.126     brouard  11108:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11109:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11110:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11111:     }
1.227     brouard  11112:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11113:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11114: 
1.145     brouard  11115:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11116:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11117:           
1.235     brouard  11118:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11119:     if (cptcovn < 1){i1=1;}
                   11120:     
                   11121:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11122:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11123:       if(TKresult[nres]!= k)
                   11124:        continue;
                   11125:       printf("\n#****** Selected:");
                   11126:       fprintf(ficrest,"\n#****** Selected:");
                   11127:       fprintf(ficlog,"\n#****** Selected:");
1.227     brouard  11128:       for(j=1;j<=cptcoveff;j++){ 
                   11129:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11130:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11131:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11132:       }
1.235     brouard  11133:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11134:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11135:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11136:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11137:       }        
1.208     brouard  11138:       fprintf(ficrest,"******\n");
1.227     brouard  11139:       fprintf(ficlog,"******\n");
                   11140:       printf("******\n");
1.208     brouard  11141:       
                   11142:       fprintf(ficresstdeij,"\n#****** ");
                   11143:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11144:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11145:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11146:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11147:       }
1.235     brouard  11148:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11149:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11150:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11151:       }        
1.208     brouard  11152:       fprintf(ficresstdeij,"******\n");
                   11153:       fprintf(ficrescveij,"******\n");
                   11154:       
                   11155:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11156:       /* pstamp(ficresvij); */
1.225     brouard  11157:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11158:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11159:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11160:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11161:       }        
1.208     brouard  11162:       fprintf(ficresvij,"******\n");
                   11163:       
                   11164:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11165:       oldm=oldms;savm=savms;
1.235     brouard  11166:       printf(" cvevsij ");
                   11167:       fprintf(ficlog, " cvevsij ");
                   11168:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11169:       printf(" end cvevsij \n ");
                   11170:       fprintf(ficlog, " end cvevsij \n ");
                   11171:       
                   11172:       /*
                   11173:        */
                   11174:       /* goto endfree; */
                   11175:       
                   11176:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11177:       pstamp(ficrest);
                   11178:       
                   11179:       
                   11180:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11181:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11182:        cptcod= 0; /* To be deleted */
                   11183:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11184:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11185:        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  11186:        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 ");
                   11187:        if(vpopbased==1)
                   11188:          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);
                   11189:        else
                   11190:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11191:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11192:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11193:        fprintf(ficrest,"\n");
                   11194:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11195:        epj=vector(1,nlstate+1);
                   11196:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11197:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11198:        for(age=bage; age <=fage ;age++){
1.235     brouard  11199:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11200:          if (vpopbased==1) {
                   11201:            if(mobilav ==0){
                   11202:              for(i=1; i<=nlstate;i++)
                   11203:                prlim[i][i]=probs[(int)age][i][k];
                   11204:            }else{ /* mobilav */ 
                   11205:              for(i=1; i<=nlstate;i++)
                   11206:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11207:            }
                   11208:          }
1.219     brouard  11209:          
1.227     brouard  11210:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11211:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11212:          /* printf(" age %4.0f ",age); */
                   11213:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11214:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11215:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11216:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11217:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11218:            }
                   11219:            epj[nlstate+1] +=epj[j];
                   11220:          }
                   11221:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11222:          
1.227     brouard  11223:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11224:            for(j=1;j <=nlstate;j++)
                   11225:              vepp += vareij[i][j][(int)age];
                   11226:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11227:          for(j=1;j <=nlstate;j++){
                   11228:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11229:          }
                   11230:          fprintf(ficrest,"\n");
                   11231:        }
1.208     brouard  11232:       } /* End vpopbased */
                   11233:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11234:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11235:       free_vector(epj,1,nlstate+1);
1.235     brouard  11236:       printf("done selection\n");fflush(stdout);
                   11237:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11238:       
1.145     brouard  11239:       /*}*/
1.235     brouard  11240:     } /* End k selection */
1.227     brouard  11241: 
                   11242:     printf("done State-specific expectancies\n");fflush(stdout);
                   11243:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11244: 
1.126     brouard  11245:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11246:     
1.201     brouard  11247:     strcpy(fileresvpl,"VPL_");
                   11248:     strcat(fileresvpl,fileresu);
1.126     brouard  11249:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11250:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11251:       exit(0);
                   11252:     }
1.208     brouard  11253:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11254:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11255:     
1.145     brouard  11256:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11257:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11258:     
1.235     brouard  11259:     i1=pow(2,cptcoveff);
                   11260:     if (cptcovn < 1){i1=1;}
                   11261: 
                   11262:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11263:     for(k=1; k<=i1;k++){
                   11264:       if(TKresult[nres]!= k)
                   11265:        continue;
1.227     brouard  11266:       fprintf(ficresvpl,"\n#****** ");
                   11267:       printf("\n#****** ");
                   11268:       fprintf(ficlog,"\n#****** ");
                   11269:       for(j=1;j<=cptcoveff;j++) {
                   11270:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11271:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11272:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11273:       }
1.235     brouard  11274:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11275:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11276:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11277:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11278:       }        
1.227     brouard  11279:       fprintf(ficresvpl,"******\n");
                   11280:       printf("******\n");
                   11281:       fprintf(ficlog,"******\n");
                   11282:       
                   11283:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11284:       oldm=oldms;savm=savms;
1.235     brouard  11285:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11286:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11287:       /*}*/
1.126     brouard  11288:     }
1.227     brouard  11289:     
1.126     brouard  11290:     fclose(ficresvpl);
1.208     brouard  11291:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11292:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11293:     
                   11294:     free_vector(weight,1,n);
                   11295:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11296:     free_imatrix(s,1,maxwav+1,1,n);
                   11297:     free_matrix(anint,1,maxwav,1,n); 
                   11298:     free_matrix(mint,1,maxwav,1,n);
                   11299:     free_ivector(cod,1,n);
                   11300:     free_ivector(tab,1,NCOVMAX);
                   11301:     fclose(ficresstdeij);
                   11302:     fclose(ficrescveij);
                   11303:     fclose(ficresvij);
                   11304:     fclose(ficrest);
                   11305:     fclose(ficpar);
                   11306:     
                   11307:     
1.126     brouard  11308:     /*---------- End : free ----------------*/
1.219     brouard  11309:     if (mobilav!=0 ||mobilavproj !=0)
                   11310:       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  11311:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11312:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11313:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11314:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11315:   /* endfree:*/
                   11316:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11317:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11318:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11319:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11320:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11321:   free_matrix(coqvar,1,maxwav,1,n);
                   11322:   free_matrix(covar,0,NCOVMAX,1,n);
                   11323:   free_matrix(matcov,1,npar,1,npar);
                   11324:   free_matrix(hess,1,npar,1,npar);
                   11325:   /*free_vector(delti,1,npar);*/
                   11326:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11327:   free_matrix(agev,1,maxwav,1,imx);
                   11328:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11329:   
                   11330:   free_ivector(ncodemax,1,NCOVMAX);
                   11331:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11332:   free_ivector(Dummy,-1,NCOVMAX);
                   11333:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11334:   free_ivector(DummyV,1,NCOVMAX);
                   11335:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11336:   free_ivector(Typevar,-1,NCOVMAX);
                   11337:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11338:   free_ivector(TvarsQ,1,NCOVMAX);
                   11339:   free_ivector(TvarsQind,1,NCOVMAX);
                   11340:   free_ivector(TvarsD,1,NCOVMAX);
                   11341:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11342:   free_ivector(TvarFD,1,NCOVMAX);
                   11343:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11344:   free_ivector(TvarF,1,NCOVMAX);
                   11345:   free_ivector(TvarFind,1,NCOVMAX);
                   11346:   free_ivector(TvarV,1,NCOVMAX);
                   11347:   free_ivector(TvarVind,1,NCOVMAX);
                   11348:   free_ivector(TvarA,1,NCOVMAX);
                   11349:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11350:   free_ivector(TvarFQ,1,NCOVMAX);
                   11351:   free_ivector(TvarFQind,1,NCOVMAX);
                   11352:   free_ivector(TvarVD,1,NCOVMAX);
                   11353:   free_ivector(TvarVDind,1,NCOVMAX);
                   11354:   free_ivector(TvarVQ,1,NCOVMAX);
                   11355:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11356:   free_ivector(Tvarsel,1,NCOVMAX);
                   11357:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11358:   free_ivector(Tposprod,1,NCOVMAX);
                   11359:   free_ivector(Tprod,1,NCOVMAX);
                   11360:   free_ivector(Tvaraff,1,NCOVMAX);
                   11361:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11362:   free_ivector(Tage,1,NCOVMAX);
                   11363:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11364:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11365:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11366:   
                   11367:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11368:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11369:   fflush(fichtm);
                   11370:   fflush(ficgp);
                   11371:   
1.227     brouard  11372:   
1.126     brouard  11373:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11374:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11375:     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  11376:   }else{
                   11377:     printf("End of Imach\n");
                   11378:     fprintf(ficlog,"End of Imach\n");
                   11379:   }
                   11380:   printf("See log file on %s\n",filelog);
                   11381:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11382:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11383:   rend_time = time(NULL);  
                   11384:   end_time = *localtime(&rend_time);
                   11385:   /* tml = *localtime(&end_time.tm_sec); */
                   11386:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11387:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11388:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11389:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11390:   
1.157     brouard  11391:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11392:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11393:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11394:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11395: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11396:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11397:   fclose(fichtm);
                   11398:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11399:   fclose(fichtmcov);
                   11400:   fclose(ficgp);
                   11401:   fclose(ficlog);
                   11402:   /*------ End -----------*/
1.227     brouard  11403:   
                   11404:   
                   11405:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11406: #ifdef WIN32
1.227     brouard  11407:   if (_chdir(pathcd) != 0)
                   11408:     printf("Can't move to directory %s!\n",path);
                   11409:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11410: #else
1.227     brouard  11411:     if(chdir(pathcd) != 0)
                   11412:       printf("Can't move to directory %s!\n", path);
                   11413:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11414: #endif 
1.126     brouard  11415:     printf("Current directory %s!\n",pathcd);
                   11416:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11417:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11418: #ifdef _WIN32
1.126     brouard  11419:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11420: #endif
                   11421:   if(!stat(plotcmd,&info)){
1.158     brouard  11422:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11423:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11424:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11425:     }else
                   11426:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11427: #ifdef __unix
1.126     brouard  11428:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11429:     if(!stat(plotcmd,&info)){
1.158     brouard  11430:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11431:     }else
                   11432:       strcpy(pplotcmd,plotcmd);
                   11433: #endif
                   11434:   }else
                   11435:     strcpy(pplotcmd,plotcmd);
                   11436:   
                   11437:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11438:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11439:   
1.126     brouard  11440:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11441:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11442:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11443:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11444:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11445:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11446:   }
1.158     brouard  11447:   printf(" Successful, please wait...");
1.126     brouard  11448:   while (z[0] != 'q') {
                   11449:     /* chdir(path); */
1.154     brouard  11450:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11451:     scanf("%s",z);
                   11452: /*     if (z[0] == 'c') system("./imach"); */
                   11453:     if (z[0] == 'e') {
1.158     brouard  11454: #ifdef __APPLE__
1.152     brouard  11455:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11456: #elif __linux
                   11457:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11458: #else
1.152     brouard  11459:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11460: #endif
                   11461:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11462:       system(pplotcmd);
1.126     brouard  11463:     }
                   11464:     else if (z[0] == 'g') system(plotcmd);
                   11465:     else if (z[0] == 'q') exit(0);
                   11466:   }
1.227     brouard  11467: end:
1.126     brouard  11468:   while (z[0] != 'q') {
1.195     brouard  11469:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11470:     scanf("%s",z);
                   11471:   }
                   11472: }

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