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

1.238   ! brouard     1: /* $Id: imach.c,v 1.237 2016/08/26 09:20:19 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.238   ! brouard     4:   Revision 1.237  2016/08/26 09:20:19  brouard
        !             5:   Summary: to valgrind
        !             6: 
1.237     brouard     7:   Revision 1.236  2016/08/25 10:50:18  brouard
                      8:   *** empty log message ***
                      9: 
1.236     brouard    10:   Revision 1.235  2016/08/25 06:59:23  brouard
                     11:   *** empty log message ***
                     12: 
1.235     brouard    13:   Revision 1.234  2016/08/23 16:51:20  brouard
                     14:   *** empty log message ***
                     15: 
1.234     brouard    16:   Revision 1.233  2016/08/23 07:40:50  brouard
                     17:   Summary: not working
                     18: 
1.233     brouard    19:   Revision 1.232  2016/08/22 14:20:21  brouard
                     20:   Summary: not working
                     21: 
1.232     brouard    22:   Revision 1.231  2016/08/22 07:17:15  brouard
                     23:   Summary: not working
                     24: 
1.231     brouard    25:   Revision 1.230  2016/08/22 06:55:53  brouard
                     26:   Summary: Not working
                     27: 
1.230     brouard    28:   Revision 1.229  2016/07/23 09:45:53  brouard
                     29:   Summary: Completing for func too
                     30: 
1.229     brouard    31:   Revision 1.228  2016/07/22 17:45:30  brouard
                     32:   Summary: Fixing some arrays, still debugging
                     33: 
1.227     brouard    34:   Revision 1.226  2016/07/12 18:42:34  brouard
                     35:   Summary: temp
                     36: 
1.226     brouard    37:   Revision 1.225  2016/07/12 08:40:03  brouard
                     38:   Summary: saving but not running
                     39: 
1.225     brouard    40:   Revision 1.224  2016/07/01 13:16:01  brouard
                     41:   Summary: Fixes
                     42: 
1.224     brouard    43:   Revision 1.223  2016/02/19 09:23:35  brouard
                     44:   Summary: temporary
                     45: 
1.223     brouard    46:   Revision 1.222  2016/02/17 08:14:50  brouard
                     47:   Summary: Probably last 0.98 stable version 0.98r6
                     48: 
1.222     brouard    49:   Revision 1.221  2016/02/15 23:35:36  brouard
                     50:   Summary: minor bug
                     51: 
1.220     brouard    52:   Revision 1.219  2016/02/15 00:48:12  brouard
                     53:   *** empty log message ***
                     54: 
1.219     brouard    55:   Revision 1.218  2016/02/12 11:29:23  brouard
                     56:   Summary: 0.99 Back projections
                     57: 
1.218     brouard    58:   Revision 1.217  2015/12/23 17:18:31  brouard
                     59:   Summary: Experimental backcast
                     60: 
1.217     brouard    61:   Revision 1.216  2015/12/18 17:32:11  brouard
                     62:   Summary: 0.98r4 Warning and status=-2
                     63: 
                     64:   Version 0.98r4 is now:
                     65:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     66:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     67:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     68: 
1.216     brouard    69:   Revision 1.215  2015/12/16 08:52:24  brouard
                     70:   Summary: 0.98r4 working
                     71: 
1.215     brouard    72:   Revision 1.214  2015/12/16 06:57:54  brouard
                     73:   Summary: temporary not working
                     74: 
1.214     brouard    75:   Revision 1.213  2015/12/11 18:22:17  brouard
                     76:   Summary: 0.98r4
                     77: 
1.213     brouard    78:   Revision 1.212  2015/11/21 12:47:24  brouard
                     79:   Summary: minor typo
                     80: 
1.212     brouard    81:   Revision 1.211  2015/11/21 12:41:11  brouard
                     82:   Summary: 0.98r3 with some graph of projected cross-sectional
                     83: 
                     84:   Author: Nicolas Brouard
                     85: 
1.211     brouard    86:   Revision 1.210  2015/11/18 17:41:20  brouard
                     87:   Summary: Start working on projected prevalences
                     88: 
1.210     brouard    89:   Revision 1.209  2015/11/17 22:12:03  brouard
                     90:   Summary: Adding ftolpl parameter
                     91:   Author: N Brouard
                     92: 
                     93:   We had difficulties to get smoothed confidence intervals. It was due
                     94:   to the period prevalence which wasn't computed accurately. The inner
                     95:   parameter ftolpl is now an outer parameter of the .imach parameter
                     96:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     97:   computation are long.
                     98: 
1.209     brouard    99:   Revision 1.208  2015/11/17 14:31:57  brouard
                    100:   Summary: temporary
                    101: 
1.208     brouard   102:   Revision 1.207  2015/10/27 17:36:57  brouard
                    103:   *** empty log message ***
                    104: 
1.207     brouard   105:   Revision 1.206  2015/10/24 07:14:11  brouard
                    106:   *** empty log message ***
                    107: 
1.206     brouard   108:   Revision 1.205  2015/10/23 15:50:53  brouard
                    109:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    110: 
1.205     brouard   111:   Revision 1.204  2015/10/01 16:20:26  brouard
                    112:   Summary: Some new graphs of contribution to likelihood
                    113: 
1.204     brouard   114:   Revision 1.203  2015/09/30 17:45:14  brouard
                    115:   Summary: looking at better estimation of the hessian
                    116: 
                    117:   Also a better criteria for convergence to the period prevalence And
                    118:   therefore adding the number of years needed to converge. (The
                    119:   prevalence in any alive state shold sum to one
                    120: 
1.203     brouard   121:   Revision 1.202  2015/09/22 19:45:16  brouard
                    122:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    123: 
1.202     brouard   124:   Revision 1.201  2015/09/15 17:34:58  brouard
                    125:   Summary: 0.98r0
                    126: 
                    127:   - Some new graphs like suvival functions
                    128:   - Some bugs fixed like model=1+age+V2.
                    129: 
1.201     brouard   130:   Revision 1.200  2015/09/09 16:53:55  brouard
                    131:   Summary: Big bug thanks to Flavia
                    132: 
                    133:   Even model=1+age+V2. did not work anymore
                    134: 
1.200     brouard   135:   Revision 1.199  2015/09/07 14:09:23  brouard
                    136:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    137: 
1.199     brouard   138:   Revision 1.198  2015/09/03 07:14:39  brouard
                    139:   Summary: 0.98q5 Flavia
                    140: 
1.198     brouard   141:   Revision 1.197  2015/09/01 18:24:39  brouard
                    142:   *** empty log message ***
                    143: 
1.197     brouard   144:   Revision 1.196  2015/08/18 23:17:52  brouard
                    145:   Summary: 0.98q5
                    146: 
1.196     brouard   147:   Revision 1.195  2015/08/18 16:28:39  brouard
                    148:   Summary: Adding a hack for testing purpose
                    149: 
                    150:   After reading the title, ftol and model lines, if the comment line has
                    151:   a q, starting with #q, the answer at the end of the run is quit. It
                    152:   permits to run test files in batch with ctest. The former workaround was
                    153:   $ echo q | imach foo.imach
                    154: 
1.195     brouard   155:   Revision 1.194  2015/08/18 13:32:00  brouard
                    156:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    157: 
1.194     brouard   158:   Revision 1.193  2015/08/04 07:17:42  brouard
                    159:   Summary: 0.98q4
                    160: 
1.193     brouard   161:   Revision 1.192  2015/07/16 16:49:02  brouard
                    162:   Summary: Fixing some outputs
                    163: 
1.192     brouard   164:   Revision 1.191  2015/07/14 10:00:33  brouard
                    165:   Summary: Some fixes
                    166: 
1.191     brouard   167:   Revision 1.190  2015/05/05 08:51:13  brouard
                    168:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    169: 
                    170:   Fix 1+age+.
                    171: 
1.190     brouard   172:   Revision 1.189  2015/04/30 14:45:16  brouard
                    173:   Summary: 0.98q2
                    174: 
1.189     brouard   175:   Revision 1.188  2015/04/30 08:27:53  brouard
                    176:   *** empty log message ***
                    177: 
1.188     brouard   178:   Revision 1.187  2015/04/29 09:11:15  brouard
                    179:   *** empty log message ***
                    180: 
1.187     brouard   181:   Revision 1.186  2015/04/23 12:01:52  brouard
                    182:   Summary: V1*age is working now, version 0.98q1
                    183: 
                    184:   Some codes had been disabled in order to simplify and Vn*age was
                    185:   working in the optimization phase, ie, giving correct MLE parameters,
                    186:   but, as usual, outputs were not correct and program core dumped.
                    187: 
1.186     brouard   188:   Revision 1.185  2015/03/11 13:26:42  brouard
                    189:   Summary: Inclusion of compile and links command line for Intel Compiler
                    190: 
1.185     brouard   191:   Revision 1.184  2015/03/11 11:52:39  brouard
                    192:   Summary: Back from Windows 8. Intel Compiler
                    193: 
1.184     brouard   194:   Revision 1.183  2015/03/10 20:34:32  brouard
                    195:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    196: 
                    197:   We use directest instead of original Powell test; probably no
                    198:   incidence on the results, but better justifications;
                    199:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    200:   wrong results.
                    201: 
1.183     brouard   202:   Revision 1.182  2015/02/12 08:19:57  brouard
                    203:   Summary: Trying to keep directest which seems simpler and more general
                    204:   Author: Nicolas Brouard
                    205: 
1.182     brouard   206:   Revision 1.181  2015/02/11 23:22:24  brouard
                    207:   Summary: Comments on Powell added
                    208: 
                    209:   Author:
                    210: 
1.181     brouard   211:   Revision 1.180  2015/02/11 17:33:45  brouard
                    212:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    213: 
1.180     brouard   214:   Revision 1.179  2015/01/04 09:57:06  brouard
                    215:   Summary: back to OS/X
                    216: 
1.179     brouard   217:   Revision 1.178  2015/01/04 09:35:48  brouard
                    218:   *** empty log message ***
                    219: 
1.178     brouard   220:   Revision 1.177  2015/01/03 18:40:56  brouard
                    221:   Summary: Still testing ilc32 on OSX
                    222: 
1.177     brouard   223:   Revision 1.176  2015/01/03 16:45:04  brouard
                    224:   *** empty log message ***
                    225: 
1.176     brouard   226:   Revision 1.175  2015/01/03 16:33:42  brouard
                    227:   *** empty log message ***
                    228: 
1.175     brouard   229:   Revision 1.174  2015/01/03 16:15:49  brouard
                    230:   Summary: Still in cross-compilation
                    231: 
1.174     brouard   232:   Revision 1.173  2015/01/03 12:06:26  brouard
                    233:   Summary: trying to detect cross-compilation
                    234: 
1.173     brouard   235:   Revision 1.172  2014/12/27 12:07:47  brouard
                    236:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    237: 
1.172     brouard   238:   Revision 1.171  2014/12/23 13:26:59  brouard
                    239:   Summary: Back from Visual C
                    240: 
                    241:   Still problem with utsname.h on Windows
                    242: 
1.171     brouard   243:   Revision 1.170  2014/12/23 11:17:12  brouard
                    244:   Summary: Cleaning some \%% back to %%
                    245: 
                    246:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    247: 
1.170     brouard   248:   Revision 1.169  2014/12/22 23:08:31  brouard
                    249:   Summary: 0.98p
                    250: 
                    251:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    252: 
1.169     brouard   253:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   254:   Summary: update
1.169     brouard   255: 
1.168     brouard   256:   Revision 1.167  2014/12/22 13:50:56  brouard
                    257:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    258: 
                    259:   Testing on Linux 64
                    260: 
1.167     brouard   261:   Revision 1.166  2014/12/22 11:40:47  brouard
                    262:   *** empty log message ***
                    263: 
1.166     brouard   264:   Revision 1.165  2014/12/16 11:20:36  brouard
                    265:   Summary: After compiling on Visual C
                    266: 
                    267:   * imach.c (Module): Merging 1.61 to 1.162
                    268: 
1.165     brouard   269:   Revision 1.164  2014/12/16 10:52:11  brouard
                    270:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    271: 
                    272:   * imach.c (Module): Merging 1.61 to 1.162
                    273: 
1.164     brouard   274:   Revision 1.163  2014/12/16 10:30:11  brouard
                    275:   * imach.c (Module): Merging 1.61 to 1.162
                    276: 
1.163     brouard   277:   Revision 1.162  2014/09/25 11:43:39  brouard
                    278:   Summary: temporary backup 0.99!
                    279: 
1.162     brouard   280:   Revision 1.1  2014/09/16 11:06:58  brouard
                    281:   Summary: With some code (wrong) for nlopt
                    282: 
                    283:   Author:
                    284: 
                    285:   Revision 1.161  2014/09/15 20:41:41  brouard
                    286:   Summary: Problem with macro SQR on Intel compiler
                    287: 
1.161     brouard   288:   Revision 1.160  2014/09/02 09:24:05  brouard
                    289:   *** empty log message ***
                    290: 
1.160     brouard   291:   Revision 1.159  2014/09/01 10:34:10  brouard
                    292:   Summary: WIN32
                    293:   Author: Brouard
                    294: 
1.159     brouard   295:   Revision 1.158  2014/08/27 17:11:51  brouard
                    296:   *** empty log message ***
                    297: 
1.158     brouard   298:   Revision 1.157  2014/08/27 16:26:55  brouard
                    299:   Summary: Preparing windows Visual studio version
                    300:   Author: Brouard
                    301: 
                    302:   In order to compile on Visual studio, time.h is now correct and time_t
                    303:   and tm struct should be used. difftime should be used but sometimes I
                    304:   just make the differences in raw time format (time(&now).
                    305:   Trying to suppress #ifdef LINUX
                    306:   Add xdg-open for __linux in order to open default browser.
                    307: 
1.157     brouard   308:   Revision 1.156  2014/08/25 20:10:10  brouard
                    309:   *** empty log message ***
                    310: 
1.156     brouard   311:   Revision 1.155  2014/08/25 18:32:34  brouard
                    312:   Summary: New compile, minor changes
                    313:   Author: Brouard
                    314: 
1.155     brouard   315:   Revision 1.154  2014/06/20 17:32:08  brouard
                    316:   Summary: Outputs now all graphs of convergence to period prevalence
                    317: 
1.154     brouard   318:   Revision 1.153  2014/06/20 16:45:46  brouard
                    319:   Summary: If 3 live state, convergence to period prevalence on same graph
                    320:   Author: Brouard
                    321: 
1.153     brouard   322:   Revision 1.152  2014/06/18 17:54:09  brouard
                    323:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    324: 
1.152     brouard   325:   Revision 1.151  2014/06/18 16:43:30  brouard
                    326:   *** empty log message ***
                    327: 
1.151     brouard   328:   Revision 1.150  2014/06/18 16:42:35  brouard
                    329:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    330:   Author: brouard
                    331: 
1.150     brouard   332:   Revision 1.149  2014/06/18 15:51:14  brouard
                    333:   Summary: Some fixes in parameter files errors
                    334:   Author: Nicolas Brouard
                    335: 
1.149     brouard   336:   Revision 1.148  2014/06/17 17:38:48  brouard
                    337:   Summary: Nothing new
                    338:   Author: Brouard
                    339: 
                    340:   Just a new packaging for OS/X version 0.98nS
                    341: 
1.148     brouard   342:   Revision 1.147  2014/06/16 10:33:11  brouard
                    343:   *** empty log message ***
                    344: 
1.147     brouard   345:   Revision 1.146  2014/06/16 10:20:28  brouard
                    346:   Summary: Merge
                    347:   Author: Brouard
                    348: 
                    349:   Merge, before building revised version.
                    350: 
1.146     brouard   351:   Revision 1.145  2014/06/10 21:23:15  brouard
                    352:   Summary: Debugging with valgrind
                    353:   Author: Nicolas Brouard
                    354: 
                    355:   Lot of changes in order to output the results with some covariates
                    356:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    357:   improve the code.
                    358:   No more memory valgrind error but a lot has to be done in order to
                    359:   continue the work of splitting the code into subroutines.
                    360:   Also, decodemodel has been improved. Tricode is still not
                    361:   optimal. nbcode should be improved. Documentation has been added in
                    362:   the source code.
                    363: 
1.144     brouard   364:   Revision 1.143  2014/01/26 09:45:38  brouard
                    365:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    366: 
                    367:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    368:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    369: 
1.143     brouard   370:   Revision 1.142  2014/01/26 03:57:36  brouard
                    371:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    372: 
                    373:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    374: 
1.142     brouard   375:   Revision 1.141  2014/01/26 02:42:01  brouard
                    376:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    377: 
1.141     brouard   378:   Revision 1.140  2011/09/02 10:37:54  brouard
                    379:   Summary: times.h is ok with mingw32 now.
                    380: 
1.140     brouard   381:   Revision 1.139  2010/06/14 07:50:17  brouard
                    382:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    383:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    384: 
1.139     brouard   385:   Revision 1.138  2010/04/30 18:19:40  brouard
                    386:   *** empty log message ***
                    387: 
1.138     brouard   388:   Revision 1.137  2010/04/29 18:11:38  brouard
                    389:   (Module): Checking covariates for more complex models
                    390:   than V1+V2. A lot of change to be done. Unstable.
                    391: 
1.137     brouard   392:   Revision 1.136  2010/04/26 20:30:53  brouard
                    393:   (Module): merging some libgsl code. Fixing computation
                    394:   of likelione (using inter/intrapolation if mle = 0) in order to
                    395:   get same likelihood as if mle=1.
                    396:   Some cleaning of code and comments added.
                    397: 
1.136     brouard   398:   Revision 1.135  2009/10/29 15:33:14  brouard
                    399:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    400: 
1.135     brouard   401:   Revision 1.134  2009/10/29 13:18:53  brouard
                    402:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    403: 
1.134     brouard   404:   Revision 1.133  2009/07/06 10:21:25  brouard
                    405:   just nforces
                    406: 
1.133     brouard   407:   Revision 1.132  2009/07/06 08:22:05  brouard
                    408:   Many tings
                    409: 
1.132     brouard   410:   Revision 1.131  2009/06/20 16:22:47  brouard
                    411:   Some dimensions resccaled
                    412: 
1.131     brouard   413:   Revision 1.130  2009/05/26 06:44:34  brouard
                    414:   (Module): Max Covariate is now set to 20 instead of 8. A
                    415:   lot of cleaning with variables initialized to 0. Trying to make
                    416:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    417: 
1.130     brouard   418:   Revision 1.129  2007/08/31 13:49:27  lievre
                    419:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    420: 
1.129     lievre    421:   Revision 1.128  2006/06/30 13:02:05  brouard
                    422:   (Module): Clarifications on computing e.j
                    423: 
1.128     brouard   424:   Revision 1.127  2006/04/28 18:11:50  brouard
                    425:   (Module): Yes the sum of survivors was wrong since
                    426:   imach-114 because nhstepm was no more computed in the age
                    427:   loop. Now we define nhstepma in the age loop.
                    428:   (Module): In order to speed up (in case of numerous covariates) we
                    429:   compute health expectancies (without variances) in a first step
                    430:   and then all the health expectancies with variances or standard
                    431:   deviation (needs data from the Hessian matrices) which slows the
                    432:   computation.
                    433:   In the future we should be able to stop the program is only health
                    434:   expectancies and graph are needed without standard deviations.
                    435: 
1.127     brouard   436:   Revision 1.126  2006/04/28 17:23:28  brouard
                    437:   (Module): Yes the sum of survivors was wrong since
                    438:   imach-114 because nhstepm was no more computed in the age
                    439:   loop. Now we define nhstepma in the age loop.
                    440:   Version 0.98h
                    441: 
1.126     brouard   442:   Revision 1.125  2006/04/04 15:20:31  lievre
                    443:   Errors in calculation of health expectancies. Age was not initialized.
                    444:   Forecasting file added.
                    445: 
                    446:   Revision 1.124  2006/03/22 17:13:53  lievre
                    447:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    448:   The log-likelihood is printed in the log file
                    449: 
                    450:   Revision 1.123  2006/03/20 10:52:43  brouard
                    451:   * imach.c (Module): <title> changed, corresponds to .htm file
                    452:   name. <head> headers where missing.
                    453: 
                    454:   * imach.c (Module): Weights can have a decimal point as for
                    455:   English (a comma might work with a correct LC_NUMERIC environment,
                    456:   otherwise the weight is truncated).
                    457:   Modification of warning when the covariates values are not 0 or
                    458:   1.
                    459:   Version 0.98g
                    460: 
                    461:   Revision 1.122  2006/03/20 09:45:41  brouard
                    462:   (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.121  2006/03/16 17:45:01  lievre
                    470:   * imach.c (Module): Comments concerning covariates added
                    471: 
                    472:   * imach.c (Module): refinements in the computation of lli if
                    473:   status=-2 in order to have more reliable computation if stepm is
                    474:   not 1 month. Version 0.98f
                    475: 
                    476:   Revision 1.120  2006/03/16 15:10:38  lievre
                    477:   (Module): refinements in the computation of lli if
                    478:   status=-2 in order to have more reliable computation if stepm is
                    479:   not 1 month. Version 0.98f
                    480: 
                    481:   Revision 1.119  2006/03/15 17:42:26  brouard
                    482:   (Module): Bug if status = -2, the loglikelihood was
                    483:   computed as likelihood omitting the logarithm. Version O.98e
                    484: 
                    485:   Revision 1.118  2006/03/14 18:20:07  brouard
                    486:   (Module): varevsij Comments added explaining the second
                    487:   table of variances if popbased=1 .
                    488:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    489:   (Module): Function pstamp added
                    490:   (Module): Version 0.98d
                    491: 
                    492:   Revision 1.117  2006/03/14 17:16:22  brouard
                    493:   (Module): varevsij Comments added explaining the second
                    494:   table of variances if popbased=1 .
                    495:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    496:   (Module): Function pstamp added
                    497:   (Module): Version 0.98d
                    498: 
                    499:   Revision 1.116  2006/03/06 10:29:27  brouard
                    500:   (Module): Variance-covariance wrong links and
                    501:   varian-covariance of ej. is needed (Saito).
                    502: 
                    503:   Revision 1.115  2006/02/27 12:17:45  brouard
                    504:   (Module): One freematrix added in mlikeli! 0.98c
                    505: 
                    506:   Revision 1.114  2006/02/26 12:57:58  brouard
                    507:   (Module): Some improvements in processing parameter
                    508:   filename with strsep.
                    509: 
                    510:   Revision 1.113  2006/02/24 14:20:24  brouard
                    511:   (Module): Memory leaks checks with valgrind and:
                    512:   datafile was not closed, some imatrix were not freed and on matrix
                    513:   allocation too.
                    514: 
                    515:   Revision 1.112  2006/01/30 09:55:26  brouard
                    516:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    517: 
                    518:   Revision 1.111  2006/01/25 20:38:18  brouard
                    519:   (Module): Lots of cleaning and bugs added (Gompertz)
                    520:   (Module): Comments can be added in data file. Missing date values
                    521:   can be a simple dot '.'.
                    522: 
                    523:   Revision 1.110  2006/01/25 00:51:50  brouard
                    524:   (Module): Lots of cleaning and bugs added (Gompertz)
                    525: 
                    526:   Revision 1.109  2006/01/24 19:37:15  brouard
                    527:   (Module): Comments (lines starting with a #) are allowed in data.
                    528: 
                    529:   Revision 1.108  2006/01/19 18:05:42  lievre
                    530:   Gnuplot problem appeared...
                    531:   To be fixed
                    532: 
                    533:   Revision 1.107  2006/01/19 16:20:37  brouard
                    534:   Test existence of gnuplot in imach path
                    535: 
                    536:   Revision 1.106  2006/01/19 13:24:36  brouard
                    537:   Some cleaning and links added in html output
                    538: 
                    539:   Revision 1.105  2006/01/05 20:23:19  lievre
                    540:   *** empty log message ***
                    541: 
                    542:   Revision 1.104  2005/09/30 16:11:43  lievre
                    543:   (Module): sump fixed, loop imx fixed, and simplifications.
                    544:   (Module): If the status is missing at the last wave but we know
                    545:   that the person is alive, then we can code his/her status as -2
                    546:   (instead of missing=-1 in earlier versions) and his/her
                    547:   contributions to the likelihood is 1 - Prob of dying from last
                    548:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    549:   the healthy state at last known wave). Version is 0.98
                    550: 
                    551:   Revision 1.103  2005/09/30 15:54:49  lievre
                    552:   (Module): sump fixed, loop imx fixed, and simplifications.
                    553: 
                    554:   Revision 1.102  2004/09/15 17:31:30  brouard
                    555:   Add the possibility to read data file including tab characters.
                    556: 
                    557:   Revision 1.101  2004/09/15 10:38:38  brouard
                    558:   Fix on curr_time
                    559: 
                    560:   Revision 1.100  2004/07/12 18:29:06  brouard
                    561:   Add version for Mac OS X. Just define UNIX in Makefile
                    562: 
                    563:   Revision 1.99  2004/06/05 08:57:40  brouard
                    564:   *** empty log message ***
                    565: 
                    566:   Revision 1.98  2004/05/16 15:05:56  brouard
                    567:   New version 0.97 . First attempt to estimate force of mortality
                    568:   directly from the data i.e. without the need of knowing the health
                    569:   state at each age, but using a Gompertz model: log u =a + b*age .
                    570:   This is the basic analysis of mortality and should be done before any
                    571:   other analysis, in order to test if the mortality estimated from the
                    572:   cross-longitudinal survey is different from the mortality estimated
                    573:   from other sources like vital statistic data.
                    574: 
                    575:   The same imach parameter file can be used but the option for mle should be -3.
                    576: 
1.133     brouard   577:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   578:   former routines in order to include the new code within the former code.
                    579: 
                    580:   The output is very simple: only an estimate of the intercept and of
                    581:   the slope with 95% confident intervals.
                    582: 
                    583:   Current limitations:
                    584:   A) Even if you enter covariates, i.e. with the
                    585:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    586:   B) There is no computation of Life Expectancy nor Life Table.
                    587: 
                    588:   Revision 1.97  2004/02/20 13:25:42  lievre
                    589:   Version 0.96d. Population forecasting command line is (temporarily)
                    590:   suppressed.
                    591: 
                    592:   Revision 1.96  2003/07/15 15:38:55  brouard
                    593:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    594:   rewritten within the same printf. Workaround: many printfs.
                    595: 
                    596:   Revision 1.95  2003/07/08 07:54:34  brouard
                    597:   * imach.c (Repository):
                    598:   (Repository): Using imachwizard code to output a more meaningful covariance
                    599:   matrix (cov(a12,c31) instead of numbers.
                    600: 
                    601:   Revision 1.94  2003/06/27 13:00:02  brouard
                    602:   Just cleaning
                    603: 
                    604:   Revision 1.93  2003/06/25 16:33:55  brouard
                    605:   (Module): On windows (cygwin) function asctime_r doesn't
                    606:   exist so I changed back to asctime which exists.
                    607:   (Module): Version 0.96b
                    608: 
                    609:   Revision 1.92  2003/06/25 16:30:45  brouard
                    610:   (Module): On windows (cygwin) function asctime_r doesn't
                    611:   exist so I changed back to asctime which exists.
                    612: 
                    613:   Revision 1.91  2003/06/25 15:30:29  brouard
                    614:   * imach.c (Repository): Duplicated warning errors corrected.
                    615:   (Repository): Elapsed time after each iteration is now output. It
                    616:   helps to forecast when convergence will be reached. Elapsed time
                    617:   is stamped in powell.  We created a new html file for the graphs
                    618:   concerning matrix of covariance. It has extension -cov.htm.
                    619: 
                    620:   Revision 1.90  2003/06/24 12:34:15  brouard
                    621:   (Module): Some bugs corrected for windows. Also, when
                    622:   mle=-1 a template is output in file "or"mypar.txt with the design
                    623:   of the covariance matrix to be input.
                    624: 
                    625:   Revision 1.89  2003/06/24 12:30:52  brouard
                    626:   (Module): Some bugs corrected for windows. Also, when
                    627:   mle=-1 a template is output in file "or"mypar.txt with the design
                    628:   of the covariance matrix to be input.
                    629: 
                    630:   Revision 1.88  2003/06/23 17:54:56  brouard
                    631:   * 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.
                    632: 
                    633:   Revision 1.87  2003/06/18 12:26:01  brouard
                    634:   Version 0.96
                    635: 
                    636:   Revision 1.86  2003/06/17 20:04:08  brouard
                    637:   (Module): Change position of html and gnuplot routines and added
                    638:   routine fileappend.
                    639: 
                    640:   Revision 1.85  2003/06/17 13:12:43  brouard
                    641:   * imach.c (Repository): Check when date of death was earlier that
                    642:   current date of interview. It may happen when the death was just
                    643:   prior to the death. In this case, dh was negative and likelihood
                    644:   was wrong (infinity). We still send an "Error" but patch by
                    645:   assuming that the date of death was just one stepm after the
                    646:   interview.
                    647:   (Repository): Because some people have very long ID (first column)
                    648:   we changed int to long in num[] and we added a new lvector for
                    649:   memory allocation. But we also truncated to 8 characters (left
                    650:   truncation)
                    651:   (Repository): No more line truncation errors.
                    652: 
                    653:   Revision 1.84  2003/06/13 21:44:43  brouard
                    654:   * imach.c (Repository): Replace "freqsummary" at a correct
                    655:   place. It differs from routine "prevalence" which may be called
                    656:   many times. Probs is memory consuming and must be used with
                    657:   parcimony.
                    658:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    659: 
                    660:   Revision 1.83  2003/06/10 13:39:11  lievre
                    661:   *** empty log message ***
                    662: 
                    663:   Revision 1.82  2003/06/05 15:57:20  brouard
                    664:   Add log in  imach.c and  fullversion number is now printed.
                    665: 
                    666: */
                    667: /*
                    668:    Interpolated Markov Chain
                    669: 
                    670:   Short summary of the programme:
                    671:   
1.227     brouard   672:   This program computes Healthy Life Expectancies or State-specific
                    673:   (if states aren't health statuses) Expectancies from
                    674:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    675: 
                    676:   -1- a first survey ("cross") where individuals from different ages
                    677:   are interviewed on their health status or degree of disability (in
                    678:   the case of a health survey which is our main interest)
                    679: 
                    680:   -2- at least a second wave of interviews ("longitudinal") which
                    681:   measure each change (if any) in individual health status.  Health
                    682:   expectancies are computed from the time spent in each health state
                    683:   according to a model. More health states you consider, more time is
                    684:   necessary to reach the Maximum Likelihood of the parameters involved
                    685:   in the model.  The simplest model is the multinomial logistic model
                    686:   where pij is the probability to be observed in state j at the second
                    687:   wave conditional to be observed in state i at the first
                    688:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    689:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    690:   have a more complex model than "constant and age", you should modify
                    691:   the program where the markup *Covariates have to be included here
                    692:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   693:   convergence.
                    694: 
                    695:   The advantage of this computer programme, compared to a simple
                    696:   multinomial logistic model, is clear when the delay between waves is not
                    697:   identical for each individual. Also, if a individual missed an
                    698:   intermediate interview, the information is lost, but taken into
                    699:   account using an interpolation or extrapolation.  
                    700: 
                    701:   hPijx is the probability to be observed in state i at age x+h
                    702:   conditional to the observed state i at age x. The delay 'h' can be
                    703:   split into an exact number (nh*stepm) of unobserved intermediate
                    704:   states. This elementary transition (by month, quarter,
                    705:   semester or year) is modelled as a multinomial logistic.  The hPx
                    706:   matrix is simply the matrix product of nh*stepm elementary matrices
                    707:   and the contribution of each individual to the likelihood is simply
                    708:   hPijx.
                    709: 
                    710:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   711:   of the life expectancies. It also computes the period (stable) prevalence.
                    712: 
                    713: Back prevalence and projections:
1.227     brouard   714: 
                    715:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    716:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    717:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    718:    mobilavproj)
                    719: 
                    720:     Computes the back prevalence limit for any combination of
                    721:     covariate values k at any age between ageminpar and agemaxpar and
                    722:     returns it in **bprlim. In the loops,
                    723: 
                    724:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    725:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    726: 
                    727:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   728:    Computes for any combination of covariates k and any age between bage and fage 
                    729:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    730:                        oldm=oldms;savm=savms;
1.227     brouard   731: 
                    732:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   733:      Computes the transition matrix starting at age 'age' over
                    734:      'nhstepm*hstepm*stepm' months (i.e. until
                    735:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   736:      nhstepm*hstepm matrices. 
                    737: 
                    738:      Returns p3mat[i][j][h] after calling
                    739:      p3mat[i][j][h]=matprod2(newm,
                    740:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    741:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    742:      oldm);
1.226     brouard   743: 
                    744: Important routines
                    745: 
                    746: - func (or funcone), computes logit (pij) distinguishing
                    747:   o fixed variables (single or product dummies or quantitative);
                    748:   o varying variables by:
                    749:    (1) wave (single, product dummies, quantitative), 
                    750:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    751:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    752:        % varying dummy (not done) or quantitative (not done);
                    753: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    754:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    755: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    756:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    757:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   758: 
1.226     brouard   759: 
                    760:   
1.133     brouard   761:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    762:            Institut national d'études démographiques, Paris.
1.126     brouard   763:   This software have been partly granted by Euro-REVES, a concerted action
                    764:   from the European Union.
                    765:   It is copyrighted identically to a GNU software product, ie programme and
                    766:   software can be distributed freely for non commercial use. Latest version
                    767:   can be accessed at http://euroreves.ined.fr/imach .
                    768: 
                    769:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    770:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    771:   
                    772:   **********************************************************************/
                    773: /*
                    774:   main
                    775:   read parameterfile
                    776:   read datafile
                    777:   concatwav
                    778:   freqsummary
                    779:   if (mle >= 1)
                    780:     mlikeli
                    781:   print results files
                    782:   if mle==1 
                    783:      computes hessian
                    784:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    785:       begin-prev-date,...
                    786:   open gnuplot file
                    787:   open html file
1.145     brouard   788:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    789:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    790:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    791:     freexexit2 possible for memory heap.
                    792: 
                    793:   h Pij x                         | pij_nom  ficrestpij
                    794:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    795:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    796:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    797: 
                    798:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    799:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    800:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    801:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    802:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    803: 
1.126     brouard   804:   forecasting if prevfcast==1 prevforecast call prevalence()
                    805:   health expectancies
                    806:   Variance-covariance of DFLE
                    807:   prevalence()
                    808:    movingaverage()
                    809:   varevsij() 
                    810:   if popbased==1 varevsij(,popbased)
                    811:   total life expectancies
                    812:   Variance of period (stable) prevalence
                    813:  end
                    814: */
                    815: 
1.187     brouard   816: /* #define DEBUG */
                    817: /* #define DEBUGBRENT */
1.203     brouard   818: /* #define DEBUGLINMIN */
                    819: /* #define DEBUGHESS */
                    820: #define DEBUGHESSIJ
1.224     brouard   821: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   822: #define POWELL /* Instead of NLOPT */
1.224     brouard   823: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   824: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    825: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   826: 
                    827: #include <math.h>
                    828: #include <stdio.h>
                    829: #include <stdlib.h>
                    830: #include <string.h>
1.226     brouard   831: #include <ctype.h>
1.159     brouard   832: 
                    833: #ifdef _WIN32
                    834: #include <io.h>
1.172     brouard   835: #include <windows.h>
                    836: #include <tchar.h>
1.159     brouard   837: #else
1.126     brouard   838: #include <unistd.h>
1.159     brouard   839: #endif
1.126     brouard   840: 
                    841: #include <limits.h>
                    842: #include <sys/types.h>
1.171     brouard   843: 
                    844: #if defined(__GNUC__)
                    845: #include <sys/utsname.h> /* Doesn't work on Windows */
                    846: #endif
                    847: 
1.126     brouard   848: #include <sys/stat.h>
                    849: #include <errno.h>
1.159     brouard   850: /* extern int errno; */
1.126     brouard   851: 
1.157     brouard   852: /* #ifdef LINUX */
                    853: /* #include <time.h> */
                    854: /* #include "timeval.h" */
                    855: /* #else */
                    856: /* #include <sys/time.h> */
                    857: /* #endif */
                    858: 
1.126     brouard   859: #include <time.h>
                    860: 
1.136     brouard   861: #ifdef GSL
                    862: #include <gsl/gsl_errno.h>
                    863: #include <gsl/gsl_multimin.h>
                    864: #endif
                    865: 
1.167     brouard   866: 
1.162     brouard   867: #ifdef NLOPT
                    868: #include <nlopt.h>
                    869: typedef struct {
                    870:   double (* function)(double [] );
                    871: } myfunc_data ;
                    872: #endif
                    873: 
1.126     brouard   874: /* #include <libintl.h> */
                    875: /* #define _(String) gettext (String) */
                    876: 
1.141     brouard   877: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   878: 
                    879: #define GNUPLOTPROGRAM "gnuplot"
                    880: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    881: #define FILENAMELENGTH 132
                    882: 
                    883: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    884: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    885: 
1.144     brouard   886: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    887: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   888: 
                    889: #define NINTERVMAX 8
1.144     brouard   890: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    891: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    892: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   893: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   894: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    895: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   896: #define MAXN 20000
1.144     brouard   897: #define YEARM 12. /**< Number of months per year */
1.218     brouard   898: /* #define AGESUP 130 */
                    899: #define AGESUP 150
                    900: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   901: #define AGEBASE 40
1.194     brouard   902: #define AGEOVERFLOW 1.e20
1.164     brouard   903: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   904: #ifdef _WIN32
                    905: #define DIRSEPARATOR '\\'
                    906: #define CHARSEPARATOR "\\"
                    907: #define ODIRSEPARATOR '/'
                    908: #else
1.126     brouard   909: #define DIRSEPARATOR '/'
                    910: #define CHARSEPARATOR "/"
                    911: #define ODIRSEPARATOR '\\'
                    912: #endif
                    913: 
1.238   ! brouard   914: /* $Id: imach.c,v 1.237 2016/08/26 09:20:19 brouard Exp $ */
1.126     brouard   915: /* $State: Exp $ */
1.196     brouard   916: #include "version.h"
                    917: char version[]=__IMACH_VERSION__;
1.224     brouard   918: 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.238   ! brouard   919: char fullversion[]="$Revision: 1.237 $ $Date: 2016/08/26 09:20:19 $"; 
1.126     brouard   920: char strstart[80];
                    921: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   922: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   923: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   924: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    925: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    926: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   927: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    928: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   929: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    930: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    931: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   932: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    933: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   934: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   935: int nsd=0; /**< Total number of single dummy variables (output) */
                    936: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   937: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   938: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   939: int ntveff=0; /**< ntveff number of effective time varying variables */
                    940: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   941: int cptcov=0; /* Working variable */
1.218     brouard   942: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   943: int npar=NPARMAX;
                    944: int nlstate=2; /* Number of live states */
                    945: int ndeath=1; /* Number of dead states */
1.130     brouard   946: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   947: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   948: int popbased=0;
                    949: 
                    950: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   951: int maxwav=0; /* Maxim number of waves */
                    952: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    953: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    954: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   955:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   956: int mle=1, weightopt=0;
1.126     brouard   957: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    958: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    959: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    960:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   961: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   962: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    963: 
1.130     brouard   964: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   965: double **matprod2(); /* test */
1.126     brouard   966: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    967: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   968: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    969: 
1.136     brouard   970: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   971: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   972: FILE *ficlog, *ficrespow;
1.130     brouard   973: int globpr=0; /* Global variable for printing or not */
1.126     brouard   974: double fretone; /* Only one call to likelihood */
1.130     brouard   975: long ipmx=0; /* Number of contributions */
1.126     brouard   976: double sw; /* Sum of weights */
                    977: char filerespow[FILENAMELENGTH];
                    978: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    979: FILE *ficresilk;
                    980: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    981: FILE *ficresprobmorprev;
                    982: FILE *fichtm, *fichtmcov; /* Html File */
                    983: FILE *ficreseij;
                    984: char filerese[FILENAMELENGTH];
                    985: FILE *ficresstdeij;
                    986: char fileresstde[FILENAMELENGTH];
                    987: FILE *ficrescveij;
                    988: char filerescve[FILENAMELENGTH];
                    989: FILE  *ficresvij;
                    990: char fileresv[FILENAMELENGTH];
                    991: FILE  *ficresvpl;
                    992: char fileresvpl[FILENAMELENGTH];
                    993: char title[MAXLINE];
1.234     brouard   994: char model[MAXLINE]; /**< The model line */
1.217     brouard   995: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   996: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    997: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    998: char command[FILENAMELENGTH];
                    999: int  outcmd=0;
                   1000: 
1.217     brouard  1001: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1002: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1003: char filelog[FILENAMELENGTH]; /* Log file */
                   1004: char filerest[FILENAMELENGTH];
                   1005: char fileregp[FILENAMELENGTH];
                   1006: char popfile[FILENAMELENGTH];
                   1007: 
                   1008: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1009: 
1.157     brouard  1010: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1011: /* struct timezone tzp; */
                   1012: /* extern int gettimeofday(); */
                   1013: struct tm tml, *gmtime(), *localtime();
                   1014: 
                   1015: extern time_t time();
                   1016: 
                   1017: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1018: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1019: struct tm tm;
                   1020: 
1.126     brouard  1021: char strcurr[80], strfor[80];
                   1022: 
                   1023: char *endptr;
                   1024: long lval;
                   1025: double dval;
                   1026: 
                   1027: #define NR_END 1
                   1028: #define FREE_ARG char*
                   1029: #define FTOL 1.0e-10
                   1030: 
                   1031: #define NRANSI 
                   1032: #define ITMAX 200 
                   1033: 
                   1034: #define TOL 2.0e-4 
                   1035: 
                   1036: #define CGOLD 0.3819660 
                   1037: #define ZEPS 1.0e-10 
                   1038: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1039: 
                   1040: #define GOLD 1.618034 
                   1041: #define GLIMIT 100.0 
                   1042: #define TINY 1.0e-20 
                   1043: 
                   1044: static double maxarg1,maxarg2;
                   1045: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1046: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1047:   
                   1048: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1049: #define rint(a) floor(a+0.5)
1.166     brouard  1050: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1051: #define mytinydouble 1.0e-16
1.166     brouard  1052: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1053: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1054: /* static double dsqrarg; */
                   1055: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1056: static double sqrarg;
                   1057: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1058: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1059: int agegomp= AGEGOMP;
                   1060: 
                   1061: int imx; 
                   1062: int stepm=1;
                   1063: /* Stepm, step in month: minimum step interpolation*/
                   1064: 
                   1065: int estepm;
                   1066: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1067: 
                   1068: int m,nb;
                   1069: long *num;
1.197     brouard  1070: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1071: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1072:                   covariate for which somebody answered excluding 
                   1073:                   undefined. Usually 2: 0 and 1. */
                   1074: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1075:                             covariate for which somebody answered including 
                   1076:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1077: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1078: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1079: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1080: double *ageexmed,*agecens;
                   1081: double dateintmean=0;
                   1082: 
                   1083: double *weight;
                   1084: int **s; /* Status */
1.141     brouard  1085: double *agedc;
1.145     brouard  1086: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1087:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1088:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1089: double **coqvar; /* Fixed quantitative covariate iqv */
                   1090: double ***cotvar; /* Time varying covariate itv */
                   1091: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1092: double  idx; 
                   1093: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1094: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1095: /*k          1  2   3   4     5    6    7     8    9 */
                   1096: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1097: /* Tndvar[k]    1   2   3               4          5 */
                   1098: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1099: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1100: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1101: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1102: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1103: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1104: /* Tprod[i]=k           4               7            */
                   1105: /* Tage[i]=k                  5               8      */
                   1106: /* */
                   1107: /* Type                    */
                   1108: /* V         1  2  3  4  5 */
                   1109: /*           F  F  V  V  V */
                   1110: /*           D  Q  D  D  Q */
                   1111: /*                         */
                   1112: int *TvarsD;
                   1113: int *TvarsDind;
                   1114: int *TvarsQ;
                   1115: int *TvarsQind;
                   1116: 
1.235     brouard  1117: #define MAXRESULTLINES 10
                   1118: int nresult=0;
                   1119: int TKresult[MAXRESULTLINES];
1.237     brouard  1120: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1121: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1122: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1123: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1124: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1125: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1126: 
1.234     brouard  1127: /* 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  1128: 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 */
                   1129: 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 */
                   1130: 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 */
                   1131: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1132: 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 */
                   1133: 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  1134: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1135: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1136: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1137: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1138: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1139: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1140: 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 */
                   1141: 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 */
                   1142: 
1.230     brouard  1143: int *Tvarsel; /**< Selected covariates for output */
                   1144: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1145: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1146: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1147: 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  1148: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
        !          1149: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1150: int *Tage;
1.227     brouard  1151: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1152: 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  1153: 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*/ 
                   1154: 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  1155: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1156: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1157: int **Tvard;
                   1158: int *Tprod;/**< Gives the k position of the k1 product */
1.238   ! brouard  1159: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1160: int *Tposprod; /**< Gives the k1 product from the k position */
1.238   ! brouard  1161:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
        !          1162:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1163: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1164: double *lsurv, *lpop, *tpop;
                   1165: 
1.231     brouard  1166: #define FD 1; /* Fixed dummy covariate */
                   1167: #define FQ 2; /* Fixed quantitative covariate */
                   1168: #define FP 3; /* Fixed product covariate */
                   1169: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1170: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1171: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1172: #define VD 10; /* Varying dummy covariate */
                   1173: #define VQ 11; /* Varying quantitative covariate */
                   1174: #define VP 12; /* Varying product covariate */
                   1175: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1176: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1177: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1178: #define APFD 16; /* Age product * fixed dummy covariate */
                   1179: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1180: #define APVD 18; /* Age product * varying dummy covariate */
                   1181: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1182: 
                   1183: #define FTYPE 1; /* Fixed covariate */
                   1184: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1185: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1186: 
                   1187: struct kmodel{
                   1188:        int maintype; /* main type */
                   1189:        int subtype; /* subtype */
                   1190: };
                   1191: struct kmodel modell[NCOVMAX];
                   1192: 
1.143     brouard  1193: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1194: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1195: 
                   1196: /**************** split *************************/
                   1197: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1198: {
                   1199:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1200:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1201:   */ 
                   1202:   char *ss;                            /* pointer */
1.186     brouard  1203:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1204: 
                   1205:   l1 = strlen(path );                  /* length of path */
                   1206:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1207:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1208:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1209:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1210:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1211:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1212:     /* get current working directory */
                   1213:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1214: #ifdef WIN32
                   1215:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1216: #else
                   1217:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1218: #endif
1.126     brouard  1219:       return( GLOCK_ERROR_GETCWD );
                   1220:     }
                   1221:     /* got dirc from getcwd*/
                   1222:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1223:   } else {                             /* strip directory from path */
1.126     brouard  1224:     ss++;                              /* after this, the filename */
                   1225:     l2 = strlen( ss );                 /* length of filename */
                   1226:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1227:     strcpy( name, ss );                /* save file name */
                   1228:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1229:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1230:     printf(" DIRC2 = %s \n",dirc);
                   1231:   }
                   1232:   /* We add a separator at the end of dirc if not exists */
                   1233:   l1 = strlen( dirc );                 /* length of directory */
                   1234:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1235:     dirc[l1] =  DIRSEPARATOR;
                   1236:     dirc[l1+1] = 0; 
                   1237:     printf(" DIRC3 = %s \n",dirc);
                   1238:   }
                   1239:   ss = strrchr( name, '.' );           /* find last / */
                   1240:   if (ss >0){
                   1241:     ss++;
                   1242:     strcpy(ext,ss);                    /* save extension */
                   1243:     l1= strlen( name);
                   1244:     l2= strlen(ss)+1;
                   1245:     strncpy( finame, name, l1-l2);
                   1246:     finame[l1-l2]= 0;
                   1247:   }
                   1248: 
                   1249:   return( 0 );                         /* we're done */
                   1250: }
                   1251: 
                   1252: 
                   1253: /******************************************/
                   1254: 
                   1255: void replace_back_to_slash(char *s, char*t)
                   1256: {
                   1257:   int i;
                   1258:   int lg=0;
                   1259:   i=0;
                   1260:   lg=strlen(t);
                   1261:   for(i=0; i<= lg; i++) {
                   1262:     (s[i] = t[i]);
                   1263:     if (t[i]== '\\') s[i]='/';
                   1264:   }
                   1265: }
                   1266: 
1.132     brouard  1267: char *trimbb(char *out, char *in)
1.137     brouard  1268: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1269:   char *s;
                   1270:   s=out;
                   1271:   while (*in != '\0'){
1.137     brouard  1272:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1273:       in++;
                   1274:     }
                   1275:     *out++ = *in++;
                   1276:   }
                   1277:   *out='\0';
                   1278:   return s;
                   1279: }
                   1280: 
1.187     brouard  1281: /* char *substrchaine(char *out, char *in, char *chain) */
                   1282: /* { */
                   1283: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1284: /*   char *s, *t; */
                   1285: /*   t=in;s=out; */
                   1286: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1287: /*     *out++ = *in++; */
                   1288: /*   } */
                   1289: 
                   1290: /*   /\* *in matches *chain *\/ */
                   1291: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1292: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1293: /*   } */
                   1294: /*   in--; chain--; */
                   1295: /*   while ( (*in != '\0')){ */
                   1296: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1297: /*     *out++ = *in++; */
                   1298: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1299: /*   } */
                   1300: /*   *out='\0'; */
                   1301: /*   out=s; */
                   1302: /*   return out; */
                   1303: /* } */
                   1304: char *substrchaine(char *out, char *in, char *chain)
                   1305: {
                   1306:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1307:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1308: 
                   1309:   char *strloc;
                   1310: 
                   1311:   strcpy (out, in); 
                   1312:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1313:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1314:   if(strloc != NULL){ 
                   1315:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1316:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1317:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1318:   }
                   1319:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1320:   return out;
                   1321: }
                   1322: 
                   1323: 
1.145     brouard  1324: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1325: {
1.187     brouard  1326:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1327:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1328:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1329:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1330:   */
1.160     brouard  1331:   char *s, *t;
1.145     brouard  1332:   t=in;s=in;
                   1333:   while ((*in != occ) && (*in != '\0')){
                   1334:     *alocc++ = *in++;
                   1335:   }
                   1336:   if( *in == occ){
                   1337:     *(alocc)='\0';
                   1338:     s=++in;
                   1339:   }
                   1340:  
                   1341:   if (s == t) {/* occ not found */
                   1342:     *(alocc-(in-s))='\0';
                   1343:     in=s;
                   1344:   }
                   1345:   while ( *in != '\0'){
                   1346:     *blocc++ = *in++;
                   1347:   }
                   1348: 
                   1349:   *blocc='\0';
                   1350:   return t;
                   1351: }
1.137     brouard  1352: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1353: {
1.187     brouard  1354:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1355:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1356:      gives blocc="abcdef2ghi" and alocc="j".
                   1357:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1358:   */
                   1359:   char *s, *t;
                   1360:   t=in;s=in;
                   1361:   while (*in != '\0'){
                   1362:     while( *in == occ){
                   1363:       *blocc++ = *in++;
                   1364:       s=in;
                   1365:     }
                   1366:     *blocc++ = *in++;
                   1367:   }
                   1368:   if (s == t) /* occ not found */
                   1369:     *(blocc-(in-s))='\0';
                   1370:   else
                   1371:     *(blocc-(in-s)-1)='\0';
                   1372:   in=s;
                   1373:   while ( *in != '\0'){
                   1374:     *alocc++ = *in++;
                   1375:   }
                   1376: 
                   1377:   *alocc='\0';
                   1378:   return s;
                   1379: }
                   1380: 
1.126     brouard  1381: int nbocc(char *s, char occ)
                   1382: {
                   1383:   int i,j=0;
                   1384:   int lg=20;
                   1385:   i=0;
                   1386:   lg=strlen(s);
                   1387:   for(i=0; i<= lg; i++) {
1.234     brouard  1388:     if  (s[i] == occ ) j++;
1.126     brouard  1389:   }
                   1390:   return j;
                   1391: }
                   1392: 
1.137     brouard  1393: /* void cutv(char *u,char *v, char*t, char occ) */
                   1394: /* { */
                   1395: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1396: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1397: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1398: /*   int i,lg,j,p=0; */
                   1399: /*   i=0; */
                   1400: /*   lg=strlen(t); */
                   1401: /*   for(j=0; j<=lg-1; j++) { */
                   1402: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1403: /*   } */
1.126     brouard  1404: 
1.137     brouard  1405: /*   for(j=0; j<p; j++) { */
                   1406: /*     (u[j] = t[j]); */
                   1407: /*   } */
                   1408: /*      u[p]='\0'; */
1.126     brouard  1409: 
1.137     brouard  1410: /*    for(j=0; j<= lg; j++) { */
                   1411: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1412: /*   } */
                   1413: /* } */
1.126     brouard  1414: 
1.160     brouard  1415: #ifdef _WIN32
                   1416: char * strsep(char **pp, const char *delim)
                   1417: {
                   1418:   char *p, *q;
                   1419:          
                   1420:   if ((p = *pp) == NULL)
                   1421:     return 0;
                   1422:   if ((q = strpbrk (p, delim)) != NULL)
                   1423:   {
                   1424:     *pp = q + 1;
                   1425:     *q = '\0';
                   1426:   }
                   1427:   else
                   1428:     *pp = 0;
                   1429:   return p;
                   1430: }
                   1431: #endif
                   1432: 
1.126     brouard  1433: /********************** nrerror ********************/
                   1434: 
                   1435: void nrerror(char error_text[])
                   1436: {
                   1437:   fprintf(stderr,"ERREUR ...\n");
                   1438:   fprintf(stderr,"%s\n",error_text);
                   1439:   exit(EXIT_FAILURE);
                   1440: }
                   1441: /*********************** vector *******************/
                   1442: double *vector(int nl, int nh)
                   1443: {
                   1444:   double *v;
                   1445:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1446:   if (!v) nrerror("allocation failure in vector");
                   1447:   return v-nl+NR_END;
                   1448: }
                   1449: 
                   1450: /************************ free vector ******************/
                   1451: void free_vector(double*v, int nl, int nh)
                   1452: {
                   1453:   free((FREE_ARG)(v+nl-NR_END));
                   1454: }
                   1455: 
                   1456: /************************ivector *******************************/
                   1457: int *ivector(long nl,long nh)
                   1458: {
                   1459:   int *v;
                   1460:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1461:   if (!v) nrerror("allocation failure in ivector");
                   1462:   return v-nl+NR_END;
                   1463: }
                   1464: 
                   1465: /******************free ivector **************************/
                   1466: void free_ivector(int *v, long nl, long nh)
                   1467: {
                   1468:   free((FREE_ARG)(v+nl-NR_END));
                   1469: }
                   1470: 
                   1471: /************************lvector *******************************/
                   1472: long *lvector(long nl,long nh)
                   1473: {
                   1474:   long *v;
                   1475:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1476:   if (!v) nrerror("allocation failure in ivector");
                   1477:   return v-nl+NR_END;
                   1478: }
                   1479: 
                   1480: /******************free lvector **************************/
                   1481: void free_lvector(long *v, long nl, long nh)
                   1482: {
                   1483:   free((FREE_ARG)(v+nl-NR_END));
                   1484: }
                   1485: 
                   1486: /******************* imatrix *******************************/
                   1487: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1488:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1489: { 
                   1490:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1491:   int **m; 
                   1492:   
                   1493:   /* allocate pointers to rows */ 
                   1494:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1495:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1496:   m += NR_END; 
                   1497:   m -= nrl; 
                   1498:   
                   1499:   
                   1500:   /* allocate rows and set pointers to them */ 
                   1501:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1502:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1503:   m[nrl] += NR_END; 
                   1504:   m[nrl] -= ncl; 
                   1505:   
                   1506:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1507:   
                   1508:   /* return pointer to array of pointers to rows */ 
                   1509:   return m; 
                   1510: } 
                   1511: 
                   1512: /****************** free_imatrix *************************/
                   1513: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1514:       int **m;
                   1515:       long nch,ncl,nrh,nrl; 
                   1516:      /* free an int matrix allocated by imatrix() */ 
                   1517: { 
                   1518:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1519:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1520: } 
                   1521: 
                   1522: /******************* matrix *******************************/
                   1523: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1524: {
                   1525:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1526:   double **m;
                   1527: 
                   1528:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1529:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1530:   m += NR_END;
                   1531:   m -= nrl;
                   1532: 
                   1533:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1534:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1535:   m[nrl] += NR_END;
                   1536:   m[nrl] -= ncl;
                   1537: 
                   1538:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1539:   return m;
1.145     brouard  1540:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1541: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1542: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1543:    */
                   1544: }
                   1545: 
                   1546: /*************************free matrix ************************/
                   1547: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1548: {
                   1549:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1550:   free((FREE_ARG)(m+nrl-NR_END));
                   1551: }
                   1552: 
                   1553: /******************* ma3x *******************************/
                   1554: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1555: {
                   1556:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1557:   double ***m;
                   1558: 
                   1559:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1560:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1561:   m += NR_END;
                   1562:   m -= nrl;
                   1563: 
                   1564:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1565:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1566:   m[nrl] += NR_END;
                   1567:   m[nrl] -= ncl;
                   1568: 
                   1569:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1570: 
                   1571:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1572:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1573:   m[nrl][ncl] += NR_END;
                   1574:   m[nrl][ncl] -= nll;
                   1575:   for (j=ncl+1; j<=nch; j++) 
                   1576:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1577:   
                   1578:   for (i=nrl+1; i<=nrh; i++) {
                   1579:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1580:     for (j=ncl+1; j<=nch; j++) 
                   1581:       m[i][j]=m[i][j-1]+nlay;
                   1582:   }
                   1583:   return m; 
                   1584:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1585:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1586:   */
                   1587: }
                   1588: 
                   1589: /*************************free ma3x ************************/
                   1590: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1591: {
                   1592:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1593:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1594:   free((FREE_ARG)(m+nrl-NR_END));
                   1595: }
                   1596: 
                   1597: /*************** function subdirf ***********/
                   1598: char *subdirf(char fileres[])
                   1599: {
                   1600:   /* Caution optionfilefiname is hidden */
                   1601:   strcpy(tmpout,optionfilefiname);
                   1602:   strcat(tmpout,"/"); /* Add to the right */
                   1603:   strcat(tmpout,fileres);
                   1604:   return tmpout;
                   1605: }
                   1606: 
                   1607: /*************** function subdirf2 ***********/
                   1608: char *subdirf2(char fileres[], char *preop)
                   1609: {
                   1610:   
                   1611:   /* Caution optionfilefiname is hidden */
                   1612:   strcpy(tmpout,optionfilefiname);
                   1613:   strcat(tmpout,"/");
                   1614:   strcat(tmpout,preop);
                   1615:   strcat(tmpout,fileres);
                   1616:   return tmpout;
                   1617: }
                   1618: 
                   1619: /*************** function subdirf3 ***********/
                   1620: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1621: {
                   1622:   
                   1623:   /* Caution optionfilefiname is hidden */
                   1624:   strcpy(tmpout,optionfilefiname);
                   1625:   strcat(tmpout,"/");
                   1626:   strcat(tmpout,preop);
                   1627:   strcat(tmpout,preop2);
                   1628:   strcat(tmpout,fileres);
                   1629:   return tmpout;
                   1630: }
1.213     brouard  1631:  
                   1632: /*************** function subdirfext ***********/
                   1633: char *subdirfext(char fileres[], char *preop, char *postop)
                   1634: {
                   1635:   
                   1636:   strcpy(tmpout,preop);
                   1637:   strcat(tmpout,fileres);
                   1638:   strcat(tmpout,postop);
                   1639:   return tmpout;
                   1640: }
1.126     brouard  1641: 
1.213     brouard  1642: /*************** function subdirfext3 ***********/
                   1643: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1644: {
                   1645:   
                   1646:   /* Caution optionfilefiname is hidden */
                   1647:   strcpy(tmpout,optionfilefiname);
                   1648:   strcat(tmpout,"/");
                   1649:   strcat(tmpout,preop);
                   1650:   strcat(tmpout,fileres);
                   1651:   strcat(tmpout,postop);
                   1652:   return tmpout;
                   1653: }
                   1654:  
1.162     brouard  1655: char *asc_diff_time(long time_sec, char ascdiff[])
                   1656: {
                   1657:   long sec_left, days, hours, minutes;
                   1658:   days = (time_sec) / (60*60*24);
                   1659:   sec_left = (time_sec) % (60*60*24);
                   1660:   hours = (sec_left) / (60*60) ;
                   1661:   sec_left = (sec_left) %(60*60);
                   1662:   minutes = (sec_left) /60;
                   1663:   sec_left = (sec_left) % (60);
                   1664:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1665:   return ascdiff;
                   1666: }
                   1667: 
1.126     brouard  1668: /***************** f1dim *************************/
                   1669: extern int ncom; 
                   1670: extern double *pcom,*xicom;
                   1671: extern double (*nrfunc)(double []); 
                   1672:  
                   1673: double f1dim(double x) 
                   1674: { 
                   1675:   int j; 
                   1676:   double f;
                   1677:   double *xt; 
                   1678:  
                   1679:   xt=vector(1,ncom); 
                   1680:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1681:   f=(*nrfunc)(xt); 
                   1682:   free_vector(xt,1,ncom); 
                   1683:   return f; 
                   1684: } 
                   1685: 
                   1686: /*****************brent *************************/
                   1687: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1688: {
                   1689:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1690:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1691:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1692:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1693:    * returned function value. 
                   1694:   */
1.126     brouard  1695:   int iter; 
                   1696:   double a,b,d,etemp;
1.159     brouard  1697:   double fu=0,fv,fw,fx;
1.164     brouard  1698:   double ftemp=0.;
1.126     brouard  1699:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1700:   double e=0.0; 
                   1701:  
                   1702:   a=(ax < cx ? ax : cx); 
                   1703:   b=(ax > cx ? ax : cx); 
                   1704:   x=w=v=bx; 
                   1705:   fw=fv=fx=(*f)(x); 
                   1706:   for (iter=1;iter<=ITMAX;iter++) { 
                   1707:     xm=0.5*(a+b); 
                   1708:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1709:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1710:     printf(".");fflush(stdout);
                   1711:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1712: #ifdef DEBUGBRENT
1.126     brouard  1713:     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);
                   1714:     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);
                   1715:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1716: #endif
                   1717:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1718:       *xmin=x; 
                   1719:       return fx; 
                   1720:     } 
                   1721:     ftemp=fu;
                   1722:     if (fabs(e) > tol1) { 
                   1723:       r=(x-w)*(fx-fv); 
                   1724:       q=(x-v)*(fx-fw); 
                   1725:       p=(x-v)*q-(x-w)*r; 
                   1726:       q=2.0*(q-r); 
                   1727:       if (q > 0.0) p = -p; 
                   1728:       q=fabs(q); 
                   1729:       etemp=e; 
                   1730:       e=d; 
                   1731:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1732:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1733:       else { 
1.224     brouard  1734:                                d=p/q; 
                   1735:                                u=x+d; 
                   1736:                                if (u-a < tol2 || b-u < tol2) 
                   1737:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1738:       } 
                   1739:     } else { 
                   1740:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1741:     } 
                   1742:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1743:     fu=(*f)(u); 
                   1744:     if (fu <= fx) { 
                   1745:       if (u >= x) a=x; else b=x; 
                   1746:       SHFT(v,w,x,u) 
1.183     brouard  1747:       SHFT(fv,fw,fx,fu) 
                   1748:     } else { 
                   1749:       if (u < x) a=u; else b=u; 
                   1750:       if (fu <= fw || w == x) { 
1.224     brouard  1751:                                v=w; 
                   1752:                                w=u; 
                   1753:                                fv=fw; 
                   1754:                                fw=fu; 
1.183     brouard  1755:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1756:                                v=u; 
                   1757:                                fv=fu; 
1.183     brouard  1758:       } 
                   1759:     } 
1.126     brouard  1760:   } 
                   1761:   nrerror("Too many iterations in brent"); 
                   1762:   *xmin=x; 
                   1763:   return fx; 
                   1764: } 
                   1765: 
                   1766: /****************** mnbrak ***********************/
                   1767: 
                   1768: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1769:            double (*func)(double)) 
1.183     brouard  1770: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1771: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1772: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1773: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1774:    */
1.126     brouard  1775:   double ulim,u,r,q, dum;
                   1776:   double fu; 
1.187     brouard  1777: 
                   1778:   double scale=10.;
                   1779:   int iterscale=0;
                   1780: 
                   1781:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1782:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1783: 
                   1784: 
                   1785:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1786:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1787:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1788:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1789:   /* } */
                   1790: 
1.126     brouard  1791:   if (*fb > *fa) { 
                   1792:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1793:     SHFT(dum,*fb,*fa,dum) 
                   1794:   } 
1.126     brouard  1795:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1796:   *fc=(*func)(*cx); 
1.183     brouard  1797: #ifdef DEBUG
1.224     brouard  1798:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1799:   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  1800: #endif
1.224     brouard  1801:   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  1802:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1803:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1804:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1805:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1806:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1807:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1808:       fu=(*func)(u); 
1.163     brouard  1809: #ifdef DEBUG
                   1810:       /* f(x)=A(x-u)**2+f(u) */
                   1811:       double A, fparabu; 
                   1812:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1813:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1814:       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);
                   1815:       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  1816:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1817:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1818:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1819:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1820: #endif 
1.184     brouard  1821: #ifdef MNBRAKORIGINAL
1.183     brouard  1822: #else
1.191     brouard  1823: /*       if (fu > *fc) { */
                   1824: /* #ifdef DEBUG */
                   1825: /*       printf("mnbrak4  fu > fc \n"); */
                   1826: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1827: /* #endif */
                   1828: /*     /\* 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 *\\/  *\/ */
                   1829: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1830: /*     dum=u; /\* Shifting c and u *\/ */
                   1831: /*     u = *cx; */
                   1832: /*     *cx = dum; */
                   1833: /*     dum = fu; */
                   1834: /*     fu = *fc; */
                   1835: /*     *fc =dum; */
                   1836: /*       } else { /\* end *\/ */
                   1837: /* #ifdef DEBUG */
                   1838: /*       printf("mnbrak3  fu < fc \n"); */
                   1839: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1840: /* #endif */
                   1841: /*     dum=u; /\* Shifting c and u *\/ */
                   1842: /*     u = *cx; */
                   1843: /*     *cx = dum; */
                   1844: /*     dum = fu; */
                   1845: /*     fu = *fc; */
                   1846: /*     *fc =dum; */
                   1847: /*       } */
1.224     brouard  1848: #ifdef DEBUGMNBRAK
                   1849:                 double A, fparabu; 
                   1850:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1851:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1852:      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);
                   1853:      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  1854: #endif
1.191     brouard  1855:       dum=u; /* Shifting c and u */
                   1856:       u = *cx;
                   1857:       *cx = dum;
                   1858:       dum = fu;
                   1859:       fu = *fc;
                   1860:       *fc =dum;
1.183     brouard  1861: #endif
1.162     brouard  1862:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1863: #ifdef DEBUG
1.224     brouard  1864:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1865:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1866: #endif
1.126     brouard  1867:       fu=(*func)(u); 
                   1868:       if (fu < *fc) { 
1.183     brouard  1869: #ifdef DEBUG
1.224     brouard  1870:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1871:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1872: #endif
                   1873:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1874:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1875: #ifdef DEBUG
                   1876:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1877: #endif
                   1878:       } 
1.162     brouard  1879:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1880: #ifdef DEBUG
1.224     brouard  1881:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1882:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1883: #endif
1.126     brouard  1884:       u=ulim; 
                   1885:       fu=(*func)(u); 
1.183     brouard  1886:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1887: #ifdef DEBUG
1.224     brouard  1888:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1889:       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  1890: #endif
1.126     brouard  1891:       u=(*cx)+GOLD*(*cx-*bx); 
                   1892:       fu=(*func)(u); 
1.224     brouard  1893: #ifdef DEBUG
                   1894:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1895:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1896: #endif
1.183     brouard  1897:     } /* end tests */
1.126     brouard  1898:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1899:     SHFT(*fa,*fb,*fc,fu) 
                   1900: #ifdef DEBUG
1.224     brouard  1901:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1902:       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  1903: #endif
                   1904:   } /* 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  1905: } 
                   1906: 
                   1907: /*************** linmin ************************/
1.162     brouard  1908: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1909: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1910: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1911: the value of func at the returned location p . This is actually all accomplished by calling the
                   1912: routines mnbrak and brent .*/
1.126     brouard  1913: int ncom; 
                   1914: double *pcom,*xicom;
                   1915: double (*nrfunc)(double []); 
                   1916:  
1.224     brouard  1917: #ifdef LINMINORIGINAL
1.126     brouard  1918: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1919: #else
                   1920: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1921: #endif
1.126     brouard  1922: { 
                   1923:   double brent(double ax, double bx, double cx, 
                   1924:               double (*f)(double), double tol, double *xmin); 
                   1925:   double f1dim(double x); 
                   1926:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1927:              double *fc, double (*func)(double)); 
                   1928:   int j; 
                   1929:   double xx,xmin,bx,ax; 
                   1930:   double fx,fb,fa;
1.187     brouard  1931: 
1.203     brouard  1932: #ifdef LINMINORIGINAL
                   1933: #else
                   1934:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1935: #endif
                   1936:   
1.126     brouard  1937:   ncom=n; 
                   1938:   pcom=vector(1,n); 
                   1939:   xicom=vector(1,n); 
                   1940:   nrfunc=func; 
                   1941:   for (j=1;j<=n;j++) { 
                   1942:     pcom[j]=p[j]; 
1.202     brouard  1943:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1944:   } 
1.187     brouard  1945: 
1.203     brouard  1946: #ifdef LINMINORIGINAL
                   1947:   xx=1.;
                   1948: #else
                   1949:   axs=0.0;
                   1950:   xxs=1.;
                   1951:   do{
                   1952:     xx= xxs;
                   1953: #endif
1.187     brouard  1954:     ax=0.;
                   1955:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1956:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1957:     /* 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))   */
                   1958:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1959:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1960:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1961:     /* 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  1962: #ifdef LINMINORIGINAL
                   1963: #else
                   1964:     if (fx != fx){
1.224     brouard  1965:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1966:                        printf("|");
                   1967:                        fprintf(ficlog,"|");
1.203     brouard  1968: #ifdef DEBUGLINMIN
1.224     brouard  1969:                        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  1970: #endif
                   1971:     }
1.224     brouard  1972:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1973: #endif
                   1974:   
1.191     brouard  1975: #ifdef DEBUGLINMIN
                   1976:   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  1977:   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  1978: #endif
1.224     brouard  1979: #ifdef LINMINORIGINAL
                   1980: #else
                   1981:        if(fb == fx){ /* Flat function in the direction */
                   1982:                xmin=xx;
                   1983:     *flat=1;
                   1984:        }else{
                   1985:     *flat=0;
                   1986: #endif
                   1987:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  1988:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1989:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1990:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1991:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1992:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1993: #ifdef DEBUG
1.224     brouard  1994:   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);
                   1995:   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);
                   1996: #endif
                   1997: #ifdef LINMINORIGINAL
                   1998: #else
                   1999:                        }
1.126     brouard  2000: #endif
1.191     brouard  2001: #ifdef DEBUGLINMIN
                   2002:   printf("linmin end ");
1.202     brouard  2003:   fprintf(ficlog,"linmin end ");
1.191     brouard  2004: #endif
1.126     brouard  2005:   for (j=1;j<=n;j++) { 
1.203     brouard  2006: #ifdef LINMINORIGINAL
                   2007:     xi[j] *= xmin; 
                   2008: #else
                   2009: #ifdef DEBUGLINMIN
                   2010:     if(xxs <1.0)
                   2011:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2012: #endif
                   2013:     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) */
                   2014: #ifdef DEBUGLINMIN
                   2015:     if(xxs <1.0)
                   2016:       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 );
                   2017: #endif
                   2018: #endif
1.187     brouard  2019:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2020:   } 
1.191     brouard  2021: #ifdef DEBUGLINMIN
1.203     brouard  2022:   printf("\n");
1.191     brouard  2023:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2024:   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  2025:   for (j=1;j<=n;j++) { 
1.202     brouard  2026:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2027:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2028:     if(j % ncovmodel == 0){
1.191     brouard  2029:       printf("\n");
1.202     brouard  2030:       fprintf(ficlog,"\n");
                   2031:     }
1.191     brouard  2032:   }
1.203     brouard  2033: #else
1.191     brouard  2034: #endif
1.126     brouard  2035:   free_vector(xicom,1,n); 
                   2036:   free_vector(pcom,1,n); 
                   2037: } 
                   2038: 
                   2039: 
                   2040: /*************** powell ************************/
1.162     brouard  2041: /*
                   2042: Minimization of a function func of n variables. Input consists of an initial starting point
                   2043: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2044: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2045: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2046: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2047: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2048:  */
1.224     brouard  2049: #ifdef LINMINORIGINAL
                   2050: #else
                   2051:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2052:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2053: #endif
1.126     brouard  2054: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2055:            double (*func)(double [])) 
                   2056: { 
1.224     brouard  2057: #ifdef LINMINORIGINAL
                   2058:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2059:              double (*func)(double [])); 
1.224     brouard  2060: #else 
                   2061:  void linmin(double p[], double xi[], int n, double *fret, 
                   2062:                                                 double (*func)(double []),int *flat); 
                   2063: #endif
1.126     brouard  2064:   int i,ibig,j; 
                   2065:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2066:   double directest;
1.126     brouard  2067:   double fp,fptt;
                   2068:   double *xits;
                   2069:   int niterf, itmp;
1.224     brouard  2070: #ifdef LINMINORIGINAL
                   2071: #else
                   2072: 
                   2073:   flatdir=ivector(1,n); 
                   2074:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2075: #endif
1.126     brouard  2076: 
                   2077:   pt=vector(1,n); 
                   2078:   ptt=vector(1,n); 
                   2079:   xit=vector(1,n); 
                   2080:   xits=vector(1,n); 
                   2081:   *fret=(*func)(p); 
                   2082:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2083:   rcurr_time = time(NULL);  
1.126     brouard  2084:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2085:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2086:     ibig=0; 
                   2087:     del=0.0; 
1.157     brouard  2088:     rlast_time=rcurr_time;
                   2089:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2090:     rcurr_time = time(NULL);  
                   2091:     curr_time = *localtime(&rcurr_time);
                   2092:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2093:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2094: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2095:     for (i=1;i<=n;i++) {
1.126     brouard  2096:       printf(" %d %.12f",i, p[i]);
                   2097:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   2098:       fprintf(ficrespow," %.12lf", p[i]);
                   2099:     }
                   2100:     printf("\n");
                   2101:     fprintf(ficlog,"\n");
                   2102:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2103:     if(*iter <=3){
1.157     brouard  2104:       tml = *localtime(&rcurr_time);
                   2105:       strcpy(strcurr,asctime(&tml));
                   2106:       rforecast_time=rcurr_time; 
1.126     brouard  2107:       itmp = strlen(strcurr);
                   2108:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.224     brouard  2109:                                strcurr[itmp-1]='\0';
1.162     brouard  2110:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2111:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2112:       for(niterf=10;niterf<=30;niterf+=10){
1.224     brouard  2113:                                rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2114:                                forecast_time = *localtime(&rforecast_time);
                   2115:                                strcpy(strfor,asctime(&forecast_time));
                   2116:                                itmp = strlen(strfor);
                   2117:                                if(strfor[itmp-1]=='\n')
                   2118:                                        strfor[itmp-1]='\0';
                   2119:                                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);
                   2120:                                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  2121:       }
                   2122:     }
1.187     brouard  2123:     for (i=1;i<=n;i++) { /* For each direction i */
                   2124:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2125:       fptt=(*fret); 
                   2126: #ifdef DEBUG
1.203     brouard  2127:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2128:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2129: #endif
1.203     brouard  2130:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2131:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2132: #ifdef LINMINORIGINAL
1.188     brouard  2133:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2134: #else
                   2135:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2136:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2137: #endif
                   2138:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2139:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2140:                                /* because that direction will be replaced unless the gain del is small */
                   2141:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2142:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2143:                                /* with the new direction. */
                   2144:                                del=fabs(fptt-(*fret)); 
                   2145:                                ibig=i; 
1.126     brouard  2146:       } 
                   2147: #ifdef DEBUG
                   2148:       printf("%d %.12e",i,(*fret));
                   2149:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2150:       for (j=1;j<=n;j++) {
1.224     brouard  2151:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2152:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2153:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2154:       }
                   2155:       for(j=1;j<=n;j++) {
1.225     brouard  2156:                                printf(" p(%d)=%.12e",j,p[j]);
                   2157:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2158:       }
                   2159:       printf("\n");
                   2160:       fprintf(ficlog,"\n");
                   2161: #endif
1.187     brouard  2162:     } /* end loop on each direction i */
                   2163:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2164:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2165:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2166:       for(j=1;j<=n;j++) {
1.225     brouard  2167:                                if(flatdir[j] >0){
                   2168:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2169:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2170:                                }
                   2171:                                /* printf("\n"); */
                   2172:                                /* fprintf(ficlog,"\n"); */
                   2173:                        }
1.182     brouard  2174:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  2175:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2176:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2177:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2178:       /* decreased of more than 3.84  */
                   2179:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2180:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2181:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2182:                        
1.188     brouard  2183:       /* Starting the program with initial values given by a former maximization will simply change */
                   2184:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2185:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2186:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2187: #ifdef DEBUG
                   2188:       int k[2],l;
                   2189:       k[0]=1;
                   2190:       k[1]=-1;
                   2191:       printf("Max: %.12e",(*func)(p));
                   2192:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2193:       for (j=1;j<=n;j++) {
                   2194:        printf(" %.12e",p[j]);
                   2195:        fprintf(ficlog," %.12e",p[j]);
                   2196:       }
                   2197:       printf("\n");
                   2198:       fprintf(ficlog,"\n");
                   2199:       for(l=0;l<=1;l++) {
                   2200:        for (j=1;j<=n;j++) {
                   2201:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2202:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2203:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2204:        }
                   2205:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2206:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2207:       }
                   2208: #endif
                   2209: 
1.224     brouard  2210: #ifdef LINMINORIGINAL
                   2211: #else
                   2212:       free_ivector(flatdir,1,n); 
                   2213: #endif
1.126     brouard  2214:       free_vector(xit,1,n); 
                   2215:       free_vector(xits,1,n); 
                   2216:       free_vector(ptt,1,n); 
                   2217:       free_vector(pt,1,n); 
                   2218:       return; 
1.192     brouard  2219:     } /* enough precision */ 
1.126     brouard  2220:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2221:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2222:       ptt[j]=2.0*p[j]-pt[j]; 
                   2223:       xit[j]=p[j]-pt[j]; 
                   2224:       pt[j]=p[j]; 
                   2225:     } 
1.181     brouard  2226:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2227: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2228:                if (*iter <=4) {
1.225     brouard  2229: #else
                   2230: #endif
1.224     brouard  2231: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2232: #else
1.161     brouard  2233:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2234: #endif
1.162     brouard  2235:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2236:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2237:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2238:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2239:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2240:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2241:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2242:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2243:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2244:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2245:       /* mu² and del² are equal when f3=f1 */
                   2246:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2247:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2248:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2249:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2250: #ifdef NRCORIGINAL
                   2251:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2252: #else
                   2253:       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  2254:       t= t- del*SQR(fp-fptt);
1.183     brouard  2255: #endif
1.202     brouard  2256:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2257: #ifdef DEBUG
1.181     brouard  2258:       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);
                   2259:       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  2260:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2261:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2262:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2263:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2264:       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);
                   2265:       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);
                   2266: #endif
1.183     brouard  2267: #ifdef POWELLORIGINAL
                   2268:       if (t < 0.0) { /* Then we use it for new direction */
                   2269: #else
1.182     brouard  2270:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2271:                                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  2272:         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  2273:         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  2274:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2275:       } 
1.181     brouard  2276:       if (directest < 0.0) { /* Then we use it for new direction */
                   2277: #endif
1.191     brouard  2278: #ifdef DEBUGLINMIN
1.234     brouard  2279:        printf("Before linmin in direction P%d-P0\n",n);
                   2280:        for (j=1;j<=n;j++) {
                   2281:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2282:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2283:          if(j % ncovmodel == 0){
                   2284:            printf("\n");
                   2285:            fprintf(ficlog,"\n");
                   2286:          }
                   2287:        }
1.224     brouard  2288: #endif
                   2289: #ifdef LINMINORIGINAL
1.234     brouard  2290:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2291: #else
1.234     brouard  2292:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2293:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2294: #endif
1.234     brouard  2295:        
1.191     brouard  2296: #ifdef DEBUGLINMIN
1.234     brouard  2297:        for (j=1;j<=n;j++) { 
                   2298:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2299:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2300:          if(j % ncovmodel == 0){
                   2301:            printf("\n");
                   2302:            fprintf(ficlog,"\n");
                   2303:          }
                   2304:        }
1.224     brouard  2305: #endif
1.234     brouard  2306:        for (j=1;j<=n;j++) { 
                   2307:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2308:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2309:        }
1.224     brouard  2310: #ifdef LINMINORIGINAL
                   2311: #else
1.234     brouard  2312:        for (j=1, flatd=0;j<=n;j++) {
                   2313:          if(flatdir[j]>0)
                   2314:            flatd++;
                   2315:        }
                   2316:        if(flatd >0){
                   2317:          printf("%d flat directions\n",flatd);
                   2318:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2319:          for (j=1;j<=n;j++) { 
                   2320:            if(flatdir[j]>0){
                   2321:              printf("%d ",j);
                   2322:              fprintf(ficlog,"%d ",j);
                   2323:            }
                   2324:          }
                   2325:          printf("\n");
                   2326:          fprintf(ficlog,"\n");
                   2327:        }
1.191     brouard  2328: #endif
1.234     brouard  2329:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2330:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2331:        
1.126     brouard  2332: #ifdef DEBUG
1.234     brouard  2333:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2334:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2335:        for(j=1;j<=n;j++){
                   2336:          printf(" %lf",xit[j]);
                   2337:          fprintf(ficlog," %lf",xit[j]);
                   2338:        }
                   2339:        printf("\n");
                   2340:        fprintf(ficlog,"\n");
1.126     brouard  2341: #endif
1.192     brouard  2342:       } /* end of t or directest negative */
1.224     brouard  2343: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2344: #else
1.234     brouard  2345:       } /* end if (fptt < fp)  */
1.192     brouard  2346: #endif
1.225     brouard  2347: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2348:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2349: #else
1.224     brouard  2350: #endif
1.234     brouard  2351:                } /* loop iteration */ 
1.126     brouard  2352: } 
1.234     brouard  2353:   
1.126     brouard  2354: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2355:   
1.235     brouard  2356:   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  2357:   {
1.235     brouard  2358:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2359:        (and selected quantitative values in nres)
                   2360:        by left multiplying the unit
1.234     brouard  2361:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2362:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2363:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2364:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2365:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2366:   /* Initial matrix pimij */
                   2367:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2368:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2369:   /*  0,                   0                  , 1} */
                   2370:   /*
                   2371:    * and after some iteration: */
                   2372:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2373:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2374:   /*  0,                   0                  , 1} */
                   2375:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2376:   /* {0.51571254859325999, 0.4842874514067399, */
                   2377:   /*  0.51326036147820708, 0.48673963852179264} */
                   2378:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2379:     
1.126     brouard  2380:   int i, ii,j,k;
1.209     brouard  2381:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2382:   /* double **matprod2(); */ /* test */
1.218     brouard  2383:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2384:   double **newm;
1.209     brouard  2385:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2386:   int ncvloop=0;
1.169     brouard  2387:   
1.209     brouard  2388:   min=vector(1,nlstate);
                   2389:   max=vector(1,nlstate);
                   2390:   meandiff=vector(1,nlstate);
                   2391: 
1.218     brouard  2392:        /* Starting with matrix unity */
1.126     brouard  2393:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2394:     for (j=1;j<=nlstate+ndeath;j++){
                   2395:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2396:     }
1.169     brouard  2397:   
                   2398:   cov[1]=1.;
                   2399:   
                   2400:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2401:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2402:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2403:     ncvloop++;
1.126     brouard  2404:     newm=savm;
                   2405:     /* Covariates have to be included here again */
1.138     brouard  2406:     cov[2]=agefin;
1.187     brouard  2407:     if(nagesqr==1)
                   2408:       cov[3]= agefin*agefin;;
1.234     brouard  2409:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2410:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2411:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2412:       /* 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  2413:     }
                   2414:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2415:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2416:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2417:       /* 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  2418:     }
1.237     brouard  2419:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2420:       if(Dummy[Tvar[Tage[k]]]){
                   2421:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2422:       } else{
1.235     brouard  2423:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2424:       }
1.235     brouard  2425:       /* 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  2426:     }
1.237     brouard  2427:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2428:       /* 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  2429:       if(Dummy[Tvard[k][1]==0]){
                   2430:        if(Dummy[Tvard[k][2]==0]){
                   2431:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2432:        }else{
                   2433:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2434:        }
                   2435:       }else{
                   2436:        if(Dummy[Tvard[k][2]==0]){
                   2437:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2438:        }else{
                   2439:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2440:        }
                   2441:       }
1.234     brouard  2442:     }
1.138     brouard  2443:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2444:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2445:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2446:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2447:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2448:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2449:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2450:     
1.126     brouard  2451:     savm=oldm;
                   2452:     oldm=newm;
1.209     brouard  2453: 
                   2454:     for(j=1; j<=nlstate; j++){
                   2455:       max[j]=0.;
                   2456:       min[j]=1.;
                   2457:     }
                   2458:     for(i=1;i<=nlstate;i++){
                   2459:       sumnew=0;
                   2460:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2461:       for(j=1; j<=nlstate; j++){ 
                   2462:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2463:        max[j]=FMAX(max[j],prlim[i][j]);
                   2464:        min[j]=FMIN(min[j],prlim[i][j]);
                   2465:       }
                   2466:     }
                   2467: 
1.126     brouard  2468:     maxmax=0.;
1.209     brouard  2469:     for(j=1; j<=nlstate; j++){
                   2470:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2471:       maxmax=FMAX(maxmax,meandiff[j]);
                   2472:       /* 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  2473:     } /* j loop */
1.203     brouard  2474:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2475:     /* 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  2476:     if(maxmax < ftolpl){
1.209     brouard  2477:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2478:       free_vector(min,1,nlstate);
                   2479:       free_vector(max,1,nlstate);
                   2480:       free_vector(meandiff,1,nlstate);
1.126     brouard  2481:       return prlim;
                   2482:     }
1.169     brouard  2483:   } /* age loop */
1.208     brouard  2484:     /* After some age loop it doesn't converge */
1.209     brouard  2485:   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  2486: 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  2487:   /* 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); */
                   2488:   free_vector(min,1,nlstate);
                   2489:   free_vector(max,1,nlstate);
                   2490:   free_vector(meandiff,1,nlstate);
1.208     brouard  2491:   
1.169     brouard  2492:   return prlim; /* should not reach here */
1.126     brouard  2493: }
                   2494: 
1.217     brouard  2495: 
                   2496:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2497: 
1.218     brouard  2498:  /* 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) */
                   2499:  /* 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) */
                   2500:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2501: {
1.218     brouard  2502:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2503:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2504:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2505:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2506:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2507:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2508:   /* Initial matrix pimij */
                   2509:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2510:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2511:   /*  0,                   0                  , 1} */
                   2512:   /*
                   2513:    * and after some iteration: */
                   2514:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2515:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2516:   /*  0,                   0                  , 1} */
                   2517:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2518:   /* {0.51571254859325999, 0.4842874514067399, */
                   2519:   /*  0.51326036147820708, 0.48673963852179264} */
                   2520:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2521: 
                   2522:   int i, ii,j,k;
                   2523:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2524:   /* double **matprod2(); */ /* test */
                   2525:   double **out, cov[NCOVMAX+1], **bmij();
                   2526:   double **newm;
1.218     brouard  2527:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2528:   double        **oldm, **savm;  /* for use */
                   2529: 
1.217     brouard  2530:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2531:   int ncvloop=0;
                   2532:   
                   2533:   min=vector(1,nlstate);
                   2534:   max=vector(1,nlstate);
                   2535:   meandiff=vector(1,nlstate);
                   2536: 
1.218     brouard  2537:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2538:        oldm=oldms; savm=savms;
                   2539: 
                   2540:        /* Starting with matrix unity */
                   2541:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2542:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2543:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2544:     }
                   2545:   
                   2546:   cov[1]=1.;
                   2547:   
                   2548:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2549:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2550:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2551:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2552:     ncvloop++;
1.218     brouard  2553:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2554:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2555:     /* Covariates have to be included here again */
                   2556:     cov[2]=agefin;
                   2557:     if(nagesqr==1)
                   2558:       cov[3]= agefin*agefin;;
                   2559:     for (k=1; k<=cptcovn;k++) {
                   2560:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2561:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2562:       /* 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])]); */
                   2563:     }
                   2564:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2565:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2566:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2567:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2568:     
                   2569:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2570:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2571:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2572:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2573:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2574:                /* ij should be linked to the correct index of cov */
                   2575:                /* age and covariate values ij are in 'cov', but we need to pass
                   2576:                 * ij for the observed prevalence at age and status and covariate
                   2577:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2578:                 */
                   2579:     /* 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 *\/ */
                   2580:     /* 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 *\/ */
                   2581:     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  2582:     savm=oldm;
                   2583:     oldm=newm;
                   2584:     for(j=1; j<=nlstate; j++){
                   2585:       max[j]=0.;
                   2586:       min[j]=1.;
                   2587:     }
                   2588:     for(j=1; j<=nlstate; j++){ 
                   2589:       for(i=1;i<=nlstate;i++){
1.234     brouard  2590:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2591:        bprlim[i][j]= newm[i][j];
                   2592:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2593:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2594:       }
                   2595:     }
1.218     brouard  2596:                
1.217     brouard  2597:     maxmax=0.;
                   2598:     for(i=1; i<=nlstate; i++){
                   2599:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2600:       maxmax=FMAX(maxmax,meandiff[i]);
                   2601:       /* 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); */
                   2602:     } /* j loop */
                   2603:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2604:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2605:     if(maxmax < ftolpl){
1.220     brouard  2606:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2607:       free_vector(min,1,nlstate);
                   2608:       free_vector(max,1,nlstate);
                   2609:       free_vector(meandiff,1,nlstate);
                   2610:       return bprlim;
                   2611:     }
                   2612:   } /* age loop */
                   2613:     /* After some age loop it doesn't converge */
                   2614:   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\
                   2615: 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);
                   2616:   /* 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); */
                   2617:   free_vector(min,1,nlstate);
                   2618:   free_vector(max,1,nlstate);
                   2619:   free_vector(meandiff,1,nlstate);
                   2620:   
                   2621:   return bprlim; /* should not reach here */
                   2622: }
                   2623: 
1.126     brouard  2624: /*************** transition probabilities ***************/ 
                   2625: 
                   2626: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2627: {
1.138     brouard  2628:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2629:      computes the probability to be observed in state j being in state i by appying the
                   2630:      model to the ncovmodel covariates (including constant and age).
                   2631:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2632:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2633:      ncth covariate in the global vector x is given by the formula:
                   2634:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2635:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2636:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2637:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2638:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2639:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2640:   */
                   2641:   double s1, lnpijopii;
1.126     brouard  2642:   /*double t34;*/
1.164     brouard  2643:   int i,j, nc, ii, jj;
1.126     brouard  2644: 
1.223     brouard  2645:   for(i=1; i<= nlstate; i++){
                   2646:     for(j=1; j<i;j++){
                   2647:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2648:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2649:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2650:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2651:       }
                   2652:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2653:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2654:     }
                   2655:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2656:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2657:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2658:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2659:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2660:       }
                   2661:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2662:     }
                   2663:   }
1.218     brouard  2664:   
1.223     brouard  2665:   for(i=1; i<= nlstate; i++){
                   2666:     s1=0;
                   2667:     for(j=1; j<i; j++){
                   2668:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2669:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2670:     }
                   2671:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2672:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2673:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2674:     }
                   2675:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2676:     ps[i][i]=1./(s1+1.);
                   2677:     /* Computing other pijs */
                   2678:     for(j=1; j<i; j++)
                   2679:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2680:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2681:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2682:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2683:   } /* end i */
1.218     brouard  2684:   
1.223     brouard  2685:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2686:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2687:       ps[ii][jj]=0;
                   2688:       ps[ii][ii]=1;
                   2689:     }
                   2690:   }
1.218     brouard  2691:   
                   2692:   
1.223     brouard  2693:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2694:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2695:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2696:   /*   } */
                   2697:   /*   printf("\n "); */
                   2698:   /* } */
                   2699:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2700:   /*
                   2701:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2702:                goto end;*/
1.223     brouard  2703:   return ps;
1.126     brouard  2704: }
                   2705: 
1.218     brouard  2706: /*************** backward transition probabilities ***************/ 
                   2707: 
                   2708:  /* 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 ) */
                   2709: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2710:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2711: {
1.222     brouard  2712:   /* Computes the backward probability at age agefin and covariate ij
                   2713:    * and returns in **ps as well as **bmij.
                   2714:    */
1.218     brouard  2715:   int i, ii, j,k;
1.222     brouard  2716:   
                   2717:   double **out, **pmij();
                   2718:   double sumnew=0.;
1.218     brouard  2719:   double agefin;
1.222     brouard  2720:   
                   2721:   double **dnewm, **dsavm, **doldm;
                   2722:   double **bbmij;
                   2723:   
1.218     brouard  2724:   doldm=ddoldms; /* global pointers */
1.222     brouard  2725:   dnewm=ddnewms;
                   2726:   dsavm=ddsavms;
                   2727:   
                   2728:   agefin=cov[2];
                   2729:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2730:      the observed prevalence (with this covariate ij) */
                   2731:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2732:   /* We do have the matrix Px in savm  and we need pij */
                   2733:   for (j=1;j<=nlstate+ndeath;j++){
                   2734:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2735:     for (ii=1;ii<=nlstate;ii++){
                   2736:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2737:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2738:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2739:       if(sumnew >= 1.e-10){
                   2740:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2741:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2742:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2743:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2744:        /* }else */
                   2745:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2746:       }else{
                   2747:        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);
                   2748:       }
                   2749:     } /*End ii */
                   2750:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2751:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2752:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2753:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2754:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2755:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2756:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2757:   for (j=1;j<=nlstate+ndeath;j++){
                   2758:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2759:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2760:     }
                   2761:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2762:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2763:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2764:   /* end bmij */
                   2765:   return ps; 
1.218     brouard  2766: }
1.217     brouard  2767: /*************** transition probabilities ***************/ 
                   2768: 
1.218     brouard  2769: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2770: {
                   2771:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2772:      computes the probability to be observed in state j being in state i by appying the
                   2773:      model to the ncovmodel covariates (including constant and age).
                   2774:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2775:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2776:      ncth covariate in the global vector x is given by the formula:
                   2777:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2778:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2779:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2780:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2781:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2782:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2783:   */
                   2784:   double s1, lnpijopii;
                   2785:   /*double t34;*/
                   2786:   int i,j, nc, ii, jj;
                   2787: 
1.234     brouard  2788:   for(i=1; i<= nlstate; i++){
                   2789:     for(j=1; j<i;j++){
                   2790:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2791:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2792:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2793:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2794:       }
                   2795:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2796:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2797:     }
                   2798:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2799:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2800:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2801:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2802:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2803:       }
                   2804:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2805:     }
                   2806:   }
                   2807:   
                   2808:   for(i=1; i<= nlstate; i++){
                   2809:     s1=0;
                   2810:     for(j=1; j<i; j++){
                   2811:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2812:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2813:     }
                   2814:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2815:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2816:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2817:     }
                   2818:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2819:     ps[i][i]=1./(s1+1.);
                   2820:     /* Computing other pijs */
                   2821:     for(j=1; j<i; j++)
                   2822:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2823:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2824:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2825:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2826:   } /* end i */
                   2827:   
                   2828:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2829:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2830:       ps[ii][jj]=0;
                   2831:       ps[ii][ii]=1;
                   2832:     }
                   2833:   }
                   2834:   /* Added for backcast */ /* Transposed matrix too */
                   2835:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2836:     s1=0.;
                   2837:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2838:       s1+=ps[ii][jj];
                   2839:     }
                   2840:     for(ii=1; ii<= nlstate; ii++){
                   2841:       ps[ii][jj]=ps[ii][jj]/s1;
                   2842:     }
                   2843:   }
                   2844:   /* Transposition */
                   2845:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2846:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2847:       s1=ps[ii][jj];
                   2848:       ps[ii][jj]=ps[jj][ii];
                   2849:       ps[jj][ii]=s1;
                   2850:     }
                   2851:   }
                   2852:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2853:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2854:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2855:   /*   } */
                   2856:   /*   printf("\n "); */
                   2857:   /* } */
                   2858:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2859:   /*
                   2860:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2861:     goto end;*/
                   2862:   return ps;
1.217     brouard  2863: }
                   2864: 
                   2865: 
1.126     brouard  2866: /**************** Product of 2 matrices ******************/
                   2867: 
1.145     brouard  2868: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2869: {
                   2870:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2871:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2872:   /* in, b, out are matrice of pointers which should have been initialized 
                   2873:      before: only the contents of out is modified. The function returns
                   2874:      a pointer to pointers identical to out */
1.145     brouard  2875:   int i, j, k;
1.126     brouard  2876:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2877:     for(k=ncolol; k<=ncoloh; k++){
                   2878:       out[i][k]=0.;
                   2879:       for(j=ncl; j<=nch; j++)
                   2880:        out[i][k] +=in[i][j]*b[j][k];
                   2881:     }
1.126     brouard  2882:   return out;
                   2883: }
                   2884: 
                   2885: 
                   2886: /************* Higher Matrix Product ***************/
                   2887: 
1.235     brouard  2888: 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  2889: {
1.218     brouard  2890:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2891:      'nhstepm*hstepm*stepm' months (i.e. until
                   2892:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2893:      nhstepm*hstepm matrices. 
                   2894:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2895:      (typically every 2 years instead of every month which is too big 
                   2896:      for the memory).
                   2897:      Model is determined by parameters x and covariates have to be 
                   2898:      included manually here. 
                   2899: 
                   2900:      */
                   2901: 
                   2902:   int i, j, d, h, k;
1.131     brouard  2903:   double **out, cov[NCOVMAX+1];
1.126     brouard  2904:   double **newm;
1.187     brouard  2905:   double agexact;
1.214     brouard  2906:   double agebegin, ageend;
1.126     brouard  2907: 
                   2908:   /* Hstepm could be zero and should return the unit matrix */
                   2909:   for (i=1;i<=nlstate+ndeath;i++)
                   2910:     for (j=1;j<=nlstate+ndeath;j++){
                   2911:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2912:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2913:     }
                   2914:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2915:   for(h=1; h <=nhstepm; h++){
                   2916:     for(d=1; d <=hstepm; d++){
                   2917:       newm=savm;
                   2918:       /* Covariates have to be included here again */
                   2919:       cov[1]=1.;
1.214     brouard  2920:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2921:       cov[2]=agexact;
                   2922:       if(nagesqr==1)
1.227     brouard  2923:        cov[3]= agexact*agexact;
1.235     brouard  2924:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2925:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2926:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2927:        /* 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)); */
                   2928:       }
                   2929:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2930:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2931:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2932:        /* 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]); */
                   2933:       }
                   2934:       for (k=1; k<=cptcovage;k++){
                   2935:        if(Dummy[Tvar[Tage[k]]]){
                   2936:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2937:        } else{
                   2938:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2939:        }
                   2940:        /* 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]); */
                   2941:       }
                   2942:       for (k=1; k<=cptcovprod;k++){ /*  */
                   2943:        /* 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]); */
                   2944:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2945:       }
                   2946:       /* for (k=1; k<=cptcovn;k++)  */
                   2947:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2948:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   2949:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2950:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   2951:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  2952:       
                   2953:       
1.126     brouard  2954:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2955:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2956:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2957:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2958:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2959:       /* if((int)age == 70){ */
                   2960:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2961:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2962:       /*         printf("%d pmmij ",i); */
                   2963:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2964:       /*           printf("%f ",pmmij[i][j]); */
                   2965:       /*         } */
                   2966:       /*         printf(" oldm "); */
                   2967:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2968:       /*           printf("%f ",oldm[i][j]); */
                   2969:       /*         } */
                   2970:       /*         printf("\n"); */
                   2971:       /*       } */
                   2972:       /* } */
1.126     brouard  2973:       savm=oldm;
                   2974:       oldm=newm;
                   2975:     }
                   2976:     for(i=1; i<=nlstate+ndeath; i++)
                   2977:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2978:                                po[i][j][h]=newm[i][j];
                   2979:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2980:       }
1.128     brouard  2981:     /*printf("h=%d ",h);*/
1.126     brouard  2982:   } /* end h */
1.218     brouard  2983:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2984:   return po;
                   2985: }
                   2986: 
1.217     brouard  2987: /************* Higher Back Matrix Product ***************/
1.218     brouard  2988: /* 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  2989: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2990: {
1.218     brouard  2991:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2992:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2993:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2994:      nhstepm*hstepm matrices.
                   2995:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2996:      (typically every 2 years instead of every month which is too big
1.217     brouard  2997:      for the memory).
1.218     brouard  2998:      Model is determined by parameters x and covariates have to be
                   2999:      included manually here.
1.217     brouard  3000: 
1.222     brouard  3001:   */
1.217     brouard  3002: 
                   3003:   int i, j, d, h, k;
                   3004:   double **out, cov[NCOVMAX+1];
                   3005:   double **newm;
                   3006:   double agexact;
                   3007:   double agebegin, ageend;
1.222     brouard  3008:   double **oldm, **savm;
1.217     brouard  3009: 
1.222     brouard  3010:   oldm=oldms;savm=savms;
1.217     brouard  3011:   /* Hstepm could be zero and should return the unit matrix */
                   3012:   for (i=1;i<=nlstate+ndeath;i++)
                   3013:     for (j=1;j<=nlstate+ndeath;j++){
                   3014:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3015:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3016:     }
                   3017:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3018:   for(h=1; h <=nhstepm; h++){
                   3019:     for(d=1; d <=hstepm; d++){
                   3020:       newm=savm;
                   3021:       /* Covariates have to be included here again */
                   3022:       cov[1]=1.;
                   3023:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3024:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3025:       cov[2]=agexact;
                   3026:       if(nagesqr==1)
1.222     brouard  3027:        cov[3]= agexact*agexact;
1.218     brouard  3028:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3029:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3030:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3031:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3032:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3033:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3034:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3035:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3036:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3037:       /* 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  3038:                        
                   3039:                        
1.217     brouard  3040:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3041:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3042:       /* Careful transposed matrix */
1.222     brouard  3043:       /* age is in cov[2] */
1.218     brouard  3044:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3045:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3046:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3047:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3048:       /* if((int)age == 70){ */
                   3049:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3050:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3051:       /*         printf("%d pmmij ",i); */
                   3052:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3053:       /*           printf("%f ",pmmij[i][j]); */
                   3054:       /*         } */
                   3055:       /*         printf(" oldm "); */
                   3056:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3057:       /*           printf("%f ",oldm[i][j]); */
                   3058:       /*         } */
                   3059:       /*         printf("\n"); */
                   3060:       /*       } */
                   3061:       /* } */
                   3062:       savm=oldm;
                   3063:       oldm=newm;
                   3064:     }
                   3065:     for(i=1; i<=nlstate+ndeath; i++)
                   3066:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3067:        po[i][j][h]=newm[i][j];
                   3068:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3069:       }
                   3070:     /*printf("h=%d ",h);*/
                   3071:   } /* end h */
1.222     brouard  3072:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3073:   return po;
                   3074: }
                   3075: 
                   3076: 
1.162     brouard  3077: #ifdef NLOPT
                   3078:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3079:   double fret;
                   3080:   double *xt;
                   3081:   int j;
                   3082:   myfunc_data *d2 = (myfunc_data *) pd;
                   3083: /* xt = (p1-1); */
                   3084:   xt=vector(1,n); 
                   3085:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3086: 
                   3087:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3088:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3089:   printf("Function = %.12lf ",fret);
                   3090:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3091:   printf("\n");
                   3092:  free_vector(xt,1,n);
                   3093:   return fret;
                   3094: }
                   3095: #endif
1.126     brouard  3096: 
                   3097: /*************** log-likelihood *************/
                   3098: double func( double *x)
                   3099: {
1.226     brouard  3100:   int i, ii, j, k, mi, d, kk;
                   3101:   int ioffset=0;
                   3102:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3103:   double **out;
                   3104:   double lli; /* Individual log likelihood */
                   3105:   int s1, s2;
1.228     brouard  3106:   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  3107:   double bbh, survp;
                   3108:   long ipmx;
                   3109:   double agexact;
                   3110:   /*extern weight */
                   3111:   /* We are differentiating ll according to initial status */
                   3112:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3113:   /*for(i=1;i<imx;i++) 
                   3114:     printf(" %d\n",s[4][i]);
                   3115:   */
1.162     brouard  3116: 
1.226     brouard  3117:   ++countcallfunc;
1.162     brouard  3118: 
1.226     brouard  3119:   cov[1]=1.;
1.126     brouard  3120: 
1.226     brouard  3121:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3122:   ioffset=0;
1.226     brouard  3123:   if(mle==1){
                   3124:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3125:       /* Computes the values of the ncovmodel covariates of the model
                   3126:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3127:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3128:         to be observed in j being in i according to the model.
                   3129:       */
                   3130:       ioffset=2+nagesqr+cptcovage;
1.233     brouard  3131:    /* Fixed */
1.234     brouard  3132:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3133:        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)*/
                   3134:       }
1.226     brouard  3135:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3136:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3137:         has been calculated etc */
                   3138:       /* For an individual i, wav[i] gives the number of effective waves */
                   3139:       /* We compute the contribution to Likelihood of each effective transition
                   3140:         mw[mi][i] is real wave of the mi th effectve wave */
                   3141:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3142:         s2=s[mw[mi+1][i]][i];
                   3143:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3144:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3145:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3146:       */
                   3147:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3148:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
                   3149:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
                   3150:        }
                   3151:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3152:          for (j=1;j<=nlstate+ndeath;j++){
                   3153:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3154:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3155:          }
                   3156:        for(d=0; d<dh[mi][i]; d++){
                   3157:          newm=savm;
                   3158:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3159:          cov[2]=agexact;
                   3160:          if(nagesqr==1)
                   3161:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3162:          for (kk=1; kk<=cptcovage;kk++) {
                   3163:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3164:          }
                   3165:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3166:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3167:          savm=oldm;
                   3168:          oldm=newm;
                   3169:        } /* end mult */
                   3170:        
                   3171:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3172:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3173:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3174:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3175:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3176:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3177:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3178:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3179:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3180:                                 * -stepm/2 to stepm/2 .
                   3181:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3182:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3183:                                 */
1.234     brouard  3184:        s1=s[mw[mi][i]][i];
                   3185:        s2=s[mw[mi+1][i]][i];
                   3186:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3187:        /* bias bh is positive if real duration
                   3188:         * is higher than the multiple of stepm and negative otherwise.
                   3189:         */
                   3190:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3191:        if( s2 > nlstate){ 
                   3192:          /* i.e. if s2 is a death state and if the date of death is known 
                   3193:             then the contribution to the likelihood is the probability to 
                   3194:             die between last step unit time and current  step unit time, 
                   3195:             which is also equal to probability to die before dh 
                   3196:             minus probability to die before dh-stepm . 
                   3197:             In version up to 0.92 likelihood was computed
                   3198:             as if date of death was unknown. Death was treated as any other
                   3199:             health state: the date of the interview describes the actual state
                   3200:             and not the date of a change in health state. The former idea was
                   3201:             to consider that at each interview the state was recorded
                   3202:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3203:             introduced the exact date of death then we should have modified
                   3204:             the contribution of an exact death to the likelihood. This new
                   3205:             contribution is smaller and very dependent of the step unit
                   3206:             stepm. It is no more the probability to die between last interview
                   3207:             and month of death but the probability to survive from last
                   3208:             interview up to one month before death multiplied by the
                   3209:             probability to die within a month. Thanks to Chris
                   3210:             Jackson for correcting this bug.  Former versions increased
                   3211:             mortality artificially. The bad side is that we add another loop
                   3212:             which slows down the processing. The difference can be up to 10%
                   3213:             lower mortality.
                   3214:          */
                   3215:          /* If, at the beginning of the maximization mostly, the
                   3216:             cumulative probability or probability to be dead is
                   3217:             constant (ie = 1) over time d, the difference is equal to
                   3218:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3219:             s1 at precedent wave, to be dead a month before current
                   3220:             wave is equal to probability, being at state s1 at
                   3221:             precedent wave, to be dead at mont of the current
                   3222:             wave. Then the observed probability (that this person died)
                   3223:             is null according to current estimated parameter. In fact,
                   3224:             it should be very low but not zero otherwise the log go to
                   3225:             infinity.
                   3226:          */
1.183     brouard  3227: /* #ifdef INFINITYORIGINAL */
                   3228: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3229: /* #else */
                   3230: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3231: /*         lli=log(mytinydouble); */
                   3232: /*       else */
                   3233: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3234: /* #endif */
1.226     brouard  3235:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3236:          
1.226     brouard  3237:        } else if  ( s2==-1 ) { /* alive */
                   3238:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3239:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3240:          /*survp += out[s1][j]; */
                   3241:          lli= log(survp);
                   3242:        }
                   3243:        else if  (s2==-4) { 
                   3244:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3245:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3246:          lli= log(survp); 
                   3247:        } 
                   3248:        else if  (s2==-5) { 
                   3249:          for (j=1,survp=0. ; j<=2; j++)  
                   3250:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3251:          lli= log(survp); 
                   3252:        } 
                   3253:        else{
                   3254:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3255:          /*  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 */
                   3256:        } 
                   3257:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3258:        /*if(lli ==000.0)*/
                   3259:        /*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); */
                   3260:        ipmx +=1;
                   3261:        sw += weight[i];
                   3262:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3263:        /* if (lli < log(mytinydouble)){ */
                   3264:        /*   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); */
                   3265:        /*   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]); */
                   3266:        /* } */
                   3267:       } /* end of wave */
                   3268:     } /* end of individual */
                   3269:   }  else if(mle==2){
                   3270:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3271:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3272:       for(mi=1; mi<= wav[i]-1; mi++){
                   3273:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3274:          for (j=1;j<=nlstate+ndeath;j++){
                   3275:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3276:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3277:          }
                   3278:        for(d=0; d<=dh[mi][i]; d++){
                   3279:          newm=savm;
                   3280:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3281:          cov[2]=agexact;
                   3282:          if(nagesqr==1)
                   3283:            cov[3]= agexact*agexact;
                   3284:          for (kk=1; kk<=cptcovage;kk++) {
                   3285:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3286:          }
                   3287:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3288:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3289:          savm=oldm;
                   3290:          oldm=newm;
                   3291:        } /* end mult */
                   3292:       
                   3293:        s1=s[mw[mi][i]][i];
                   3294:        s2=s[mw[mi+1][i]][i];
                   3295:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3296:        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 */
                   3297:        ipmx +=1;
                   3298:        sw += weight[i];
                   3299:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3300:       } /* end of wave */
                   3301:     } /* end of individual */
                   3302:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3303:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3304:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3305:       for(mi=1; mi<= wav[i]-1; mi++){
                   3306:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3307:          for (j=1;j<=nlstate+ndeath;j++){
                   3308:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3309:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3310:          }
                   3311:        for(d=0; d<dh[mi][i]; d++){
                   3312:          newm=savm;
                   3313:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3314:          cov[2]=agexact;
                   3315:          if(nagesqr==1)
                   3316:            cov[3]= agexact*agexact;
                   3317:          for (kk=1; kk<=cptcovage;kk++) {
                   3318:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3319:          }
                   3320:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3321:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3322:          savm=oldm;
                   3323:          oldm=newm;
                   3324:        } /* end mult */
                   3325:       
                   3326:        s1=s[mw[mi][i]][i];
                   3327:        s2=s[mw[mi+1][i]][i];
                   3328:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3329:        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 */
                   3330:        ipmx +=1;
                   3331:        sw += weight[i];
                   3332:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3333:       } /* end of wave */
                   3334:     } /* end of individual */
                   3335:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3336:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3337:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3338:       for(mi=1; mi<= wav[i]-1; mi++){
                   3339:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3340:          for (j=1;j<=nlstate+ndeath;j++){
                   3341:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3342:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3343:          }
                   3344:        for(d=0; d<dh[mi][i]; d++){
                   3345:          newm=savm;
                   3346:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3347:          cov[2]=agexact;
                   3348:          if(nagesqr==1)
                   3349:            cov[3]= agexact*agexact;
                   3350:          for (kk=1; kk<=cptcovage;kk++) {
                   3351:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3352:          }
1.126     brouard  3353:        
1.226     brouard  3354:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3355:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3356:          savm=oldm;
                   3357:          oldm=newm;
                   3358:        } /* end mult */
                   3359:       
                   3360:        s1=s[mw[mi][i]][i];
                   3361:        s2=s[mw[mi+1][i]][i];
                   3362:        if( s2 > nlstate){ 
                   3363:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3364:        } else if  ( s2==-1 ) { /* alive */
                   3365:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3366:            survp += out[s1][j];
                   3367:          lli= log(survp);
                   3368:        }else{
                   3369:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3370:        }
                   3371:        ipmx +=1;
                   3372:        sw += weight[i];
                   3373:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3374: /*     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  3375:       } /* end of wave */
                   3376:     } /* end of individual */
                   3377:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   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:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3405:        ipmx +=1;
                   3406:        sw += weight[i];
                   3407:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3408:        /*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]);*/
                   3409:       } /* end of wave */
                   3410:     } /* end of individual */
                   3411:   } /* End of if */
                   3412:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3413:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3414:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3415:   return -l;
1.126     brouard  3416: }
                   3417: 
                   3418: /*************** log-likelihood *************/
                   3419: double funcone( double *x)
                   3420: {
1.228     brouard  3421:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3422:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3423:   int ioffset=0;
1.131     brouard  3424:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3425:   double **out;
                   3426:   double lli; /* Individual log likelihood */
                   3427:   double llt;
                   3428:   int s1, s2;
1.228     brouard  3429:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3430: 
1.126     brouard  3431:   double bbh, survp;
1.187     brouard  3432:   double agexact;
1.214     brouard  3433:   double agebegin, ageend;
1.126     brouard  3434:   /*extern weight */
                   3435:   /* We are differentiating ll according to initial status */
                   3436:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3437:   /*for(i=1;i<imx;i++) 
                   3438:     printf(" %d\n",s[4][i]);
                   3439:   */
                   3440:   cov[1]=1.;
                   3441: 
                   3442:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3443:   ioffset=0;
                   3444:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.225     brouard  3445:     ioffset=2+nagesqr+cptcovage;
1.232     brouard  3446:     /* Fixed */
1.224     brouard  3447:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3448:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3449:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3450:       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)*/
                   3451: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3452: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3453: /*    cov[2+6]=covar[2][i]; V2  */
                   3454: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3455: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3456: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3457: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3458: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3459: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3460:     }
1.232     brouard  3461:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3462:     /*   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?)*\/ */
                   3463:     /* } */
1.231     brouard  3464:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3465:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3466:     /* } */
1.225     brouard  3467:     
1.233     brouard  3468: 
                   3469:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3470:     /* Wave varying (but not age varying) */
                   3471:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.233     brouard  3472:                                cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
1.232     brouard  3473:                        }
                   3474:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.231     brouard  3475:                                /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3476:                                /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
1.232     brouard  3477:                                /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3478:                                /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
1.231     brouard  3479:                                /* 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  3480:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3481:                        /*      iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3482:                        /*      /\* 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]); *\/ */
                   3483:                        /*      cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3484:       /* } */
1.126     brouard  3485:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.231     brouard  3486:                                for (j=1;j<=nlstate+ndeath;j++){
                   3487:                                        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3488:                                        savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3489:                                }
1.214     brouard  3490:       
                   3491:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3492:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3493:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.231     brouard  3494:                                /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3495:                                        and mw[mi+1][i]. dh depends on stepm.*/
                   3496:                                newm=savm;
                   3497:                                agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3498:                                cov[2]=agexact;
                   3499:                                if(nagesqr==1)
                   3500:                                        cov[3]= agexact*agexact;
                   3501:                                for (kk=1; kk<=cptcovage;kk++) {
                   3502:                                        cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3503:                                }
                   3504:                                /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3505:                                /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3506:                                out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3507:                                                                                 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3508:                                /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3509:                                /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3510:                                savm=oldm;
                   3511:                                oldm=newm;
1.126     brouard  3512:       } /* end mult */
                   3513:       
                   3514:       s1=s[mw[mi][i]][i];
                   3515:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3516:       /* if(s2==-1){ */
                   3517:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3518:       /*       /\* exit(1); *\/ */
                   3519:       /* } */
1.126     brouard  3520:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3521:       /* bias is positive if real duration
                   3522:        * is higher than the multiple of stepm and negative otherwise.
                   3523:        */
                   3524:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.232     brouard  3525:                                lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3526:       } else if  ( s2==-1 ) { /* alive */
1.232     brouard  3527:                                for (j=1,survp=0. ; j<=nlstate; j++) 
                   3528:                                        survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3529:                                lli= log(survp);
1.126     brouard  3530:       }else if (mle==1){
1.232     brouard  3531:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3532:       } else if(mle==2){
1.232     brouard  3533:                                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  3534:       } else if(mle==3){  /* exponential inter-extrapolation */
1.232     brouard  3535:                                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  3536:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.232     brouard  3537:                                lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3538:       } else{  /* mle=0 back to 1 */
1.232     brouard  3539:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3540:                                /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3541:       } /* End of if */
                   3542:       ipmx +=1;
                   3543:       sw += weight[i];
                   3544:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3545:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.126     brouard  3546:       if(globpr){
1.232     brouard  3547:                                fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3548:  %11.6f %11.6f %11.6f ", \
1.232     brouard  3549:                                                                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3550:                                                                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3551:                                for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3552:                                        llt +=ll[k]*gipmx/gsw;
                   3553:                                        fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3554:                                }
                   3555:                                fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3556:       }
1.232     brouard  3557:        } /* end of wave */
                   3558: } /* end of individual */
                   3559: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3560: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3561: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3562: if(globpr==0){ /* First time we count the contributions and weights */
                   3563:        gipmx=ipmx;
                   3564:        gsw=sw;
                   3565: }
                   3566: return -l;
1.126     brouard  3567: }
                   3568: 
                   3569: 
                   3570: /*************** function likelione ***********/
                   3571: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3572: {
                   3573:   /* This routine should help understanding what is done with 
                   3574:      the selection of individuals/waves and
                   3575:      to check the exact contribution to the likelihood.
                   3576:      Plotting could be done.
                   3577:    */
                   3578:   int k;
                   3579: 
                   3580:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3581:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3582:     strcat(fileresilk,fileresu);
1.126     brouard  3583:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3584:       printf("Problem with resultfile: %s\n", fileresilk);
                   3585:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3586:     }
1.214     brouard  3587:     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");
                   3588:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3589:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3590:     for(k=1; k<=nlstate; k++) 
                   3591:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3592:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3593:   }
                   3594: 
                   3595:   *fretone=(*funcone)(p);
                   3596:   if(*globpri !=0){
                   3597:     fclose(ficresilk);
1.205     brouard  3598:     if (mle ==0)
                   3599:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3600:     else if(mle >=1)
                   3601:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3602:     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  3603:     
1.208     brouard  3604:       
                   3605:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3606:       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  3607: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3608:     }
1.207     brouard  3609:     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  3610: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3611:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3612: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3613:     fflush(fichtm);
1.205     brouard  3614:   }
1.126     brouard  3615:   return;
                   3616: }
                   3617: 
                   3618: 
                   3619: /*********** Maximum Likelihood Estimation ***************/
                   3620: 
                   3621: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3622: {
1.165     brouard  3623:   int i,j, iter=0;
1.126     brouard  3624:   double **xi;
                   3625:   double fret;
                   3626:   double fretone; /* Only one call to likelihood */
                   3627:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3628: 
                   3629: #ifdef NLOPT
                   3630:   int creturn;
                   3631:   nlopt_opt opt;
                   3632:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3633:   double *lb;
                   3634:   double minf; /* the minimum objective value, upon return */
                   3635:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3636:   myfunc_data dinst, *d = &dinst;
                   3637: #endif
                   3638: 
                   3639: 
1.126     brouard  3640:   xi=matrix(1,npar,1,npar);
                   3641:   for (i=1;i<=npar;i++)
                   3642:     for (j=1;j<=npar;j++)
                   3643:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3644:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3645:   strcpy(filerespow,"POW_"); 
1.126     brouard  3646:   strcat(filerespow,fileres);
                   3647:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3648:     printf("Problem with resultfile: %s\n", filerespow);
                   3649:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3650:   }
                   3651:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3652:   for (i=1;i<=nlstate;i++)
                   3653:     for(j=1;j<=nlstate+ndeath;j++)
                   3654:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3655:   fprintf(ficrespow,"\n");
1.162     brouard  3656: #ifdef POWELL
1.126     brouard  3657:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3658: #endif
1.126     brouard  3659: 
1.162     brouard  3660: #ifdef NLOPT
                   3661: #ifdef NEWUOA
                   3662:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3663: #else
                   3664:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3665: #endif
                   3666:   lb=vector(0,npar-1);
                   3667:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3668:   nlopt_set_lower_bounds(opt, lb);
                   3669:   nlopt_set_initial_step1(opt, 0.1);
                   3670:   
                   3671:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3672:   d->function = func;
                   3673:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3674:   nlopt_set_min_objective(opt, myfunc, d);
                   3675:   nlopt_set_xtol_rel(opt, ftol);
                   3676:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3677:     printf("nlopt failed! %d\n",creturn); 
                   3678:   }
                   3679:   else {
                   3680:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3681:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3682:     iter=1; /* not equal */
                   3683:   }
                   3684:   nlopt_destroy(opt);
                   3685: #endif
1.126     brouard  3686:   free_matrix(xi,1,npar,1,npar);
                   3687:   fclose(ficrespow);
1.203     brouard  3688:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3689:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3690:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3691: 
                   3692: }
                   3693: 
                   3694: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3695: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3696: {
                   3697:   double  **a,**y,*x,pd;
1.203     brouard  3698:   /* double **hess; */
1.164     brouard  3699:   int i, j;
1.126     brouard  3700:   int *indx;
                   3701: 
                   3702:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3703:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3704:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3705:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3706:   double gompertz(double p[]);
1.203     brouard  3707:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3708: 
                   3709:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3710:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3711:   for (i=1;i<=npar;i++){
1.203     brouard  3712:     printf("%d-",i);fflush(stdout);
                   3713:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3714:    
                   3715:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3716:     
                   3717:     /*  printf(" %f ",p[i]);
                   3718:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3719:   }
                   3720:   
                   3721:   for (i=1;i<=npar;i++) {
                   3722:     for (j=1;j<=npar;j++)  {
                   3723:       if (j>i) { 
1.203     brouard  3724:        printf(".%d-%d",i,j);fflush(stdout);
                   3725:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3726:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3727:        
                   3728:        hess[j][i]=hess[i][j];    
                   3729:        /*printf(" %lf ",hess[i][j]);*/
                   3730:       }
                   3731:     }
                   3732:   }
                   3733:   printf("\n");
                   3734:   fprintf(ficlog,"\n");
                   3735: 
                   3736:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3737:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3738:   
                   3739:   a=matrix(1,npar,1,npar);
                   3740:   y=matrix(1,npar,1,npar);
                   3741:   x=vector(1,npar);
                   3742:   indx=ivector(1,npar);
                   3743:   for (i=1;i<=npar;i++)
                   3744:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3745:   ludcmp(a,npar,indx,&pd);
                   3746: 
                   3747:   for (j=1;j<=npar;j++) {
                   3748:     for (i=1;i<=npar;i++) x[i]=0;
                   3749:     x[j]=1;
                   3750:     lubksb(a,npar,indx,x);
                   3751:     for (i=1;i<=npar;i++){ 
                   3752:       matcov[i][j]=x[i];
                   3753:     }
                   3754:   }
                   3755: 
                   3756:   printf("\n#Hessian matrix#\n");
                   3757:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3758:   for (i=1;i<=npar;i++) { 
                   3759:     for (j=1;j<=npar;j++) { 
1.203     brouard  3760:       printf("%.6e ",hess[i][j]);
                   3761:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3762:     }
                   3763:     printf("\n");
                   3764:     fprintf(ficlog,"\n");
                   3765:   }
                   3766: 
1.203     brouard  3767:   /* printf("\n#Covariance matrix#\n"); */
                   3768:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3769:   /* for (i=1;i<=npar;i++) {  */
                   3770:   /*   for (j=1;j<=npar;j++) {  */
                   3771:   /*     printf("%.6e ",matcov[i][j]); */
                   3772:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3773:   /*   } */
                   3774:   /*   printf("\n"); */
                   3775:   /*   fprintf(ficlog,"\n"); */
                   3776:   /* } */
                   3777: 
1.126     brouard  3778:   /* Recompute Inverse */
1.203     brouard  3779:   /* for (i=1;i<=npar;i++) */
                   3780:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3781:   /* ludcmp(a,npar,indx,&pd); */
                   3782: 
                   3783:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3784: 
                   3785:   /* for (j=1;j<=npar;j++) { */
                   3786:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3787:   /*   x[j]=1; */
                   3788:   /*   lubksb(a,npar,indx,x); */
                   3789:   /*   for (i=1;i<=npar;i++){  */
                   3790:   /*     y[i][j]=x[i]; */
                   3791:   /*     printf("%.3e ",y[i][j]); */
                   3792:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3793:   /*   } */
                   3794:   /*   printf("\n"); */
                   3795:   /*   fprintf(ficlog,"\n"); */
                   3796:   /* } */
                   3797: 
                   3798:   /* Verifying the inverse matrix */
                   3799: #ifdef DEBUGHESS
                   3800:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3801: 
1.203     brouard  3802:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3803:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3804: 
                   3805:   for (j=1;j<=npar;j++) {
                   3806:     for (i=1;i<=npar;i++){ 
1.203     brouard  3807:       printf("%.2f ",y[i][j]);
                   3808:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3809:     }
                   3810:     printf("\n");
                   3811:     fprintf(ficlog,"\n");
                   3812:   }
1.203     brouard  3813: #endif
1.126     brouard  3814: 
                   3815:   free_matrix(a,1,npar,1,npar);
                   3816:   free_matrix(y,1,npar,1,npar);
                   3817:   free_vector(x,1,npar);
                   3818:   free_ivector(indx,1,npar);
1.203     brouard  3819:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3820: 
                   3821: 
                   3822: }
                   3823: 
                   3824: /*************** hessian matrix ****************/
                   3825: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3826: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3827:   int i;
                   3828:   int l=1, lmax=20;
1.203     brouard  3829:   double k1,k2, res, fx;
1.132     brouard  3830:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3831:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3832:   int k=0,kmax=10;
                   3833:   double l1;
                   3834: 
                   3835:   fx=func(x);
                   3836:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3837:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3838:     l1=pow(10,l);
                   3839:     delts=delt;
                   3840:     for(k=1 ; k <kmax; k=k+1){
                   3841:       delt = delta*(l1*k);
                   3842:       p2[theta]=x[theta] +delt;
1.145     brouard  3843:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3844:       p2[theta]=x[theta]-delt;
                   3845:       k2=func(p2)-fx;
                   3846:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3847:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3848:       
1.203     brouard  3849: #ifdef DEBUGHESSII
1.126     brouard  3850:       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);
                   3851:       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);
                   3852: #endif
                   3853:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3854:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3855:        k=kmax;
                   3856:       }
                   3857:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3858:        k=kmax; l=lmax*10;
1.126     brouard  3859:       }
                   3860:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3861:        delts=delt;
                   3862:       }
1.203     brouard  3863:     } /* End loop k */
1.126     brouard  3864:   }
                   3865:   delti[theta]=delts;
                   3866:   return res; 
                   3867:   
                   3868: }
                   3869: 
1.203     brouard  3870: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3871: {
                   3872:   int i;
1.164     brouard  3873:   int l=1, lmax=20;
1.126     brouard  3874:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3875:   double p2[MAXPARM+1];
1.203     brouard  3876:   int k, kmax=1;
                   3877:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3878: 
                   3879:   int firstime=0;
1.203     brouard  3880:   
1.126     brouard  3881:   fx=func(x);
1.203     brouard  3882:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3883:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3884:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3885:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3886:     k1=func(p2)-fx;
                   3887:   
1.203     brouard  3888:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3889:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3890:     k2=func(p2)-fx;
                   3891:   
1.203     brouard  3892:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3893:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3894:     k3=func(p2)-fx;
                   3895:   
1.203     brouard  3896:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3897:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3898:     k4=func(p2)-fx;
1.203     brouard  3899:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3900:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3901:       firstime=1;
1.203     brouard  3902:       kmax=kmax+10;
1.208     brouard  3903:     }
                   3904:     if(kmax >=10 || firstime ==1){
1.218     brouard  3905:       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);
                   3906:       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  3907:       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);
                   3908:       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);
                   3909:     }
                   3910: #ifdef DEBUGHESSIJ
                   3911:     v1=hess[thetai][thetai];
                   3912:     v2=hess[thetaj][thetaj];
                   3913:     cv12=res;
                   3914:     /* Computing eigen value of Hessian matrix */
                   3915:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3916:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3917:     if ((lc2 <0) || (lc1 <0) ){
                   3918:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3919:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3920:       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);
                   3921:       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);
                   3922:     }
1.126     brouard  3923: #endif
                   3924:   }
                   3925:   return res;
                   3926: }
                   3927: 
1.203     brouard  3928:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3929: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3930: /* { */
                   3931: /*   int i; */
                   3932: /*   int l=1, lmax=20; */
                   3933: /*   double k1,k2,k3,k4,res,fx; */
                   3934: /*   double p2[MAXPARM+1]; */
                   3935: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3936: /*   int k=0,kmax=10; */
                   3937: /*   double l1; */
                   3938:   
                   3939: /*   fx=func(x); */
                   3940: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3941: /*     l1=pow(10,l); */
                   3942: /*     delts=delt; */
                   3943: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3944: /*       delt = delti*(l1*k); */
                   3945: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3946: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3947: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3948: /*       k1=func(p2)-fx; */
                   3949:       
                   3950: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3951: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3952: /*       k2=func(p2)-fx; */
                   3953:       
                   3954: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3955: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3956: /*       k3=func(p2)-fx; */
                   3957:       
                   3958: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3959: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3960: /*       k4=func(p2)-fx; */
                   3961: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3962: /* #ifdef DEBUGHESSIJ */
                   3963: /*       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); */
                   3964: /*       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); */
                   3965: /* #endif */
                   3966: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3967: /*     k=kmax; */
                   3968: /*       } */
                   3969: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3970: /*     k=kmax; l=lmax*10; */
                   3971: /*       } */
                   3972: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3973: /*     delts=delt; */
                   3974: /*       } */
                   3975: /*     } /\* End loop k *\/ */
                   3976: /*   } */
                   3977: /*   delti[theta]=delts; */
                   3978: /*   return res;  */
                   3979: /* } */
                   3980: 
                   3981: 
1.126     brouard  3982: /************** Inverse of matrix **************/
                   3983: void ludcmp(double **a, int n, int *indx, double *d) 
                   3984: { 
                   3985:   int i,imax,j,k; 
                   3986:   double big,dum,sum,temp; 
                   3987:   double *vv; 
                   3988:  
                   3989:   vv=vector(1,n); 
                   3990:   *d=1.0; 
                   3991:   for (i=1;i<=n;i++) { 
                   3992:     big=0.0; 
                   3993:     for (j=1;j<=n;j++) 
                   3994:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3995:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3996:     vv[i]=1.0/big; 
                   3997:   } 
                   3998:   for (j=1;j<=n;j++) { 
                   3999:     for (i=1;i<j;i++) { 
                   4000:       sum=a[i][j]; 
                   4001:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4002:       a[i][j]=sum; 
                   4003:     } 
                   4004:     big=0.0; 
                   4005:     for (i=j;i<=n;i++) { 
                   4006:       sum=a[i][j]; 
                   4007:       for (k=1;k<j;k++) 
                   4008:        sum -= a[i][k]*a[k][j]; 
                   4009:       a[i][j]=sum; 
                   4010:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4011:        big=dum; 
                   4012:        imax=i; 
                   4013:       } 
                   4014:     } 
                   4015:     if (j != imax) { 
                   4016:       for (k=1;k<=n;k++) { 
                   4017:        dum=a[imax][k]; 
                   4018:        a[imax][k]=a[j][k]; 
                   4019:        a[j][k]=dum; 
                   4020:       } 
                   4021:       *d = -(*d); 
                   4022:       vv[imax]=vv[j]; 
                   4023:     } 
                   4024:     indx[j]=imax; 
                   4025:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4026:     if (j != n) { 
                   4027:       dum=1.0/(a[j][j]); 
                   4028:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4029:     } 
                   4030:   } 
                   4031:   free_vector(vv,1,n);  /* Doesn't work */
                   4032: ;
                   4033: } 
                   4034: 
                   4035: void lubksb(double **a, int n, int *indx, double b[]) 
                   4036: { 
                   4037:   int i,ii=0,ip,j; 
                   4038:   double sum; 
                   4039:  
                   4040:   for (i=1;i<=n;i++) { 
                   4041:     ip=indx[i]; 
                   4042:     sum=b[ip]; 
                   4043:     b[ip]=b[i]; 
                   4044:     if (ii) 
                   4045:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4046:     else if (sum) ii=i; 
                   4047:     b[i]=sum; 
                   4048:   } 
                   4049:   for (i=n;i>=1;i--) { 
                   4050:     sum=b[i]; 
                   4051:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4052:     b[i]=sum/a[i][i]; 
                   4053:   } 
                   4054: } 
                   4055: 
                   4056: void pstamp(FILE *fichier)
                   4057: {
1.196     brouard  4058:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4059: }
                   4060: 
                   4061: /************ Frequencies ********************/
1.226     brouard  4062: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4063:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4064:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4065: {  /* Some frequencies */
                   4066:   
1.227     brouard  4067:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4068:   int iind=0, iage=0;
                   4069:   int mi; /* Effective wave */
                   4070:   int first;
                   4071:   double ***freq; /* Frequencies */
                   4072:   double *meanq;
                   4073:   double **meanqt;
                   4074:   double *pp, **prop, *posprop, *pospropt;
                   4075:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4076:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4077:   double agebegin, ageend;
                   4078:     
                   4079:   pp=vector(1,nlstate);
                   4080:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4081:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4082:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4083:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4084:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4085:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4086:   strcpy(fileresp,"P_");
                   4087:   strcat(fileresp,fileresu);
                   4088:   /*strcat(fileresphtm,fileresu);*/
                   4089:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4090:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4091:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4092:     exit(0);
                   4093:   }
1.214     brouard  4094: 
1.226     brouard  4095:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4096:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4097:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4098:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4099:     fflush(ficlog);
                   4100:     exit(70); 
                   4101:   }
                   4102:   else{
                   4103:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  4104: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   4105: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4106:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4107:   }
1.237     brouard  4108:   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.214     brouard  4109:     
1.226     brouard  4110:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4111:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4112:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4113:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4114:     fflush(ficlog);
                   4115:     exit(70); 
                   4116:   }
                   4117:   else{
                   4118:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  4119: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   4120: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4121:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4122:   }
                   4123:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
1.214     brouard  4124: 
1.226     brouard  4125:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4126:   j1=0;
1.126     brouard  4127:   
1.227     brouard  4128:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4129:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4130:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.220     brouard  4131: 
1.226     brouard  4132:   first=1;
1.220     brouard  4133: 
1.226     brouard  4134:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4135:      reference=low_education V1=0,V2=0
                   4136:      med_educ                V1=1 V2=0, 
                   4137:      high_educ               V1=0 V2=1
                   4138:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4139:   */
1.126     brouard  4140: 
1.227     brouard  4141:   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  4142:     posproptt=0.;
                   4143:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4144:       scanf("%d", i);*/
                   4145:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4146:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.231     brouard  4147:                                for(m=iagemin; m <= iagemax+3; m++)
                   4148:                                        freq[i][jk][m]=0;
                   4149:                
1.226     brouard  4150:     for (i=1; i<=nlstate; i++)  {
                   4151:       for(m=iagemin; m <= iagemax+3; m++)
1.231     brouard  4152:                                prop[i][m]=0;
1.226     brouard  4153:       posprop[i]=0;
                   4154:       pospropt[i]=0;
                   4155:     }
1.227     brouard  4156:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4157:     /*   meanq[z1]+=0.; */
                   4158:     /*   for(m=1;m<=lastpass;m++){ */
                   4159:     /*         meanqt[m][z1]=0.; */
                   4160:     /*   } */
                   4161:     /* } */
1.231     brouard  4162:                
1.226     brouard  4163:     dateintsum=0;
                   4164:     k2cpt=0;
1.227     brouard  4165:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4166:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4167:       bool=1;
1.227     brouard  4168:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4169:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4170:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4171:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4172:          /* } */
1.234     brouard  4173:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4174:            /* if(Tvaraff[z1] ==-20){ */
                   4175:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4176:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4177:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4178:            /* }else  */
                   4179:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4180:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4181:              bool=0;
                   4182:              /* 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", 
                   4183:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4184:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4185:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4186:            } /* Onlyf fixed */
                   4187:          } /* end z1 */
                   4188:        } /* cptcovn > 0 */
1.227     brouard  4189:       } /* end any */
                   4190:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4191:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4192:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4193:          m=mw[mi][iind];
                   4194:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4195:            for (z1=1; z1<=cptcoveff; z1++) {
                   4196:              if( Fixed[Tmodelind[z1]]==1){
                   4197:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4198:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4199:                  bool=0;
                   4200:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4201:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4202:                  bool=0;
                   4203:                }
                   4204:              }
                   4205:            }
                   4206:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4207:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4208:          if(bool==1){
                   4209:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4210:               and mw[mi+1][iind]. dh depends on stepm. */
                   4211:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4212:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4213:            if(m >=firstpass && m <=lastpass){
                   4214:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4215:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4216:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4217:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4218:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4219:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4220:              if (m<lastpass) {
                   4221:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4222:                /*   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]); */
                   4223:                if(s[m][iind]==-1)
                   4224:                  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.));
                   4225:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4226:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4227:                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 */
                   4228:              }
                   4229:            } /* end if between passes */  
                   4230:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4231:              dateintsum=dateintsum+k2;
                   4232:              k2cpt++;
                   4233:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4234:            }
                   4235:          } /* end bool 2 */
                   4236:        } /* end m */
1.226     brouard  4237:       } /* end bool */
                   4238:     } /* end iind = 1 to imx */
                   4239:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4240:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.231     brouard  4241:                
                   4242:                
1.226     brouard  4243:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4244:     pstamp(ficresp);
1.227     brouard  4245:     /* if  (ncoveff>0) { */
                   4246:     if  (cptcoveff>0) {
1.226     brouard  4247:       fprintf(ficresp, "\n#********** Variable "); 
                   4248:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4249:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.227     brouard  4250:       for (z1=1; z1<=cptcoveff; z1++){
1.234     brouard  4251:        fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4252:        fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4253:        fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.226     brouard  4254:       }
                   4255:       fprintf(ficresp, "**********\n#");
                   4256:       fprintf(ficresphtm, "**********</h3>\n");
                   4257:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4258:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4259:       for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.226     brouard  4260:       fprintf(ficlog, "**********\n");
                   4261:     }
                   4262:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4263:     for(i=1; i<=nlstate;i++) {
                   4264:       fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   4265:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4266:     }
                   4267:     fprintf(ficresp, "\n");
                   4268:     fprintf(ficresphtm, "\n");
1.231     brouard  4269:                
1.226     brouard  4270:     /* Header of frequency table by age */
                   4271:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4272:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4273:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4274:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4275:        if(jk!=0 && m!=0)
                   4276:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4277:       }
                   4278:     }
                   4279:     fprintf(ficresphtmfr, "\n");
1.231     brouard  4280:                
1.226     brouard  4281:     /* For each age */
                   4282:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4283:       fprintf(ficresphtm,"<tr>");
                   4284:       if(iage==iagemax+1){
1.231     brouard  4285:                                fprintf(ficlog,"1");
                   4286:                                fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4287:       }else if(iage==iagemax+2){
1.231     brouard  4288:                                fprintf(ficlog,"0");
                   4289:                                fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4290:       }else if(iage==iagemax+3){
1.231     brouard  4291:                                fprintf(ficlog,"Total");
                   4292:                                fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4293:       }else{
1.231     brouard  4294:                                if(first==1){
                   4295:                                        first=0;
                   4296:                                        printf("See log file for details...\n");
                   4297:                                }
                   4298:                                fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4299:                                fprintf(ficlog,"Age %d", iage);
1.226     brouard  4300:       }
                   4301:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4302:                                for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4303:                                        pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4304:       }
                   4305:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4306:                                for(m=-1, pos=0; m <=0 ; m++)
                   4307:                                        pos += freq[jk][m][iage];
                   4308:                                if(pp[jk]>=1.e-10){
                   4309:                                        if(first==1){
                   4310:                                                printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4311:                                        }
                   4312:                                        fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4313:                                }else{
                   4314:                                        if(first==1)
                   4315:                                                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4316:                                        fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4317:                                }
1.226     brouard  4318:       }
1.231     brouard  4319:                        
1.226     brouard  4320:       for(jk=1; jk <=nlstate ; jk++){ 
1.231     brouard  4321:                                /* posprop[jk]=0; */
                   4322:                                for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4323:                                        pp[jk] += freq[jk][m][iage];
1.226     brouard  4324:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.231     brouard  4325:                        
1.226     brouard  4326:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.231     brouard  4327:                                pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4328:                                posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4329:                                                                                                                                                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4330:                                pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4331:                                                                                                                                                                from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4332:       }
                   4333:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4334:                                if(pos>=1.e-5){
                   4335:                                        if(first==1)
                   4336:                                                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4337:                                        fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4338:                                }else{
                   4339:                                        if(first==1)
                   4340:                                                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4341:                                        fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4342:                                }
                   4343:                                if( iage <= iagemax){
                   4344:                                        if(pos>=1.e-5){
                   4345:                                                fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4346:                                                fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4347:                                                /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4348:                                                /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4349:                                        }
                   4350:                                        else{
                   4351:                                                fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4352:                                                fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4353:                                        }
                   4354:                                }
                   4355:                                pospropt[jk] +=posprop[jk];
1.226     brouard  4356:       } /* end loop jk */
                   4357:       /* pospropt=0.; */
                   4358:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.231     brouard  4359:                                for(m=-1; m <=nlstate+ndeath; m++){
                   4360:                                        if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4361:                                                if(first==1){
                   4362:                                                        printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4363:                                                }
                   4364:                                                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4365:                                        }
                   4366:                                        if(jk!=0 && m!=0)
                   4367:                                                fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4368:                                }
1.226     brouard  4369:       } /* end loop jk */
                   4370:       posproptt=0.; 
                   4371:       for(jk=1; jk <=nlstate; jk++){
1.231     brouard  4372:                                posproptt += pospropt[jk];
1.226     brouard  4373:       }
                   4374:       fprintf(ficresphtmfr,"</tr>\n ");
                   4375:       if(iage <= iagemax){
1.231     brouard  4376:                                fprintf(ficresp,"\n");
                   4377:                                fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4378:       }
                   4379:       if(first==1)
1.231     brouard  4380:                                printf("Others in log...\n");
1.226     brouard  4381:       fprintf(ficlog,"\n");
                   4382:     } /* end loop age iage */
                   4383:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4384:     for(jk=1; jk <=nlstate ; jk++){
                   4385:       if(posproptt < 1.e-5){
1.231     brouard  4386:                                fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4387:       }else{
1.231     brouard  4388:                                fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4389:       }
                   4390:     }
                   4391:     fprintf(ficresphtm,"</tr>\n");
                   4392:     fprintf(ficresphtm,"</table>\n");
                   4393:     fprintf(ficresphtmfr,"</table>\n");
                   4394:     if(posproptt < 1.e-5){
                   4395:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4396:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4397:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4398:       invalidvarcomb[j1]=1;
                   4399:     }else{
                   4400:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4401:       invalidvarcomb[j1]=0;
                   4402:     }
                   4403:     fprintf(ficresphtmfr,"</table>\n");
                   4404:   } /* end selected combination of covariate j1 */
                   4405:   dateintmean=dateintsum/k2cpt; 
1.231     brouard  4406:        
1.226     brouard  4407:   fclose(ficresp);
                   4408:   fclose(ficresphtm);
                   4409:   fclose(ficresphtmfr);
                   4410:   free_vector(meanq,1,nqfveff);
                   4411:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4412:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4413:   free_vector(pospropt,1,nlstate);
                   4414:   free_vector(posprop,1,nlstate);
                   4415:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4416:   free_vector(pp,1,nlstate);
                   4417:   /* End of freqsummary */
                   4418: }
1.126     brouard  4419: 
                   4420: /************ Prevalence ********************/
1.227     brouard  4421: 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)
                   4422: {  
                   4423:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4424:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4425:      We still use firstpass and lastpass as another selection.
                   4426:   */
1.126     brouard  4427:  
1.227     brouard  4428:   int i, m, jk, j1, bool, z1,j, iv;
                   4429:   int mi; /* Effective wave */
                   4430:   int iage;
                   4431:   double agebegin, ageend;
                   4432: 
                   4433:   double **prop;
                   4434:   double posprop; 
                   4435:   double  y2; /* in fractional years */
                   4436:   int iagemin, iagemax;
                   4437:   int first; /** to stop verbosity which is redirected to log file */
                   4438: 
                   4439:   iagemin= (int) agemin;
                   4440:   iagemax= (int) agemax;
                   4441:   /*pp=vector(1,nlstate);*/
                   4442:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4443:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4444:   j1=0;
1.222     brouard  4445:   
1.227     brouard  4446:   /*j=cptcoveff;*/
                   4447:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4448:   
1.227     brouard  4449:   first=1;
                   4450:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4451:     for (i=1; i<=nlstate; i++)  
                   4452:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4453:        prop[i][iage]=0.0;
                   4454:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4455:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4456:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4457:     
                   4458:     for (i=1; i<=imx; i++) { /* Each individual */
                   4459:       bool=1;
                   4460:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4461:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4462:        m=mw[mi][i];
                   4463:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4464:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4465:        for (z1=1; z1<=cptcoveff; z1++){
                   4466:          if( Fixed[Tmodelind[z1]]==1){
                   4467:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4468:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4469:              bool=0;
                   4470:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4471:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4472:              bool=0;
                   4473:            }
                   4474:        }
                   4475:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4476:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4477:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4478:          if(m >=firstpass && m <=lastpass){
                   4479:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4480:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4481:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4482:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4483:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4484:                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); 
                   4485:                exit(1);
                   4486:              }
                   4487:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4488:                /*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]]);*/
                   4489:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4490:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4491:              } /* end valid statuses */ 
                   4492:            } /* end selection of dates */
                   4493:          } /* end selection of waves */
                   4494:        } /* end bool */
                   4495:       } /* end wave */
                   4496:     } /* end individual */
                   4497:     for(i=iagemin; i <= iagemax+3; i++){  
                   4498:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4499:        posprop += prop[jk][i]; 
                   4500:       } 
                   4501:       
                   4502:       for(jk=1; jk <=nlstate ; jk++){      
                   4503:        if( i <=  iagemax){ 
                   4504:          if(posprop>=1.e-5){ 
                   4505:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4506:          } else{
                   4507:            if(first==1){
                   4508:              first=0;
                   4509:              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]);
                   4510:            }
                   4511:          }
                   4512:        } 
                   4513:       }/* end jk */ 
                   4514:     }/* end i */ 
1.222     brouard  4515:      /*} *//* end i1 */
1.227     brouard  4516:   } /* end j1 */
1.222     brouard  4517:   
1.227     brouard  4518:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4519:   /*free_vector(pp,1,nlstate);*/
                   4520:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4521: }  /* End of prevalence */
1.126     brouard  4522: 
                   4523: /************* Waves Concatenation ***************/
                   4524: 
                   4525: 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)
                   4526: {
                   4527:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4528:      Death is a valid wave (if date is known).
                   4529:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4530:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4531:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4532:   */
1.126     brouard  4533: 
1.224     brouard  4534:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4535:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4536:      double sum=0., jmean=0.;*/
1.224     brouard  4537:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4538:   int j, k=0,jk, ju, jl;
                   4539:   double sum=0.;
                   4540:   first=0;
1.214     brouard  4541:   firstwo=0;
1.217     brouard  4542:   firsthree=0;
1.218     brouard  4543:   firstfour=0;
1.164     brouard  4544:   jmin=100000;
1.126     brouard  4545:   jmax=-1;
                   4546:   jmean=0.;
1.224     brouard  4547: 
                   4548: /* Treating live states */
1.214     brouard  4549:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4550:     mi=0;  /* First valid wave */
1.227     brouard  4551:     mli=0; /* Last valid wave */
1.126     brouard  4552:     m=firstpass;
1.214     brouard  4553:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4554:       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 */
                   4555:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4556:       }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 */
                   4557:        mw[++mi][i]=m;
                   4558:        mli=m;
1.224     brouard  4559:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4560:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4561:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4562:       }
1.227     brouard  4563:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4564: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4565:        break;
1.224     brouard  4566: #else
1.227     brouard  4567:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4568:          if(firsthree == 0){
                   4569:            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);
                   4570:            firsthree=1;
                   4571:          }
                   4572:          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);
                   4573:          mw[++mi][i]=m;
                   4574:          mli=m;
                   4575:        }
                   4576:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4577:          nbwarn++;
                   4578:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4579:            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);
                   4580:            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);
                   4581:          }
                   4582:          break;
                   4583:        }
                   4584:        break;
1.224     brouard  4585: #endif
1.227     brouard  4586:       }/* End m >= lastpass */
1.126     brouard  4587:     }/* end while */
1.224     brouard  4588: 
1.227     brouard  4589:     /* 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  4590:     /* After last pass */
1.224     brouard  4591: /* Treating death states */
1.214     brouard  4592:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4593:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4594:       /* } */
1.126     brouard  4595:       mi++;    /* Death is another wave */
                   4596:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4597:       /* Only death is a correct wave */
1.126     brouard  4598:       mw[mi][i]=m;
1.224     brouard  4599:     }
                   4600: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4601:     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  4602:       /* m++; */
                   4603:       /* mi++; */
                   4604:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4605:       /* mw[mi][i]=m; */
1.218     brouard  4606:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4607:        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 */
                   4608:          nbwarn++;
                   4609:          if(firstfiv==0){
                   4610:            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 );
                   4611:            firstfiv=1;
                   4612:          }else{
                   4613:            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 );
                   4614:          }
                   4615:        }else{ /* Death occured afer last wave potential bias */
                   4616:          nberr++;
                   4617:          if(firstwo==0){
                   4618:            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 );
                   4619:            firstwo=1;
                   4620:          }
                   4621:          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 );
                   4622:        }
1.218     brouard  4623:       }else{ /* end date of interview is known */
1.227     brouard  4624:        /* death is known but not confirmed by death status at any wave */
                   4625:        if(firstfour==0){
                   4626:          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 );
                   4627:          firstfour=1;
                   4628:        }
                   4629:        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  4630:       }
1.224     brouard  4631:     } /* end if date of death is known */
                   4632: #endif
                   4633:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4634:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4635:     if(mi==0){
                   4636:       nbwarn++;
                   4637:       if(first==0){
1.227     brouard  4638:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4639:        first=1;
1.126     brouard  4640:       }
                   4641:       if(first==1){
1.227     brouard  4642:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4643:       }
                   4644:     } /* end mi==0 */
                   4645:   } /* End individuals */
1.214     brouard  4646:   /* wav and mw are no more changed */
1.223     brouard  4647:        
1.214     brouard  4648:   
1.126     brouard  4649:   for(i=1; i<=imx; i++){
                   4650:     for(mi=1; mi<wav[i];mi++){
                   4651:       if (stepm <=0)
1.227     brouard  4652:        dh[mi][i]=1;
1.126     brouard  4653:       else{
1.227     brouard  4654:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4655:          if (agedc[i] < 2*AGESUP) {
                   4656:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4657:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4658:            else if(j<0){
                   4659:              nberr++;
                   4660:              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]);
                   4661:              j=1; /* Temporary Dangerous patch */
                   4662:              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);
                   4663:              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]);
                   4664:              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);
                   4665:            }
                   4666:            k=k+1;
                   4667:            if (j >= jmax){
                   4668:              jmax=j;
                   4669:              ijmax=i;
                   4670:            }
                   4671:            if (j <= jmin){
                   4672:              jmin=j;
                   4673:              ijmin=i;
                   4674:            }
                   4675:            sum=sum+j;
                   4676:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4677:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4678:          }
                   4679:        }
                   4680:        else{
                   4681:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4682: /*       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  4683:                                        
1.227     brouard  4684:          k=k+1;
                   4685:          if (j >= jmax) {
                   4686:            jmax=j;
                   4687:            ijmax=i;
                   4688:          }
                   4689:          else if (j <= jmin){
                   4690:            jmin=j;
                   4691:            ijmin=i;
                   4692:          }
                   4693:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4694:          /*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]);*/
                   4695:          if(j<0){
                   4696:            nberr++;
                   4697:            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]);
                   4698:            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]);
                   4699:          }
                   4700:          sum=sum+j;
                   4701:        }
                   4702:        jk= j/stepm;
                   4703:        jl= j -jk*stepm;
                   4704:        ju= j -(jk+1)*stepm;
                   4705:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4706:          if(jl==0){
                   4707:            dh[mi][i]=jk;
                   4708:            bh[mi][i]=0;
                   4709:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4710:                  * to avoid the price of an extra matrix product in likelihood */
                   4711:            dh[mi][i]=jk+1;
                   4712:            bh[mi][i]=ju;
                   4713:          }
                   4714:        }else{
                   4715:          if(jl <= -ju){
                   4716:            dh[mi][i]=jk;
                   4717:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4718:                                 * is higher than the multiple of stepm and negative otherwise.
                   4719:                                 */
                   4720:          }
                   4721:          else{
                   4722:            dh[mi][i]=jk+1;
                   4723:            bh[mi][i]=ju;
                   4724:          }
                   4725:          if(dh[mi][i]==0){
                   4726:            dh[mi][i]=1; /* At least one step */
                   4727:            bh[mi][i]=ju; /* At least one step */
                   4728:            /*  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);*/
                   4729:          }
                   4730:        } /* end if mle */
1.126     brouard  4731:       }
                   4732:     } /* end wave */
                   4733:   }
                   4734:   jmean=sum/k;
                   4735:   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  4736:   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  4737: }
1.126     brouard  4738: 
                   4739: /*********** Tricode ****************************/
1.220     brouard  4740:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4741: {
1.144     brouard  4742:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4743:   /*     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  4744:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.224     brouard  4745:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4746:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
1.144     brouard  4747:   */
1.130     brouard  4748: 
1.145     brouard  4749:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4750:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4751:   int cptcode=0; /* Modality max of covariates j */
                   4752:   int modmincovj=0; /* Modality min of covariates j */
                   4753: 
                   4754: 
1.220     brouard  4755:   /* cptcoveff=0;  */
1.224     brouard  4756:        /* *cptcov=0; */
1.126     brouard  4757:  
1.144     brouard  4758:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4759: 
1.224     brouard  4760:   /* Loop on covariates without age and products and no quantitative variable */
                   4761:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
1.227     brouard  4762:   for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4763:     for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4764:     if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4765:       switch(Fixed[k]) {
                   4766:       case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.231     brouard  4767:                                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*/
                   4768:                                        ij=(int)(covar[Tvar[k]][i]);
                   4769:                                        /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4770:                                         * If product of Vn*Vm, still boolean *:
                   4771:                                         * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4772:                                         * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4773:                                        /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4774:                                                 modality of the nth covariate of individual i. */
                   4775:                                        if (ij > modmaxcovj)
                   4776:                                                modmaxcovj=ij; 
                   4777:                                        else if (ij < modmincovj) 
                   4778:                                                modmincovj=ij; 
                   4779:                                        if ((ij < -1) && (ij > NCOVMAX)){
                   4780:                                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4781:                                                exit(1);
                   4782:                                        }else
                   4783:                                                Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4784:                                        /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4785:                                        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4786:                                        /* getting the maximum value of the modality of the covariate
                   4787:                                                 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4788:                                                 female ies 1, then modmaxcovj=1.
                   4789:                                        */
                   4790:                                } /* end for loop on individuals i */
                   4791:                                printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4792:                                fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4793:                                cptcode=modmaxcovj;
                   4794:                                /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4795:                                /*for (i=0; i<=cptcode; i++) {*/
                   4796:                                for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4797:                                        printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4798:                                        fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4799:                                        if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4800:                                                if( j != -1){
                   4801:                                                        ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4802:                                                                                                                                 covariate for which somebody answered excluding 
                   4803:                                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4804:                                                }
                   4805:                                                ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4806:                                                                                                                                                covariate for which somebody answered including 
                   4807:                                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
                   4808:                                        }       /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4809:                                                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4810:                                } /* Ndum[-1] number of undefined modalities */
                   4811:                        
                   4812:                                /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4813:                                /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4814:                                /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4815:                                /* modmincovj=3; modmaxcovj = 7; */
                   4816:                                /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4817:                                /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4818:                          /*             defining two dummy variables: variables V1_1 and V1_2.*/
                   4819:              /* nbcode[Tvar[j]][ij]=k; */
                   4820:              /* nbcode[Tvar[j]][1]=0; */
                   4821:              /* nbcode[Tvar[j]][2]=1; */
                   4822:              /* nbcode[Tvar[j]][3]=2; */
                   4823:              /* To be continued (not working yet). */
                   4824:              ij=0; /* ij is similar to i but can jump over null modalities */
                   4825:                                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*/
                   4826:          if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4827:                  break;
                   4828:                }
                   4829:                                        ij++;
                   4830:                                        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*/
                   4831:                                        cptcode = ij; /* New max modality for covar j */
                   4832:                                } /* end of loop on modality i=-1 to 1 or more */
                   4833:                                break;
1.227     brouard  4834:       case 1: /* Testing on varying covariate, could be simple and
                   4835:               * should look at waves or product of fixed *
                   4836:               * varying. No time to test -1, assuming 0 and 1 only */
1.231     brouard  4837:                                ij=0;
                   4838:                                for(i=0; i<=1;i++){
                   4839:                                        nbcode[Tvar[k]][++ij]=i;
                   4840:                                }
                   4841:                                break;
1.227     brouard  4842:       default:
1.231     brouard  4843:                                break;
1.227     brouard  4844:       } /* end switch */
                   4845:     } /* end dummy test */
1.225     brouard  4846:     
1.192     brouard  4847:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4848:     /*         /\*recode from 0 *\/ */
                   4849:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4850:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4851:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4852:     /*         } */
                   4853:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4854:     /*         if (ij > ncodemax[j]) { */
                   4855:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4856:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4857:     /*           break; */
                   4858:     /*         } */
                   4859:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4860:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4861:   
1.225     brouard  4862:   for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.227     brouard  4863:   /* Look at fixed dummy (single or product) covariates to check empty modalities */
1.187     brouard  4864:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.225     brouard  4865:     /* 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  4866:     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 */ 
                   4867:     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 */
                   4868:     /* 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  4869:   } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4870:   
                   4871:   ij=0;
1.227     brouard  4872:   /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4873:   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  4874:     /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.227     brouard  4875:     /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4876:     if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4877:       /* If product not in single variable we don't print results */
1.225     brouard  4878:       /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.230     brouard  4879:       ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   4880:       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*/
                   4881:       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  4882:       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  4883:       if(Fixed[k]!=0)
                   4884:         anyvaryingduminmodel=1;
1.231     brouard  4885:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   4886:                        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4887:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   4888:                        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   4889:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   4890:                        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
1.227     brouard  4891:     } 
1.225     brouard  4892:   } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   4893:   /* ij--; */
                   4894:   /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4895:   *cptcov=ij; /*Number of total real effective covariates: effective
1.231     brouard  4896:                                                         * because they can be excluded from the model and real
                   4897:                                                         * if in the model but excluded because missing values, but how to get k from ij?*/
1.227     brouard  4898:   for(j=ij+1; j<= cptcovt; j++){
                   4899:     Tvaraff[j]=0;
                   4900:     Tmodelind[j]=0;
                   4901:   }
1.228     brouard  4902:   for(j=ntveff+1; j<= cptcovt; j++){
                   4903:     TmodelInvind[j]=0;
                   4904:   }
1.227     brouard  4905:   /* To be sorted */
                   4906:   ;
1.126     brouard  4907: }
                   4908: 
1.145     brouard  4909: 
1.126     brouard  4910: /*********** Health Expectancies ****************/
                   4911: 
1.235     brouard  4912:  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  4913: 
                   4914: {
                   4915:   /* Health expectancies, no variances */
1.164     brouard  4916:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4917:   int nhstepma, nstepma; /* Decreasing with age */
                   4918:   double age, agelim, hf;
                   4919:   double ***p3mat;
                   4920:   double eip;
                   4921: 
1.238   ! brouard  4922:   /* pstamp(ficreseij); */
1.126     brouard  4923:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4924:   fprintf(ficreseij,"# Age");
                   4925:   for(i=1; i<=nlstate;i++){
                   4926:     for(j=1; j<=nlstate;j++){
                   4927:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4928:     }
                   4929:     fprintf(ficreseij," e%1d. ",i);
                   4930:   }
                   4931:   fprintf(ficreseij,"\n");
                   4932: 
                   4933:   
                   4934:   if(estepm < stepm){
                   4935:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4936:   }
                   4937:   else  hstepm=estepm;   
                   4938:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4939:    * This is mainly to measure the difference between two models: for example
                   4940:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4941:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4942:    * progression in between and thus overestimating or underestimating according
                   4943:    * to the curvature of the survival function. If, for the same date, we 
                   4944:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4945:    * to compare the new estimate of Life expectancy with the same linear 
                   4946:    * hypothesis. A more precise result, taking into account a more precise
                   4947:    * curvature will be obtained if estepm is as small as stepm. */
                   4948: 
                   4949:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4950:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4951:      nhstepm is the number of hstepm from age to agelim 
                   4952:      nstepm is the number of stepm from age to agelin. 
                   4953:      Look at hpijx to understand the reason of that which relies in memory size
                   4954:      and note for a fixed period like estepm months */
                   4955:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4956:      survival function given by stepm (the optimization length). Unfortunately it
                   4957:      means that if the survival funtion is printed only each two years of age and if
                   4958:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4959:      results. So we changed our mind and took the option of the best precision.
                   4960:   */
                   4961:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4962: 
                   4963:   agelim=AGESUP;
                   4964:   /* If stepm=6 months */
                   4965:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4966:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4967:     
                   4968: /* nhstepm age range expressed in number of stepm */
                   4969:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4970:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4971:   /* if (stepm >= YEARM) hstepm=1;*/
                   4972:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4973:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4974: 
                   4975:   for (age=bage; age<=fage; age ++){ 
                   4976:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4977:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4978:     /* if (stepm >= YEARM) hstepm=1;*/
                   4979:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4980: 
                   4981:     /* If stepm=6 months */
                   4982:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4983:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4984:     
1.235     brouard  4985:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  4986:     
                   4987:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4988:     
                   4989:     printf("%d|",(int)age);fflush(stdout);
                   4990:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4991:     
                   4992:     /* Computing expectancies */
                   4993:     for(i=1; i<=nlstate;i++)
                   4994:       for(j=1; j<=nlstate;j++)
                   4995:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4996:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4997:          
                   4998:          /* 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]);*/
                   4999: 
                   5000:        }
                   5001: 
                   5002:     fprintf(ficreseij,"%3.0f",age );
                   5003:     for(i=1; i<=nlstate;i++){
                   5004:       eip=0;
                   5005:       for(j=1; j<=nlstate;j++){
                   5006:        eip +=eij[i][j][(int)age];
                   5007:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5008:       }
                   5009:       fprintf(ficreseij,"%9.4f", eip );
                   5010:     }
                   5011:     fprintf(ficreseij,"\n");
                   5012:     
                   5013:   }
                   5014:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5015:   printf("\n");
                   5016:   fprintf(ficlog,"\n");
                   5017:   
                   5018: }
                   5019: 
1.235     brouard  5020:  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  5021: 
                   5022: {
                   5023:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5024:      to initial status i, ei. .
1.126     brouard  5025:   */
                   5026:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5027:   int nhstepma, nstepma; /* Decreasing with age */
                   5028:   double age, agelim, hf;
                   5029:   double ***p3matp, ***p3matm, ***varhe;
                   5030:   double **dnewm,**doldm;
                   5031:   double *xp, *xm;
                   5032:   double **gp, **gm;
                   5033:   double ***gradg, ***trgradg;
                   5034:   int theta;
                   5035: 
                   5036:   double eip, vip;
                   5037: 
                   5038:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5039:   xp=vector(1,npar);
                   5040:   xm=vector(1,npar);
                   5041:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5042:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5043:   
                   5044:   pstamp(ficresstdeij);
                   5045:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5046:   fprintf(ficresstdeij,"# Age");
                   5047:   for(i=1; i<=nlstate;i++){
                   5048:     for(j=1; j<=nlstate;j++)
                   5049:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5050:     fprintf(ficresstdeij," e%1d. ",i);
                   5051:   }
                   5052:   fprintf(ficresstdeij,"\n");
                   5053: 
                   5054:   pstamp(ficrescveij);
                   5055:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5056:   fprintf(ficrescveij,"# Age");
                   5057:   for(i=1; i<=nlstate;i++)
                   5058:     for(j=1; j<=nlstate;j++){
                   5059:       cptj= (j-1)*nlstate+i;
                   5060:       for(i2=1; i2<=nlstate;i2++)
                   5061:        for(j2=1; j2<=nlstate;j2++){
                   5062:          cptj2= (j2-1)*nlstate+i2;
                   5063:          if(cptj2 <= cptj)
                   5064:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5065:        }
                   5066:     }
                   5067:   fprintf(ficrescveij,"\n");
                   5068:   
                   5069:   if(estepm < stepm){
                   5070:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5071:   }
                   5072:   else  hstepm=estepm;   
                   5073:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5074:    * This is mainly to measure the difference between two models: for example
                   5075:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5076:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5077:    * progression in between and thus overestimating or underestimating according
                   5078:    * to the curvature of the survival function. If, for the same date, we 
                   5079:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5080:    * to compare the new estimate of Life expectancy with the same linear 
                   5081:    * hypothesis. A more precise result, taking into account a more precise
                   5082:    * curvature will be obtained if estepm is as small as stepm. */
                   5083: 
                   5084:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5085:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5086:      nhstepm is the number of hstepm from age to agelim 
                   5087:      nstepm is the number of stepm from age to agelin. 
                   5088:      Look at hpijx to understand the reason of that which relies in memory size
                   5089:      and note for a fixed period like estepm months */
                   5090:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5091:      survival function given by stepm (the optimization length). Unfortunately it
                   5092:      means that if the survival funtion is printed only each two years of age and if
                   5093:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5094:      results. So we changed our mind and took the option of the best precision.
                   5095:   */
                   5096:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5097: 
                   5098:   /* If stepm=6 months */
                   5099:   /* nhstepm age range expressed in number of stepm */
                   5100:   agelim=AGESUP;
                   5101:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5102:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5103:   /* if (stepm >= YEARM) hstepm=1;*/
                   5104:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5105:   
                   5106:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5107:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5108:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5109:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5110:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5111:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5112: 
                   5113:   for (age=bage; age<=fage; age ++){ 
                   5114:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5115:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5116:     /* if (stepm >= YEARM) hstepm=1;*/
                   5117:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5118:                
1.126     brouard  5119:     /* If stepm=6 months */
                   5120:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5121:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5122:     
                   5123:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5124:                
1.126     brouard  5125:     /* Computing  Variances of health expectancies */
                   5126:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5127:        decrease memory allocation */
                   5128:     for(theta=1; theta <=npar; theta++){
                   5129:       for(i=1; i<=npar; i++){ 
1.222     brouard  5130:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5131:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5132:       }
1.235     brouard  5133:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5134:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5135:                        
1.126     brouard  5136:       for(j=1; j<= nlstate; j++){
1.222     brouard  5137:        for(i=1; i<=nlstate; i++){
                   5138:          for(h=0; h<=nhstepm-1; h++){
                   5139:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5140:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5141:          }
                   5142:        }
1.126     brouard  5143:       }
1.218     brouard  5144:                        
1.126     brouard  5145:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5146:        for(h=0; h<=nhstepm-1; h++){
                   5147:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5148:        }
1.126     brouard  5149:     }/* End theta */
                   5150:     
                   5151:     
                   5152:     for(h=0; h<=nhstepm-1; h++)
                   5153:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5154:        for(theta=1; theta <=npar; theta++)
                   5155:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5156:     
1.218     brouard  5157:                
1.222     brouard  5158:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5159:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5160:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5161:                
1.222     brouard  5162:     printf("%d|",(int)age);fflush(stdout);
                   5163:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5164:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5165:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5166:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5167:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5168:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5169:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5170:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5171:       }
                   5172:     }
1.218     brouard  5173:                
1.126     brouard  5174:     /* Computing expectancies */
1.235     brouard  5175:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5176:     for(i=1; i<=nlstate;i++)
                   5177:       for(j=1; j<=nlstate;j++)
1.222     brouard  5178:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5179:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5180:                                        
1.222     brouard  5181:          /* 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  5182:                                        
1.222     brouard  5183:        }
1.218     brouard  5184:                
1.126     brouard  5185:     fprintf(ficresstdeij,"%3.0f",age );
                   5186:     for(i=1; i<=nlstate;i++){
                   5187:       eip=0.;
                   5188:       vip=0.;
                   5189:       for(j=1; j<=nlstate;j++){
1.222     brouard  5190:        eip += eij[i][j][(int)age];
                   5191:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5192:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5193:        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  5194:       }
                   5195:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5196:     }
                   5197:     fprintf(ficresstdeij,"\n");
1.218     brouard  5198:                
1.126     brouard  5199:     fprintf(ficrescveij,"%3.0f",age );
                   5200:     for(i=1; i<=nlstate;i++)
                   5201:       for(j=1; j<=nlstate;j++){
1.222     brouard  5202:        cptj= (j-1)*nlstate+i;
                   5203:        for(i2=1; i2<=nlstate;i2++)
                   5204:          for(j2=1; j2<=nlstate;j2++){
                   5205:            cptj2= (j2-1)*nlstate+i2;
                   5206:            if(cptj2 <= cptj)
                   5207:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5208:          }
1.126     brouard  5209:       }
                   5210:     fprintf(ficrescveij,"\n");
1.218     brouard  5211:                
1.126     brouard  5212:   }
                   5213:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5214:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5215:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5216:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5217:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5218:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5219:   printf("\n");
                   5220:   fprintf(ficlog,"\n");
1.218     brouard  5221:        
1.126     brouard  5222:   free_vector(xm,1,npar);
                   5223:   free_vector(xp,1,npar);
                   5224:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5225:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5226:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5227: }
1.218     brouard  5228:  
1.126     brouard  5229: /************ Variance ******************/
1.235     brouard  5230:  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  5231:  {
                   5232:    /* Variance of health expectancies */
                   5233:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5234:    /* double **newm;*/
                   5235:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5236:   
                   5237:    /* int movingaverage(); */
                   5238:    double **dnewm,**doldm;
                   5239:    double **dnewmp,**doldmp;
                   5240:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5241:    int k;
                   5242:    double *xp;
                   5243:    double **gp, **gm;  /* for var eij */
                   5244:    double ***gradg, ***trgradg; /*for var eij */
                   5245:    double **gradgp, **trgradgp; /* for var p point j */
                   5246:    double *gpp, *gmp; /* for var p point j */
                   5247:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5248:    double ***p3mat;
                   5249:    double age,agelim, hf;
                   5250:    /* double ***mobaverage; */
                   5251:    int theta;
                   5252:    char digit[4];
                   5253:    char digitp[25];
                   5254: 
                   5255:    char fileresprobmorprev[FILENAMELENGTH];
                   5256: 
                   5257:    if(popbased==1){
                   5258:      if(mobilav!=0)
                   5259:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5260:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5261:    }
                   5262:    else 
                   5263:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5264: 
1.218     brouard  5265:    /* if (mobilav!=0) { */
                   5266:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5267:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5268:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5269:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5270:    /*   } */
                   5271:    /* } */
                   5272: 
                   5273:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5274:    sprintf(digit,"%-d",ij);
                   5275:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5276:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5277:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5278:    strcat(fileresprobmorprev,fileresu);
                   5279:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5280:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5281:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5282:    }
                   5283:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5284:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5285:    pstamp(ficresprobmorprev);
                   5286:    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  5287:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
        !          5288:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
        !          5289:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          5290:    }
        !          5291:    for(j=1;j<=cptcoveff;j++) 
        !          5292:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
        !          5293:    fprintf(ficresprobmorprev,"\n");
        !          5294: 
1.218     brouard  5295:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5296:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5297:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5298:      for(i=1; i<=nlstate;i++)
                   5299:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5300:    }  
                   5301:    fprintf(ficresprobmorprev,"\n");
                   5302:   
                   5303:    fprintf(ficgp,"\n# Routine varevsij");
                   5304:    fprintf(ficgp,"\nunset title \n");
                   5305:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5306:    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");
                   5307:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5308:    /*   } */
                   5309:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5310:    pstamp(ficresvij);
                   5311:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5312:    if(popbased==1)
                   5313:      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);
                   5314:    else
                   5315:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5316:    fprintf(ficresvij,"# Age");
                   5317:    for(i=1; i<=nlstate;i++)
                   5318:      for(j=1; j<=nlstate;j++)
                   5319:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5320:    fprintf(ficresvij,"\n");
                   5321: 
                   5322:    xp=vector(1,npar);
                   5323:    dnewm=matrix(1,nlstate,1,npar);
                   5324:    doldm=matrix(1,nlstate,1,nlstate);
                   5325:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5326:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5327: 
                   5328:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5329:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5330:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5331:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5332:   
1.218     brouard  5333:    if(estepm < stepm){
                   5334:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5335:    }
                   5336:    else  hstepm=estepm;   
                   5337:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5338:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5339:       nhstepm is the number of hstepm from age to agelim 
                   5340:       nstepm is the number of stepm from age to agelim. 
                   5341:       Look at function hpijx to understand why because of memory size limitations, 
                   5342:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5343:       survival function given by stepm (the optimization length). Unfortunately it
                   5344:       means that if the survival funtion is printed every two years of age and if
                   5345:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5346:       results. So we changed our mind and took the option of the best precision.
                   5347:    */
                   5348:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5349:    agelim = AGESUP;
                   5350:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5351:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5352:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5353:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5354:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5355:      gp=matrix(0,nhstepm,1,nlstate);
                   5356:      gm=matrix(0,nhstepm,1,nlstate);
                   5357:                
                   5358:                
                   5359:      for(theta=1; theta <=npar; theta++){
                   5360:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5361:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5362:        }
                   5363:                        
1.235     brouard  5364:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
1.218     brouard  5365:                        
                   5366:        if (popbased==1) {
                   5367:         if(mobilav ==0){
                   5368:           for(i=1; i<=nlstate;i++)
                   5369:             prlim[i][i]=probs[(int)age][i][ij];
                   5370:         }else{ /* mobilav */ 
                   5371:           for(i=1; i<=nlstate;i++)
                   5372:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5373:         }
                   5374:        }
                   5375:                        
1.235     brouard  5376:        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  5377:        for(j=1; j<= nlstate; j++){
                   5378:         for(h=0; h<=nhstepm; h++){
                   5379:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5380:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5381:         }
                   5382:        }
                   5383:        /* Next for computing probability of death (h=1 means
                   5384:          computed over hstepm matrices product = hstepm*stepm months) 
                   5385:          as a weighted average of prlim.
                   5386:        */
                   5387:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5388:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5389:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5390:        }    
                   5391:        /* end probability of death */
                   5392:                        
                   5393:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5394:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5395:                        
1.235     brouard  5396:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nresult);
1.218     brouard  5397:                        
                   5398:        if (popbased==1) {
                   5399:         if(mobilav ==0){
                   5400:           for(i=1; i<=nlstate;i++)
                   5401:             prlim[i][i]=probs[(int)age][i][ij];
                   5402:         }else{ /* mobilav */ 
                   5403:           for(i=1; i<=nlstate;i++)
                   5404:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5405:         }
                   5406:        }
                   5407:                        
1.235     brouard  5408:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5409:                        
                   5410:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5411:         for(h=0; h<=nhstepm; h++){
                   5412:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5413:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5414:         }
                   5415:        }
                   5416:        /* This for computing probability of death (h=1 means
                   5417:          computed over hstepm matrices product = hstepm*stepm months) 
                   5418:          as a weighted average of prlim.
                   5419:        */
                   5420:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5421:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5422:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5423:        }    
                   5424:        /* end probability of death */
                   5425:                        
                   5426:        for(j=1; j<= nlstate; j++) /* vareij */
                   5427:         for(h=0; h<=nhstepm; h++){
                   5428:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5429:         }
                   5430:                        
                   5431:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5432:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5433:        }
                   5434:                        
                   5435:      } /* End theta */
                   5436:                
                   5437:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5438:                
                   5439:      for(h=0; h<=nhstepm; h++) /* veij */
                   5440:        for(j=1; j<=nlstate;j++)
                   5441:         for(theta=1; theta <=npar; theta++)
                   5442:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5443:                
                   5444:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5445:        for(theta=1; theta <=npar; theta++)
                   5446:         trgradgp[j][theta]=gradgp[theta][j];
                   5447:                
                   5448:                
                   5449:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5450:      for(i=1;i<=nlstate;i++)
                   5451:        for(j=1;j<=nlstate;j++)
                   5452:         vareij[i][j][(int)age] =0.;
                   5453:                
                   5454:      for(h=0;h<=nhstepm;h++){
                   5455:        for(k=0;k<=nhstepm;k++){
                   5456:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5457:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5458:         for(i=1;i<=nlstate;i++)
                   5459:           for(j=1;j<=nlstate;j++)
                   5460:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5461:        }
                   5462:      }
                   5463:                
                   5464:      /* pptj */
                   5465:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5466:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5467:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5468:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5469:         varppt[j][i]=doldmp[j][i];
                   5470:      /* end ppptj */
                   5471:      /*  x centered again */
                   5472:                
1.235     brouard  5473:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
1.218     brouard  5474:                
                   5475:      if (popbased==1) {
                   5476:        if(mobilav ==0){
                   5477:         for(i=1; i<=nlstate;i++)
                   5478:           prlim[i][i]=probs[(int)age][i][ij];
                   5479:        }else{ /* mobilav */ 
                   5480:         for(i=1; i<=nlstate;i++)
                   5481:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5482:        }
                   5483:      }
                   5484:                
                   5485:      /* This for computing probability of death (h=1 means
                   5486:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5487:        as a weighted average of prlim.
                   5488:      */
1.235     brouard  5489:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5490:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5491:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5492:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5493:      }    
                   5494:      /* end probability of death */
                   5495:                
                   5496:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5497:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5498:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5499:        for(i=1; i<=nlstate;i++){
                   5500:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5501:        }
                   5502:      } 
                   5503:      fprintf(ficresprobmorprev,"\n");
                   5504:                
                   5505:      fprintf(ficresvij,"%.0f ",age );
                   5506:      for(i=1; i<=nlstate;i++)
                   5507:        for(j=1; j<=nlstate;j++){
                   5508:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5509:        }
                   5510:      fprintf(ficresvij,"\n");
                   5511:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5512:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5513:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5514:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5515:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5516:    } /* End age */
                   5517:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5518:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5519:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5520:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5521:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5522:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5523:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5524:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5525:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5526:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5527:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5528:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5529:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5530:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5531:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5532:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5533:    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);
                   5534:    /*  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  5535:     */
1.218     brouard  5536:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5537:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5538: 
1.218     brouard  5539:    free_vector(xp,1,npar);
                   5540:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5541:    free_matrix(dnewm,1,nlstate,1,npar);
                   5542:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5543:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5544:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5545:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5546:    fclose(ficresprobmorprev);
                   5547:    fflush(ficgp);
                   5548:    fflush(fichtm); 
                   5549:  }  /* end varevsij */
1.126     brouard  5550: 
                   5551: /************ Variance of prevlim ******************/
1.235     brouard  5552:  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  5553: {
1.205     brouard  5554:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5555:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5556: 
1.126     brouard  5557:   double **dnewm,**doldm;
                   5558:   int i, j, nhstepm, hstepm;
                   5559:   double *xp;
                   5560:   double *gp, *gm;
                   5561:   double **gradg, **trgradg;
1.208     brouard  5562:   double **mgm, **mgp;
1.126     brouard  5563:   double age,agelim;
                   5564:   int theta;
                   5565:   
                   5566:   pstamp(ficresvpl);
                   5567:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5568:   fprintf(ficresvpl,"# Age");
                   5569:   for(i=1; i<=nlstate;i++)
                   5570:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5571:   fprintf(ficresvpl,"\n");
                   5572: 
                   5573:   xp=vector(1,npar);
                   5574:   dnewm=matrix(1,nlstate,1,npar);
                   5575:   doldm=matrix(1,nlstate,1,nlstate);
                   5576:   
                   5577:   hstepm=1*YEARM; /* Every year of age */
                   5578:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5579:   agelim = AGESUP;
                   5580:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5581:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5582:     if (stepm >= YEARM) hstepm=1;
                   5583:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5584:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5585:     mgp=matrix(1,npar,1,nlstate);
                   5586:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5587:     gp=vector(1,nlstate);
                   5588:     gm=vector(1,nlstate);
                   5589: 
                   5590:     for(theta=1; theta <=npar; theta++){
                   5591:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5592:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5593:       }
1.209     brouard  5594:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5595:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5596:       else
1.235     brouard  5597:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5598:       for(i=1;i<=nlstate;i++){
1.126     brouard  5599:        gp[i] = prlim[i][i];
1.208     brouard  5600:        mgp[theta][i] = prlim[i][i];
                   5601:       }
1.126     brouard  5602:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5603:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5604:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5605:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5606:       else
1.235     brouard  5607:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5608:       for(i=1;i<=nlstate;i++){
1.126     brouard  5609:        gm[i] = prlim[i][i];
1.208     brouard  5610:        mgm[theta][i] = prlim[i][i];
                   5611:       }
1.126     brouard  5612:       for(i=1;i<=nlstate;i++)
                   5613:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5614:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5615:     } /* End theta */
                   5616: 
                   5617:     trgradg =matrix(1,nlstate,1,npar);
                   5618: 
                   5619:     for(j=1; j<=nlstate;j++)
                   5620:       for(theta=1; theta <=npar; theta++)
                   5621:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5622:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5623:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5624:     /*   for(j=1; j<=nlstate;j++){ */
                   5625:     /*         printf(" %d ",j); */
                   5626:     /*         for(theta=1; theta <=npar; theta++) */
                   5627:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5628:     /*         printf("\n "); */
                   5629:     /*   } */
                   5630:     /* } */
                   5631:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5632:     /*   printf("\n gradg %d ",(int)age); */
                   5633:     /*   for(j=1; j<=nlstate;j++){ */
                   5634:     /*         printf("%d ",j); */
                   5635:     /*         for(theta=1; theta <=npar; theta++) */
                   5636:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5637:     /*         printf("\n "); */
                   5638:     /*   } */
                   5639:     /* } */
1.126     brouard  5640: 
                   5641:     for(i=1;i<=nlstate;i++)
                   5642:       varpl[i][(int)age] =0.;
1.209     brouard  5643:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5644:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5645:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5646:     }else{
1.126     brouard  5647:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5648:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5649:     }
1.126     brouard  5650:     for(i=1;i<=nlstate;i++)
                   5651:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5652: 
                   5653:     fprintf(ficresvpl,"%.0f ",age );
                   5654:     for(i=1; i<=nlstate;i++)
                   5655:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5656:     fprintf(ficresvpl,"\n");
                   5657:     free_vector(gp,1,nlstate);
                   5658:     free_vector(gm,1,nlstate);
1.208     brouard  5659:     free_matrix(mgm,1,npar,1,nlstate);
                   5660:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5661:     free_matrix(gradg,1,npar,1,nlstate);
                   5662:     free_matrix(trgradg,1,nlstate,1,npar);
                   5663:   } /* End age */
                   5664: 
                   5665:   free_vector(xp,1,npar);
                   5666:   free_matrix(doldm,1,nlstate,1,npar);
                   5667:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5668: 
                   5669: }
                   5670: 
                   5671: /************ Variance of one-step probabilities  ******************/
                   5672: 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  5673:  {
                   5674:    int i, j=0,  k1, l1, tj;
                   5675:    int k2, l2, j1,  z1;
                   5676:    int k=0, l;
                   5677:    int first=1, first1, first2;
                   5678:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5679:    double **dnewm,**doldm;
                   5680:    double *xp;
                   5681:    double *gp, *gm;
                   5682:    double **gradg, **trgradg;
                   5683:    double **mu;
                   5684:    double age, cov[NCOVMAX+1];
                   5685:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5686:    int theta;
                   5687:    char fileresprob[FILENAMELENGTH];
                   5688:    char fileresprobcov[FILENAMELENGTH];
                   5689:    char fileresprobcor[FILENAMELENGTH];
                   5690:    double ***varpij;
                   5691: 
                   5692:    strcpy(fileresprob,"PROB_"); 
                   5693:    strcat(fileresprob,fileres);
                   5694:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5695:      printf("Problem with resultfile: %s\n", fileresprob);
                   5696:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5697:    }
                   5698:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5699:    strcat(fileresprobcov,fileresu);
                   5700:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5701:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5702:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5703:    }
                   5704:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5705:    strcat(fileresprobcor,fileresu);
                   5706:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5707:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5708:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5709:    }
                   5710:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5711:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5712:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5713:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5714:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5715:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5716:    pstamp(ficresprob);
                   5717:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5718:    fprintf(ficresprob,"# Age");
                   5719:    pstamp(ficresprobcov);
                   5720:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5721:    fprintf(ficresprobcov,"# Age");
                   5722:    pstamp(ficresprobcor);
                   5723:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5724:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5725: 
                   5726: 
1.222     brouard  5727:    for(i=1; i<=nlstate;i++)
                   5728:      for(j=1; j<=(nlstate+ndeath);j++){
                   5729:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5730:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5731:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5732:      }  
                   5733:    /* fprintf(ficresprob,"\n");
                   5734:       fprintf(ficresprobcov,"\n");
                   5735:       fprintf(ficresprobcor,"\n");
                   5736:    */
                   5737:    xp=vector(1,npar);
                   5738:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5739:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5740:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5741:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5742:    first=1;
                   5743:    fprintf(ficgp,"\n# Routine varprob");
                   5744:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5745:    fprintf(fichtm,"\n");
                   5746: 
                   5747:    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);
                   5748:    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);
                   5749:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5750: and drawn. It helps understanding how is the covariance between two incidences.\
                   5751:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5752:    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  5753: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5754: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5755: standard deviations wide on each axis. <br>\
                   5756:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5757:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5758: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5759: 
1.222     brouard  5760:    cov[1]=1;
                   5761:    /* tj=cptcoveff; */
1.225     brouard  5762:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5763:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5764:    j1=0;
1.224     brouard  5765:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5766:      if  (cptcovn>0) {
                   5767:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5768:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5769:        fprintf(ficresprob, "**********\n#\n");
                   5770:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5771:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5772:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5773:                        
1.222     brouard  5774:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5775:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5776:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5777:                        
                   5778:                        
1.222     brouard  5779:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5780:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5781:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5782:                        
1.222     brouard  5783:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5784:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5785:        fprintf(ficresprobcor, "**********\n#");    
                   5786:        if(invalidvarcomb[j1]){
                   5787:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5788:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5789:         continue;
                   5790:        }
                   5791:      }
                   5792:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5793:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5794:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5795:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5796:      for (age=bage; age<=fage; age ++){ 
                   5797:        cov[2]=age;
                   5798:        if(nagesqr==1)
                   5799:         cov[3]= age*age;
                   5800:        for (k=1; k<=cptcovn;k++) {
                   5801:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5802:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5803:                                                                    * 1  1 1 1 1
                   5804:                                                                    * 2  2 1 1 1
                   5805:                                                                    * 3  1 2 1 1
                   5806:                                                                    */
                   5807:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5808:        }
                   5809:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5810:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5811:        for (k=1; k<=cptcovprod;k++)
                   5812:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5813:                        
                   5814:                        
1.222     brouard  5815:        for(theta=1; theta <=npar; theta++){
                   5816:         for(i=1; i<=npar; i++)
                   5817:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5818:                                
1.222     brouard  5819:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5820:                                
1.222     brouard  5821:         k=0;
                   5822:         for(i=1; i<= (nlstate); i++){
                   5823:           for(j=1; j<=(nlstate+ndeath);j++){
                   5824:             k=k+1;
                   5825:             gp[k]=pmmij[i][j];
                   5826:           }
                   5827:         }
1.220     brouard  5828:                                
1.222     brouard  5829:         for(i=1; i<=npar; i++)
                   5830:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5831:                                
1.222     brouard  5832:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5833:         k=0;
                   5834:         for(i=1; i<=(nlstate); i++){
                   5835:           for(j=1; j<=(nlstate+ndeath);j++){
                   5836:             k=k+1;
                   5837:             gm[k]=pmmij[i][j];
                   5838:           }
                   5839:         }
1.220     brouard  5840:                                
1.222     brouard  5841:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5842:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5843:        }
1.126     brouard  5844: 
1.222     brouard  5845:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5846:         for(theta=1; theta <=npar; theta++)
                   5847:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5848:                        
1.222     brouard  5849:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5850:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5851:                        
1.222     brouard  5852:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5853:                        
1.222     brouard  5854:        k=0;
                   5855:        for(i=1; i<=(nlstate); i++){
                   5856:         for(j=1; j<=(nlstate+ndeath);j++){
                   5857:           k=k+1;
                   5858:           mu[k][(int) age]=pmmij[i][j];
                   5859:         }
                   5860:        }
                   5861:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5862:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5863:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5864:                        
1.222     brouard  5865:        /*printf("\n%d ",(int)age);
                   5866:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5867:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5868:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5869:         }*/
1.220     brouard  5870:                        
1.222     brouard  5871:        fprintf(ficresprob,"\n%d ",(int)age);
                   5872:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5873:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5874:                        
1.222     brouard  5875:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5876:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5877:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5878:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5879:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5880:        }
                   5881:        i=0;
                   5882:        for (k=1; k<=(nlstate);k++){
                   5883:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5884:           i++;
                   5885:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5886:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5887:           for (j=1; j<=i;j++){
                   5888:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5889:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5890:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5891:           }
                   5892:         }
                   5893:        }/* end of loop for state */
                   5894:      } /* end of loop for age */
                   5895:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5896:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5897:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5898:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5899:     
                   5900:      /* Confidence intervalle of pij  */
                   5901:      /*
                   5902:        fprintf(ficgp,"\nunset parametric;unset label");
                   5903:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5904:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5905:        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);
                   5906:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5907:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5908:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5909:      */
                   5910:                
                   5911:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5912:      first1=1;first2=2;
                   5913:      for (k2=1; k2<=(nlstate);k2++){
                   5914:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5915:         if(l2==k2) continue;
                   5916:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5917:         for (k1=1; k1<=(nlstate);k1++){
                   5918:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5919:             if(l1==k1) continue;
                   5920:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5921:             if(i<=j) continue;
                   5922:             for (age=bage; age<=fage; age ++){ 
                   5923:               if ((int)age %5==0){
                   5924:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5925:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5926:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5927:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5928:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5929:                 c12=cv12/sqrt(v1*v2);
                   5930:                 /* Computing eigen value of matrix of covariance */
                   5931:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5932:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5933:                 if ((lc2 <0) || (lc1 <0) ){
                   5934:                   if(first2==1){
                   5935:                     first1=0;
                   5936:                     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);
                   5937:                   }
                   5938:                   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);
                   5939:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5940:                   /* lc2=fabs(lc2); */
                   5941:                 }
1.220     brouard  5942:                                                                
1.222     brouard  5943:                 /* Eigen vectors */
                   5944:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5945:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5946:                 v21=(lc1-v1)/cv12*v11;
                   5947:                 v12=-v21;
                   5948:                 v22=v11;
                   5949:                 tnalp=v21/v11;
                   5950:                 if(first1==1){
                   5951:                   first1=0;
                   5952:                   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);
                   5953:                 }
                   5954:                 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);
                   5955:                 /*printf(fignu*/
                   5956:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5957:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5958:                 if(first==1){
                   5959:                   first=0;
                   5960:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5961:                   fprintf(ficgp,"\nset parametric;unset label");
                   5962:                   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);
                   5963:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   5964:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  5965:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5966: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  5967:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   5968:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5969:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5970:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5971:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5972:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5973:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5974:                   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",      \
                   5975:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   5976:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5977:                 }else{
                   5978:                   first=0;
                   5979:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5980:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5981:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5982:                   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", \
                   5983:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   5984:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5985:                 }/* if first */
                   5986:               } /* age mod 5 */
                   5987:             } /* end loop age */
                   5988:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5989:             first=1;
                   5990:           } /*l12 */
                   5991:         } /* k12 */
                   5992:        } /*l1 */
                   5993:      }/* k1 */
                   5994:    }  /* loop on combination of covariates j1 */
                   5995:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5996:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5997:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5998:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5999:    free_vector(xp,1,npar);
                   6000:    fclose(ficresprob);
                   6001:    fclose(ficresprobcov);
                   6002:    fclose(ficresprobcor);
                   6003:    fflush(ficgp);
                   6004:    fflush(fichtmcov);
                   6005:  }
1.126     brouard  6006: 
                   6007: 
                   6008: /******************* Printing html file ***********/
1.201     brouard  6009: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6010:                  int lastpass, int stepm, int weightopt, char model[],\
                   6011:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6012:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6013:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6014:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6015:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6016: 
                   6017:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6018:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6019: </ul>");
1.237     brouard  6020:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6021: </ul>", model);
1.214     brouard  6022:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6023:    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",
                   6024:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6025:    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  6026:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6027:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6028:    fprintf(fichtm,"\
                   6029:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6030:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6031:    fprintf(fichtm,"\
1.217     brouard  6032:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6033:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6034:    fprintf(fichtm,"\
1.126     brouard  6035:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6036:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6037:    fprintf(fichtm,"\
1.217     brouard  6038:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6039:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6040:    fprintf(fichtm,"\
1.211     brouard  6041:  - (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  6042:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6043:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6044:    if(prevfcast==1){
                   6045:      fprintf(fichtm,"\
                   6046:  - Prevalence projections by age and states:                           \
1.201     brouard  6047:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6048:    }
1.126     brouard  6049: 
1.222     brouard  6050:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6051: 
1.225     brouard  6052:    m=pow(2,cptcoveff);
1.222     brouard  6053:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6054: 
1.222     brouard  6055:    jj1=0;
1.237     brouard  6056: 
                   6057:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.222     brouard  6058:    for(k1=1; k1<=m;k1++){
1.237     brouard  6059:      if(TKresult[nres]!= k1)
                   6060:        continue;
1.220     brouard  6061: 
1.222     brouard  6062:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6063:      jj1++;
                   6064:      if (cptcovn > 0) {
                   6065:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6066:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6067:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6068:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6069:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6070:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6071:        }
1.237     brouard  6072:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6073:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6074:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6075:       }
                   6076:        
1.230     brouard  6077:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6078:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6079:        if(invalidvarcomb[k1]){
                   6080:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6081:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6082:         continue;
                   6083:        }
                   6084:      }
                   6085:      /* aij, bij */
                   6086:      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  6087: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222     brouard  6088:      /* Pij */
                   6089:      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  6090: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222     brouard  6091:      /* Quasi-incidences */
                   6092:      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  6093:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6094:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   6095: 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  6096: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222     brouard  6097:      /* Survival functions (period) in state j */
                   6098:      for(cpt=1; cpt<=nlstate;cpt++){
                   6099:        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  6100: <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  6101:      }
                   6102:      /* State specific survival functions (period) */
                   6103:      for(cpt=1; cpt<=nlstate;cpt++){
                   6104:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6105:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  6106:  <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  6107:      }
                   6108:      /* Period (stable) prevalence in each health state */
                   6109:      for(cpt=1; cpt<=nlstate;cpt++){
                   6110:        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  6111: <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  6112:      }
                   6113:      if(backcast==1){
                   6114:        /* Period (stable) back prevalence in each health state */
                   6115:        for(cpt=1; cpt<=nlstate;cpt++){
                   6116:         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  6117: <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  6118:        }
1.217     brouard  6119:      }
1.222     brouard  6120:      if(prevfcast==1){
                   6121:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6122:        for(cpt=1; cpt<=nlstate;cpt++){
                   6123:         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  6124: <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  6125:        }
                   6126:      }
1.220     brouard  6127:         
1.222     brouard  6128:      for(cpt=1; cpt<=nlstate;cpt++) {
                   6129:        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  6130: <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  6131:      }
                   6132:      /* } /\* end i1 *\/ */
                   6133:    }/* End k1 */
                   6134:    fprintf(fichtm,"</ul>");
1.126     brouard  6135: 
1.222     brouard  6136:    fprintf(fichtm,"\
1.126     brouard  6137: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6138:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6139:  - 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  6140: But because parameters are usually highly correlated (a higher incidence of disability \
                   6141: and a higher incidence of recovery can give very close observed transition) it might \
                   6142: be very useful to look not only at linear confidence intervals estimated from the \
                   6143: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6144: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6145: covariance matrix of the one-step probabilities. \
                   6146: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6147: 
1.222     brouard  6148:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6149:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6150:    fprintf(fichtm,"\
1.126     brouard  6151:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6152:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6153: 
1.222     brouard  6154:    fprintf(fichtm,"\
1.126     brouard  6155:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6156:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6157:    fprintf(fichtm,"\
1.126     brouard  6158:  - 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): \
                   6159:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6160:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6161:    fprintf(fichtm,"\
1.126     brouard  6162:  - (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): \
                   6163:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6164:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6165:    fprintf(fichtm,"\
1.128     brouard  6166:  - 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  6167:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6168:    fprintf(fichtm,"\
1.128     brouard  6169:  - 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  6170:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6171:    fprintf(fichtm,"\
1.126     brouard  6172:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6173:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6174: 
                   6175: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6176: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6177: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6178: /*     <br>",fileres,fileres,fileres,fileres); */
                   6179: /*  else  */
                   6180: /*    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  6181:    fflush(fichtm);
                   6182:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6183: 
1.225     brouard  6184:    m=pow(2,cptcoveff);
1.222     brouard  6185:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6186: 
1.222     brouard  6187:    jj1=0;
1.237     brouard  6188: 
                   6189:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.222     brouard  6190:    for(k1=1; k1<=m;k1++){
1.237     brouard  6191:      if(TKresult[nres]!= k1)
                   6192:        continue;
1.222     brouard  6193:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6194:      jj1++;
1.126     brouard  6195:      if (cptcovn > 0) {
                   6196:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6197:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6198:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6199:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6200:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6201:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6202:       }
                   6203: 
1.126     brouard  6204:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6205: 
1.222     brouard  6206:        if(invalidvarcomb[k1]){
                   6207:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6208:         continue;
                   6209:        }
1.126     brouard  6210:      }
                   6211:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6212:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   6213: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  6214: <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  6215:      }
                   6216:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6217: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6218: true period expectancies (those weighted with period prevalences are also\
                   6219:  drawn in addition to the population based expectancies computed using\
1.218     brouard  6220:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  6221: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222     brouard  6222:      /* } /\* end i1 *\/ */
                   6223:    }/* End k1 */
                   6224:    fprintf(fichtm,"</ul>");
                   6225:    fflush(fichtm);
1.126     brouard  6226: }
                   6227: 
                   6228: /******************* Gnuplot file **************/
1.223     brouard  6229: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6230: 
                   6231:   char dirfileres[132],optfileres[132];
1.223     brouard  6232:   char gplotcondition[132];
1.237     brouard  6233:   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  6234:   int lv=0, vlv=0, kl=0;
1.130     brouard  6235:   int ng=0;
1.201     brouard  6236:   int vpopbased;
1.223     brouard  6237:   int ioffset; /* variable offset for columns */
1.235     brouard  6238:   int nres=0; /* Index of resultline */
1.219     brouard  6239: 
1.126     brouard  6240: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6241: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6242: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6243: /*   } */
                   6244: 
                   6245:   /*#ifdef windows */
                   6246:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6247:   /*#endif */
1.225     brouard  6248:   m=pow(2,cptcoveff);
1.126     brouard  6249: 
1.202     brouard  6250:   /* Contribution to likelihood */
                   6251:   /* Plot the probability implied in the likelihood */
1.223     brouard  6252:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6253:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6254:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6255:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6256: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6257:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6258: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6259:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6260:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6261:   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));
                   6262:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6263:   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));
                   6264:   for (i=1; i<= nlstate ; i ++) {
                   6265:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6266:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6267:     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);
                   6268:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6269:       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);
                   6270:     }
                   6271:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6272:   }
                   6273:   /* 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 */               
                   6274:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6275:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6276:   fprintf(ficgp,"\nset out;unset log\n");
                   6277:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6278: 
1.126     brouard  6279:   strcpy(dirfileres,optionfilefiname);
                   6280:   strcpy(optfileres,"vpl");
1.223     brouard  6281:   /* 1eme*/
1.238   ! brouard  6282:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
        !          6283:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6284:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238   ! brouard  6285:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
        !          6286:        if(TKresult[nres]!= k1)
        !          6287:          continue;
        !          6288:        /* We are interested in selected combination by the resultline */
        !          6289:        printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
        !          6290:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
        !          6291:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          6292:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
        !          6293:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          6294:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          6295:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          6296:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
        !          6297:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
        !          6298:          printf(" V%d=%d ",Tvaraff[k],vlv);
        !          6299:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
        !          6300:        }
        !          6301:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6302:          printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6303:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6304:        }       
        !          6305:        printf("\n#\n");
        !          6306:        fprintf(ficgp,"\n#\n");
        !          6307:        if(invalidvarcomb[k1]){
        !          6308:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6309:          continue;
        !          6310:        }
1.235     brouard  6311:       
1.238   ! brouard  6312:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
        !          6313:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
        !          6314:        fprintf(ficgp,"set xlabel \"Age\" \n\
1.235     brouard  6315: set ylabel \"Probability\" \n            \
                   6316: set ter svg size 640, 480\n                                            \
1.201     brouard  6317: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.235     brouard  6318:       
1.238   ! brouard  6319:        for (i=1; i<= nlstate ; i ++) {
        !          6320:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          6321:          else        fprintf(ficgp," %%*lf (%%*lf)");
        !          6322:        }
        !          6323:        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);
        !          6324:        for (i=1; i<= nlstate ; i ++) {
        !          6325:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          6326:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          6327:        } 
        !          6328:        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); 
        !          6329:        for (i=1; i<= nlstate ; i ++) {
        !          6330:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          6331:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          6332:        }  
        !          6333:        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));
        !          6334:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
        !          6335:          /* 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); */
        !          6336:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
        !          6337:          if(cptcoveff ==0){
        !          6338:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",        2+(cpt-1),  cpt );
        !          6339:          }else{
        !          6340:            kl=0;
        !          6341:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
        !          6342:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
        !          6343:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          6344:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          6345:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          6346:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6347:              kl++;
1.238   ! brouard  6348:              /* 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 *\/ */
        !          6349:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
        !          6350:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
        !          6351:              /* ''  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*/
        !          6352:              if(k==cptcoveff){
        !          6353:                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], \
        !          6354:                        4+(cpt-1),  cpt );  /* 4 or 6 ?*/
        !          6355:              }else{
        !          6356:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
        !          6357:                kl++;
        !          6358:              }
        !          6359:            } /* end covariate */
        !          6360:          } /* end if no covariate */
        !          6361:        } /* end if backcast */
        !          6362:        fprintf(ficgp,"\nset out \n");
        !          6363:       } /* nres */
1.201     brouard  6364:     } /* k1 */
                   6365:   } /* cpt */
1.235     brouard  6366: 
                   6367:   
1.126     brouard  6368:   /*2 eme*/
1.238   ! brouard  6369:   for (k1=1; k1<= m ; k1 ++){  
        !          6370:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6371:       if(TKresult[nres]!= k1)
        !          6372:        continue;
        !          6373:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
        !          6374:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6375:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6376:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6377:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6378:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6379:        vlv= nbcode[Tvaraff[k]][lv];
                   6380:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6381:       }
1.237     brouard  6382:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6383:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238   ! brouard  6384:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6385:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238   ! brouard  6386:       }
1.211     brouard  6387:       fprintf(ficgp,"\n#\n");
1.223     brouard  6388:       if(invalidvarcomb[k1]){
                   6389:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6390:        continue;
                   6391:       }
1.219     brouard  6392:                        
1.238   ! brouard  6393:       fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
        !          6394:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
        !          6395:        if(vpopbased==0)
        !          6396:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
        !          6397:        else
        !          6398:          fprintf(ficgp,"\nreplot ");
        !          6399:        for (i=1; i<= nlstate+1 ; i ++) {
        !          6400:          k=2*i;
        !          6401:          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);
        !          6402:          for (j=1; j<= nlstate+1 ; j ++) {
        !          6403:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          6404:            else fprintf(ficgp," %%*lf (%%*lf)");
        !          6405:          }   
        !          6406:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
        !          6407:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
        !          6408:          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);
        !          6409:          for (j=1; j<= nlstate+1 ; j ++) {
        !          6410:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          6411:            else fprintf(ficgp," %%*lf (%%*lf)");
        !          6412:          }   
        !          6413:          fprintf(ficgp,"\" t\"\" w l lt 0,");
        !          6414:          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);
        !          6415:          for (j=1; j<= nlstate+1 ; j ++) {
        !          6416:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          6417:            else fprintf(ficgp," %%*lf (%%*lf)");
        !          6418:          }   
        !          6419:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
        !          6420:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
        !          6421:        } /* state */
        !          6422:       } /* vpopbased */
        !          6423:       fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
        !          6424:     } /* end nres */
        !          6425:   } /* k1 end 2 eme*/
        !          6426:        
        !          6427:        
        !          6428:   /*3eme*/
        !          6429:   for (k1=1; k1<= m ; k1 ++){
        !          6430:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6431:       if(TKresult[nres]!= k)
        !          6432:        continue;
        !          6433: 
        !          6434:       for (cpt=1; cpt<= nlstate ; cpt ++) {
        !          6435:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
        !          6436:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          6437:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          6438:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          6439:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          6440:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          6441:          vlv= nbcode[Tvaraff[k]][lv];
        !          6442:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
        !          6443:        }
        !          6444:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6445:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6446:        }       
        !          6447:        fprintf(ficgp,"\n#\n");
        !          6448:        if(invalidvarcomb[k1]){
        !          6449:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6450:          continue;
        !          6451:        }
        !          6452:                        
        !          6453:        /*       k=2+nlstate*(2*cpt-2); */
        !          6454:        k=2+(nlstate+1)*(cpt-1);
        !          6455:        fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
        !          6456:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6457: 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  6458:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
        !          6459:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          6460:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
        !          6461:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
        !          6462:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          6463:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6464:                                
1.238   ! brouard  6465:        */
        !          6466:        for (i=1; i< nlstate ; i ++) {
        !          6467:          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);
        !          6468:          /*    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  6469:                                
1.238   ! brouard  6470:        } 
        !          6471:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
        !          6472:       }
        !          6473:     } /* end nres */
        !          6474:   } /* end kl 3eme */
1.126     brouard  6475:   
1.223     brouard  6476:   /* 4eme */
1.201     brouard  6477:   /* Survival functions (period) from state i in state j by initial state i */
1.238   ! brouard  6478:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
        !          6479:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6480:       if(TKresult[nres]!= k1)
1.223     brouard  6481:        continue;
1.238   ! brouard  6482:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
        !          6483:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
        !          6484:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          6485:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          6486:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          6487:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          6488:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          6489:          vlv= nbcode[Tvaraff[k]][lv];
        !          6490:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
        !          6491:        }
        !          6492:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6493:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6494:        }       
        !          6495:        fprintf(ficgp,"\n#\n");
        !          6496:        if(invalidvarcomb[k1]){
        !          6497:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6498:          continue;
1.223     brouard  6499:        }
1.238   ! brouard  6500:       
        !          6501:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
        !          6502:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
        !          6503: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          6504:        k=3;
        !          6505:        for (i=1; i<= nlstate ; i ++){
        !          6506:          if(i==1){
        !          6507:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          6508:          }else{
        !          6509:            fprintf(ficgp,", '' ");
        !          6510:          }
        !          6511:          l=(nlstate+ndeath)*(i-1)+1;
        !          6512:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
        !          6513:          for (j=2; j<= nlstate+ndeath ; j ++)
        !          6514:            fprintf(ficgp,"+$%d",k+l+j-1);
        !          6515:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
        !          6516:        } /* nlstate */
        !          6517:        fprintf(ficgp,"\nset out\n");
        !          6518:       } /* end cpt state*/ 
        !          6519:     } /* end nres */
        !          6520:   } /* end covariate k1 */  
        !          6521: 
1.220     brouard  6522: /* 5eme */
1.201     brouard  6523:   /* Survival functions (period) from state i in state j by final state j */
1.238   ! brouard  6524:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
        !          6525:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          6526:       if(TKresult[nres]!= k1)
1.227     brouard  6527:        continue;
1.238   ! brouard  6528:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
        !          6529:        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);
        !          6530:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          6531:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          6532:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          6533:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          6534:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          6535:          vlv= nbcode[Tvaraff[k]][lv];
        !          6536:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
        !          6537:        }
        !          6538:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          6539:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          6540:        }       
        !          6541:        fprintf(ficgp,"\n#\n");
        !          6542:        if(invalidvarcomb[k1]){
        !          6543:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6544:          continue;
        !          6545:        }
1.227     brouard  6546:       
1.238   ! brouard  6547:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
        !          6548:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
        !          6549: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          6550:        k=3;
        !          6551:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
        !          6552:          if(j==1)
        !          6553:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          6554:          else
        !          6555:            fprintf(ficgp,", '' ");
        !          6556:          l=(nlstate+ndeath)*(cpt-1) +j;
        !          6557:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
        !          6558:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
        !          6559:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
        !          6560:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
        !          6561:        } /* nlstate */
        !          6562:        fprintf(ficgp,", '' ");
        !          6563:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
        !          6564:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
        !          6565:          l=(nlstate+ndeath)*(cpt-1) +j;
        !          6566:          if(j < nlstate)
        !          6567:            fprintf(ficgp,"$%d +",k+l);
        !          6568:          else
        !          6569:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
        !          6570:        }
        !          6571:        fprintf(ficgp,"\nset out\n");
        !          6572:       } /* end cpt state*/ 
        !          6573:     } /* end covariate */  
        !          6574:   } /* end nres */
1.227     brouard  6575:   
1.220     brouard  6576: /* 6eme */
1.202     brouard  6577:   /* CV preval stable (period) for each covariate */
1.237     brouard  6578:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6579:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6580:     if(TKresult[nres]!= k1)
                   6581:       continue;
1.153     brouard  6582:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6583:       
1.211     brouard  6584:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6585:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6586:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6587:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6588:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6589:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6590:        vlv= nbcode[Tvaraff[k]][lv];
                   6591:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6592:       }
1.237     brouard  6593:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6594:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6595:       }        
1.211     brouard  6596:       fprintf(ficgp,"\n#\n");
1.223     brouard  6597:       if(invalidvarcomb[k1]){
1.227     brouard  6598:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6599:        continue;
1.223     brouard  6600:       }
1.227     brouard  6601:       
1.201     brouard  6602:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6603:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238   ! brouard  6604: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6605:       k=3; /* Offset */
1.153     brouard  6606:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6607:        if(i==1)
                   6608:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6609:        else
                   6610:          fprintf(ficgp,", '' ");
                   6611:        l=(nlstate+ndeath)*(i-1)+1;
                   6612:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6613:        for (j=2; j<= nlstate ; j ++)
                   6614:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6615:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6616:       } /* nlstate */
1.201     brouard  6617:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6618:     } /* end cpt state*/ 
                   6619:   } /* end covariate */  
1.227     brouard  6620:   
                   6621:   
1.220     brouard  6622: /* 7eme */
1.218     brouard  6623:   if(backcast == 1){
1.217     brouard  6624:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6625:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6626:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6627:       if(TKresult[nres]!= k1)
                   6628:        continue;
1.218     brouard  6629:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6630:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6631:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6632:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6633:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6634:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6635:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6636:          vlv= nbcode[Tvaraff[k]][lv];
                   6637:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6638:        }
1.237     brouard  6639:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6640:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6641:        }       
1.227     brouard  6642:        fprintf(ficgp,"\n#\n");
                   6643:        if(invalidvarcomb[k1]){
                   6644:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6645:          continue;
                   6646:        }
                   6647:        
                   6648:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6649:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238   ! brouard  6650: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6651:        k=3; /* Offset */
                   6652:        for (i=1; i<= nlstate ; i ++){
                   6653:          if(i==1)
                   6654:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6655:          else
                   6656:            fprintf(ficgp,", '' ");
                   6657:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6658:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6659:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6660:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6661:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6662:          /* for (j=2; j<= nlstate ; j ++) */
                   6663:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6664:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6665:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6666:        } /* nlstate */
                   6667:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6668:       } /* end cpt state*/ 
                   6669:     } /* end covariate */  
                   6670:   } /* End if backcast */
                   6671:   
1.223     brouard  6672:   /* 8eme */
1.218     brouard  6673:   if(prevfcast==1){
                   6674:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6675:     
1.237     brouard  6676:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6677:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6678:       if(TKresult[nres]!= k1)
                   6679:        continue;
1.211     brouard  6680:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6681:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6682:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6683:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6684:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6685:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6686:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6687:          vlv= nbcode[Tvaraff[k]][lv];
                   6688:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6689:        }
1.237     brouard  6690:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6691:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6692:        }       
1.227     brouard  6693:        fprintf(ficgp,"\n#\n");
                   6694:        if(invalidvarcomb[k1]){
                   6695:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6696:          continue;
                   6697:        }
                   6698:        
                   6699:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6700:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6701:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238   ! brouard  6702: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6703:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6704:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6705:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6706:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6707:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6708:          if(i==1){
                   6709:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6710:          }else{
                   6711:            fprintf(ficgp,",\\\n '' ");
                   6712:          }
                   6713:          if(cptcoveff ==0){ /* No covariate */
                   6714:            ioffset=2; /* Age is in 2 */
                   6715:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6716:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6717:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6718:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6719:            fprintf(ficgp," u %d:(", ioffset); 
                   6720:            if(i==nlstate+1)
                   6721:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6722:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6723:            else
                   6724:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6725:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6726:          }else{ /* more than 2 covariates */
                   6727:            if(cptcoveff ==1){
                   6728:              ioffset=4; /* Age is in 4 */
                   6729:            }else{
                   6730:              ioffset=6; /* Age is in 6 */
                   6731:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6732:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6733:            }   
                   6734:            fprintf(ficgp," u %d:(",ioffset); 
                   6735:            kl=0;
                   6736:            strcpy(gplotcondition,"(");
                   6737:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6738:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6739:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6740:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6741:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6742:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6743:              kl++;
                   6744:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6745:              kl++;
                   6746:              if(k <cptcoveff && cptcoveff>1)
                   6747:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6748:            }
                   6749:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6750:            /* 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 *\/ */
                   6751:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6752:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6753:            /* ''  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*/
                   6754:            if(i==nlstate+1){
                   6755:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6756:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6757:            }else{
                   6758:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6759:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6760:            }
                   6761:          } /* end if covariate */
                   6762:        } /* nlstate */
                   6763:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6764:       } /* end cpt state*/
                   6765:     } /* end covariate */
                   6766:   } /* End if prevfcast */
1.227     brouard  6767:   
                   6768:   
1.238   ! brouard  6769:   /* 9eme writing MLE parameters */
        !          6770:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6771:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6772:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6773:     for(k=1; k <=(nlstate+ndeath); k++){
                   6774:       if (k != i) {
1.227     brouard  6775:        fprintf(ficgp,"#   current state %d\n",k);
                   6776:        for(j=1; j <=ncovmodel; j++){
                   6777:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6778:          jk++; 
                   6779:        }
                   6780:        fprintf(ficgp,"\n");
1.126     brouard  6781:       }
                   6782:     }
1.223     brouard  6783:   }
1.187     brouard  6784:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6785:   
1.145     brouard  6786:   /*goto avoid;*/
1.238   ! brouard  6787:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
        !          6788:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6789:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6790:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6791:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6792:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6793:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6794:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6795:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6796:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6797:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6798:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6799:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6800:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6801:   fprintf(ficgp,"#\n");
1.223     brouard  6802:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238   ! brouard  6803:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6804:     fprintf(ficgp,"#model=%s \n",model);
1.238   ! brouard  6805:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6806:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6807:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6808:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6809:       if(TKresult[nres]!= jk)
                   6810:        continue;
                   6811:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6812:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6813:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6814:       }        
                   6815:       fprintf(ficgp,"\n#\n");
1.223     brouard  6816:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6817:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6818:       if (ng==1){
                   6819:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6820:        fprintf(ficgp,"\nunset log y");
                   6821:       }else if (ng==2){
                   6822:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6823:        fprintf(ficgp,"\nset log y");
                   6824:       }else if (ng==3){
                   6825:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6826:        fprintf(ficgp,"\nset log y");
                   6827:       }else
                   6828:        fprintf(ficgp,"\nunset title ");
                   6829:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6830:       i=1;
                   6831:       for(k2=1; k2<=nlstate; k2++) {
                   6832:        k3=i;
                   6833:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6834:          if (k != k2){
                   6835:            switch( ng) {
                   6836:            case 1:
                   6837:              if(nagesqr==0)
                   6838:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6839:              else /* nagesqr =1 */
                   6840:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6841:              break;
                   6842:            case 2: /* ng=2 */
                   6843:              if(nagesqr==0)
                   6844:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6845:              else /* nagesqr =1 */
                   6846:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6847:              break;
                   6848:            case 3:
                   6849:              if(nagesqr==0)
                   6850:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6851:              else /* nagesqr =1 */
                   6852:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6853:              break;
                   6854:            }
                   6855:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  6856:            ijp=1; /* product no age */
                   6857:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   6858:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  6859:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  6860:              if(j==Tage[ij]) { /* Product by age */
                   6861:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238   ! brouard  6862:                  if(DummyV[j]==0){
1.237     brouard  6863:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   6864:                  }else{ /* quantitative */
                   6865:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   6866:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6867:                  }
                   6868:                  ij++;
                   6869:                }
                   6870:              }else if(j==Tprod[ijp]) { /* */ 
                   6871:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   6872:                if(ijp <=cptcovprod) { /* Product */
1.238   ! brouard  6873:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
        !          6874:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  6875:                      /* 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)]); */
                   6876:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   6877:                    }else{ /* Vn is dummy and Vm is quanti */
                   6878:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   6879:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6880:                    }
                   6881:                  }else{ /* Vn*Vm Vn is quanti */
1.238   ! brouard  6882:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  6883:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   6884:                    }else{ /* Both quanti */
                   6885:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6886:                    }
                   6887:                  }
1.238   ! brouard  6888:                  ijp++;
1.237     brouard  6889:                }
                   6890:              } else{  /* simple covariate */
                   6891:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   6892:                if(Dummy[j]==0){
                   6893:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   6894:                }else{ /* quantitative */
                   6895:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  6896:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6897:                }
1.237     brouard  6898:              } /* end simple */
                   6899:            } /* end j */
1.223     brouard  6900:          }else{
                   6901:            i=i-ncovmodel;
                   6902:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6903:              fprintf(ficgp," (1.");
                   6904:          }
1.227     brouard  6905:          
1.223     brouard  6906:          if(ng != 1){
                   6907:            fprintf(ficgp,")/(1");
1.227     brouard  6908:            
1.223     brouard  6909:            for(k1=1; k1 <=nlstate; k1++){ 
                   6910:              if(nagesqr==0)
                   6911:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6912:              else /* nagesqr =1 */
                   6913:                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  6914:               
1.223     brouard  6915:              ij=1;
                   6916:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  6917:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6918:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  6919:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6920:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6921:                    ij++;
                   6922:                  }
                   6923:                }
                   6924:                else
1.225     brouard  6925:                  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  6926:              }
                   6927:              fprintf(ficgp,")");
                   6928:            }
                   6929:            fprintf(ficgp,")");
                   6930:            if(ng ==2)
                   6931:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6932:            else /* ng= 3 */
                   6933:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6934:          }else{ /* end ng <> 1 */
                   6935:            if( k !=k2) /* logit p11 is hard to draw */
                   6936:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   6937:          }
                   6938:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6939:            fprintf(ficgp,",");
                   6940:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6941:            fprintf(ficgp,",");
                   6942:          i=i+ncovmodel;
                   6943:        } /* end k */
                   6944:       } /* end k2 */
                   6945:       fprintf(ficgp,"\n set out\n");
                   6946:     } /* end jk */
                   6947:   } /* end ng */
                   6948:   /* avoid: */
                   6949:   fflush(ficgp); 
1.126     brouard  6950: }  /* end gnuplot */
                   6951: 
                   6952: 
                   6953: /*************** Moving average **************/
1.219     brouard  6954: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  6955:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  6956:    
1.222     brouard  6957:    int i, cpt, cptcod;
                   6958:    int modcovmax =1;
                   6959:    int mobilavrange, mob;
                   6960:    int iage=0;
                   6961: 
                   6962:    double sum=0.;
                   6963:    double age;
                   6964:    double *sumnewp, *sumnewm;
                   6965:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6966:   
                   6967:   
1.225     brouard  6968:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  6969:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   6970: 
                   6971:    sumnewp = vector(1,ncovcombmax);
                   6972:    sumnewm = vector(1,ncovcombmax);
                   6973:    agemingood = vector(1,ncovcombmax); 
                   6974:    agemaxgood = vector(1,ncovcombmax);
                   6975: 
                   6976:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6977:      sumnewm[cptcod]=0.;
                   6978:      sumnewp[cptcod]=0.;
                   6979:      agemingood[cptcod]=0;
                   6980:      agemaxgood[cptcod]=0;
                   6981:    }
                   6982:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   6983:   
                   6984:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6985:      if(mobilav==1) mobilavrange=5; /* default */
                   6986:      else mobilavrange=mobilav;
                   6987:      for (age=bage; age<=fage; age++)
                   6988:        for (i=1; i<=nlstate;i++)
                   6989:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   6990:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6991:      /* We keep the original values on the extreme ages bage, fage and for 
                   6992:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6993:        we use a 5 terms etc. until the borders are no more concerned. 
                   6994:      */ 
                   6995:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6996:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6997:         for (i=1; i<=nlstate;i++){
                   6998:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6999:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7000:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7001:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7002:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7003:             }
                   7004:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7005:           }
                   7006:         }
                   7007:        }/* end age */
                   7008:      }/* end mob */
                   7009:    }else
                   7010:      return -1;
                   7011:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7012:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7013:      if(invalidvarcomb[cptcod]){
                   7014:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7015:        continue;
                   7016:      }
1.219     brouard  7017: 
1.222     brouard  7018:      agemingood[cptcod]=fage-(mob-1)/2;
                   7019:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7020:        sumnewm[cptcod]=0.;
                   7021:        for (i=1; i<=nlstate;i++){
                   7022:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7023:        }
                   7024:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7025:         agemingood[cptcod]=age;
                   7026:        }else{ /* bad */
                   7027:         for (i=1; i<=nlstate;i++){
                   7028:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7029:         } /* i */
                   7030:        } /* end bad */
                   7031:      }/* age */
                   7032:      sum=0.;
                   7033:      for (i=1; i<=nlstate;i++){
                   7034:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7035:      }
                   7036:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7037:        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);
                   7038:        /* for (i=1; i<=nlstate;i++){ */
                   7039:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7040:        /* } /\* i *\/ */
                   7041:      } /* end bad */
                   7042:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7043:      /* From youngest, finding the oldest wrong */
                   7044:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7045:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7046:        sumnewm[cptcod]=0.;
                   7047:        for (i=1; i<=nlstate;i++){
                   7048:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7049:        }
                   7050:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7051:         agemaxgood[cptcod]=age;
                   7052:        }else{ /* bad */
                   7053:         for (i=1; i<=nlstate;i++){
                   7054:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7055:         } /* i */
                   7056:        } /* end bad */
                   7057:      }/* age */
                   7058:      sum=0.;
                   7059:      for (i=1; i<=nlstate;i++){
                   7060:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7061:      }
                   7062:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7063:        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);
                   7064:        /* for (i=1; i<=nlstate;i++){ */
                   7065:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7066:        /* } /\* i *\/ */
                   7067:      } /* end bad */
                   7068:                
                   7069:      for (age=bage; age<=fage; age++){
1.235     brouard  7070:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7071:        sumnewp[cptcod]=0.;
                   7072:        sumnewm[cptcod]=0.;
                   7073:        for (i=1; i<=nlstate;i++){
                   7074:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7075:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7076:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7077:        }
                   7078:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7079:      }
                   7080:      /* printf("\n"); */
                   7081:      /* } */
                   7082:      /* brutal averaging */
                   7083:      for (i=1; i<=nlstate;i++){
                   7084:        for (age=1; age<=bage; age++){
                   7085:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7086:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7087:        }       
                   7088:        for (age=fage; age<=AGESUP; age++){
                   7089:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7090:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7091:        }
                   7092:      } /* end i status */
                   7093:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7094:        for (age=1; age<=AGESUP; age++){
                   7095:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7096:         mobaverage[(int)age][i][cptcod]=0.;
                   7097:        }
                   7098:      }
                   7099:    }/* end cptcod */
                   7100:    free_vector(sumnewm,1, ncovcombmax);
                   7101:    free_vector(sumnewp,1, ncovcombmax);
                   7102:    free_vector(agemaxgood,1, ncovcombmax);
                   7103:    free_vector(agemingood,1, ncovcombmax);
                   7104:    return 0;
                   7105:  }/* End movingaverage */
1.218     brouard  7106:  
1.126     brouard  7107: 
                   7108: /************** Forecasting ******************/
1.235     brouard  7109:  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  7110:   /* proj1, year, month, day of starting projection 
                   7111:      agemin, agemax range of age
                   7112:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7113:      anproj2 year of en of projection (same day and month as proj1).
                   7114:   */
1.235     brouard  7115:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7116:   double agec; /* generic age */
                   7117:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7118:   double *popeffectif,*popcount;
                   7119:   double ***p3mat;
1.218     brouard  7120:   /* double ***mobaverage; */
1.126     brouard  7121:   char fileresf[FILENAMELENGTH];
                   7122: 
                   7123:   agelim=AGESUP;
1.211     brouard  7124:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7125:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7126:      We still use firstpass and lastpass as another selection.
                   7127:   */
1.214     brouard  7128:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7129:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7130:  
1.201     brouard  7131:   strcpy(fileresf,"F_"); 
                   7132:   strcat(fileresf,fileresu);
1.126     brouard  7133:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7134:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7135:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7136:   }
1.235     brouard  7137:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7138:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7139: 
1.225     brouard  7140:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7141: 
                   7142: 
                   7143:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7144:   if (stepm<=12) stepsize=1;
                   7145:   if(estepm < stepm){
                   7146:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7147:   }
                   7148:   else  hstepm=estepm;   
                   7149: 
                   7150:   hstepm=hstepm/stepm; 
                   7151:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7152:                                fractional in yp1 */
                   7153:   anprojmean=yp;
                   7154:   yp2=modf((yp1*12),&yp);
                   7155:   mprojmean=yp;
                   7156:   yp1=modf((yp2*30.5),&yp);
                   7157:   jprojmean=yp;
                   7158:   if(jprojmean==0) jprojmean=1;
                   7159:   if(mprojmean==0) jprojmean=1;
                   7160: 
1.227     brouard  7161:   i1=pow(2,cptcoveff);
1.126     brouard  7162:   if (cptcovn < 1){i1=1;}
                   7163:   
                   7164:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7165:   
                   7166:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7167:   
1.126     brouard  7168: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7169:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7170:   for(k=1; k<=i1;k++){
                   7171:     if(TKresult[nres]!= k)
                   7172:       continue;
1.227     brouard  7173:     if(invalidvarcomb[k]){
                   7174:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7175:       continue;
                   7176:     }
                   7177:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7178:     for(j=1;j<=cptcoveff;j++) {
                   7179:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7180:     }
1.235     brouard  7181:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238   ! brouard  7182:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7183:     }
1.227     brouard  7184:     fprintf(ficresf," yearproj age");
                   7185:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7186:       for(i=1; i<=nlstate;i++)               
                   7187:        fprintf(ficresf," p%d%d",i,j);
                   7188:       fprintf(ficresf," wp.%d",j);
                   7189:     }
                   7190:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7191:       fprintf(ficresf,"\n");
                   7192:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7193:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7194:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7195:        nhstepm = nhstepm/hstepm; 
                   7196:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7197:        oldm=oldms;savm=savms;
1.235     brouard  7198:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7199:        
                   7200:        for (h=0; h<=nhstepm; h++){
                   7201:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7202:            fprintf(ficresf,"\n");
                   7203:            for(j=1;j<=cptcoveff;j++) 
                   7204:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7205:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7206:          } 
                   7207:          for(j=1; j<=nlstate+ndeath;j++) {
                   7208:            ppij=0.;
                   7209:            for(i=1; i<=nlstate;i++) {
                   7210:              if (mobilav==1) 
                   7211:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7212:              else {
                   7213:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7214:              }
                   7215:              if (h*hstepm/YEARM*stepm== yearp) {
                   7216:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7217:              }
                   7218:            } /* end i */
                   7219:            if (h*hstepm/YEARM*stepm==yearp) {
                   7220:              fprintf(ficresf," %.3f", ppij);
                   7221:            }
                   7222:          }/* end j */
                   7223:        } /* end h */
                   7224:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7225:       } /* end agec */
                   7226:     } /* end yearp */
                   7227:   } /* end  k */
1.219     brouard  7228:        
1.126     brouard  7229:   fclose(ficresf);
1.215     brouard  7230:   printf("End of Computing forecasting \n");
                   7231:   fprintf(ficlog,"End of Computing forecasting\n");
                   7232: 
1.126     brouard  7233: }
                   7234: 
1.218     brouard  7235: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7236: /* 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  7237: /*   /\* back1, year, month, day of starting backection  */
                   7238: /*      agemin, agemax range of age */
                   7239: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7240: /*      anback2 year of en of backection (same day and month as back1). */
                   7241: /*   *\/ */
                   7242: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7243: /*   double agec; /\* generic age *\/ */
                   7244: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7245: /*   double *popeffectif,*popcount; */
                   7246: /*   double ***p3mat; */
                   7247: /*   /\* double ***mobaverage; *\/ */
                   7248: /*   char fileresfb[FILENAMELENGTH]; */
                   7249:        
                   7250: /*   agelim=AGESUP; */
                   7251: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7252: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7253: /*      We still use firstpass and lastpass as another selection. */
                   7254: /*   *\/ */
                   7255: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7256: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7257: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7258:        
                   7259: /*   strcpy(fileresfb,"FB_");  */
                   7260: /*   strcat(fileresfb,fileresu); */
                   7261: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7262: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7263: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7264: /*   } */
                   7265: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7266: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7267:        
1.225     brouard  7268: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7269:        
                   7270: /*   /\* if (mobilav!=0) { *\/ */
                   7271: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7272: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7273: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7274: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7275: /*   /\*   } *\/ */
                   7276: /*   /\* } *\/ */
                   7277:        
                   7278: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7279: /*   if (stepm<=12) stepsize=1; */
                   7280: /*   if(estepm < stepm){ */
                   7281: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7282: /*   } */
                   7283: /*   else  hstepm=estepm;    */
                   7284:        
                   7285: /*   hstepm=hstepm/stepm;  */
                   7286: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7287: /*                                fractional in yp1 *\/ */
                   7288: /*   anprojmean=yp; */
                   7289: /*   yp2=modf((yp1*12),&yp); */
                   7290: /*   mprojmean=yp; */
                   7291: /*   yp1=modf((yp2*30.5),&yp); */
                   7292: /*   jprojmean=yp; */
                   7293: /*   if(jprojmean==0) jprojmean=1; */
                   7294: /*   if(mprojmean==0) jprojmean=1; */
                   7295:        
1.225     brouard  7296: /*   i1=cptcoveff; */
1.218     brouard  7297: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7298:   
1.218     brouard  7299: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7300:   
1.218     brouard  7301: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7302:        
                   7303: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7304: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7305: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7306: /*       k=k+1; */
                   7307: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7308: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7309: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7310: /*       } */
                   7311: /*       fprintf(ficresfb," yearbproj age"); */
                   7312: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7313: /*                             for(i=1; i<=nlstate;i++)               */
                   7314: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7315: /*                             fprintf(ficresfb," p.%d",j); */
                   7316: /*       } */
                   7317: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7318: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7319: /*                             fprintf(ficresfb,"\n"); */
                   7320: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7321: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7322: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7323: /*                                     nhstepm = nhstepm/hstepm;  */
                   7324: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7325: /*                                     oldm=oldms;savm=savms; */
                   7326: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7327: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7328: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7329: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7330: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7331: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7332: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7333: /*                                             }  */
                   7334: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7335: /*                                                     ppij=0.; */
                   7336: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7337: /*                                                             if (mobilav==1)  */
                   7338: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7339: /*                                                             else { */
                   7340: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7341: /*                                                             } */
                   7342: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7343: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7344: /*                                                             } */
                   7345: /*                                                     } /\* end i *\/ */
                   7346: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7347: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7348: /*                                                     } */
                   7349: /*                                             }/\* end j *\/ */
                   7350: /*                                     } /\* end h *\/ */
                   7351: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7352: /*                             } /\* end agec *\/ */
                   7353: /*       } /\* end yearp *\/ */
                   7354: /*     } /\* end cptcod *\/ */
                   7355: /*   } /\* end  cptcov *\/ */
                   7356:        
                   7357: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7358:        
                   7359: /*   fclose(ficresfb); */
                   7360: /*   printf("End of Computing Back forecasting \n"); */
                   7361: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7362:        
1.218     brouard  7363: /* } */
1.217     brouard  7364: 
1.126     brouard  7365: /************** Forecasting *****not tested NB*************/
1.227     brouard  7366: /* 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  7367:   
1.227     brouard  7368: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7369: /*   int *popage; */
                   7370: /*   double calagedatem, agelim, kk1, kk2; */
                   7371: /*   double *popeffectif,*popcount; */
                   7372: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7373: /*   /\* double ***mobaverage; *\/ */
                   7374: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7375: 
1.227     brouard  7376: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7377: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7378: /*   agelim=AGESUP; */
                   7379: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7380:   
1.227     brouard  7381: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7382:   
                   7383:   
1.227     brouard  7384: /*   strcpy(filerespop,"POP_");  */
                   7385: /*   strcat(filerespop,fileresu); */
                   7386: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7387: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7388: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7389: /*   } */
                   7390: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7391: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7392: 
1.227     brouard  7393: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7394: 
1.227     brouard  7395: /*   /\* if (mobilav!=0) { *\/ */
                   7396: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7397: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7398: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7399: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7400: /*   /\*   } *\/ */
                   7401: /*   /\* } *\/ */
1.126     brouard  7402: 
1.227     brouard  7403: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7404: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7405:   
1.227     brouard  7406: /*   agelim=AGESUP; */
1.126     brouard  7407:   
1.227     brouard  7408: /*   hstepm=1; */
                   7409: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7410:        
1.227     brouard  7411: /*   if (popforecast==1) { */
                   7412: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7413: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7414: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7415: /*     }  */
                   7416: /*     popage=ivector(0,AGESUP); */
                   7417: /*     popeffectif=vector(0,AGESUP); */
                   7418: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7419:     
1.227     brouard  7420: /*     i=1;    */
                   7421: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7422:     
1.227     brouard  7423: /*     imx=i; */
                   7424: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7425: /*   } */
1.218     brouard  7426:   
1.227     brouard  7427: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7428: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7429: /*       k=k+1; */
                   7430: /*       fprintf(ficrespop,"\n#******"); */
                   7431: /*       for(j=1;j<=cptcoveff;j++) { */
                   7432: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7433: /*       } */
                   7434: /*       fprintf(ficrespop,"******\n"); */
                   7435: /*       fprintf(ficrespop,"# Age"); */
                   7436: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7437: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7438:       
1.227     brouard  7439: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7440: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7441:        
1.227     brouard  7442: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7443: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7444: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7445:          
1.227     brouard  7446: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7447: /*       oldm=oldms;savm=savms; */
                   7448: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7449:          
1.227     brouard  7450: /*       for (h=0; h<=nhstepm; h++){ */
                   7451: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7452: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7453: /*         }  */
                   7454: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7455: /*           kk1=0.;kk2=0; */
                   7456: /*           for(i=1; i<=nlstate;i++) {               */
                   7457: /*             if (mobilav==1)  */
                   7458: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7459: /*             else { */
                   7460: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7461: /*             } */
                   7462: /*           } */
                   7463: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7464: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7465: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7466: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7467: /*           } */
                   7468: /*         } */
                   7469: /*         for(i=1; i<=nlstate;i++){ */
                   7470: /*           kk1=0.; */
                   7471: /*           for(j=1; j<=nlstate;j++){ */
                   7472: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7473: /*           } */
                   7474: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7475: /*         } */
1.218     brouard  7476:            
1.227     brouard  7477: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7478: /*           for(j=1; j<=nlstate;j++)  */
                   7479: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7480: /*       } */
                   7481: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7482: /*     } */
                   7483: /*       } */
1.218     brouard  7484:       
1.227     brouard  7485: /*       /\******\/ */
1.218     brouard  7486:       
1.227     brouard  7487: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7488: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7489: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7490: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7491: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7492:          
1.227     brouard  7493: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7494: /*       oldm=oldms;savm=savms; */
                   7495: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7496: /*       for (h=0; h<=nhstepm; h++){ */
                   7497: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7498: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7499: /*         }  */
                   7500: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7501: /*           kk1=0.;kk2=0; */
                   7502: /*           for(i=1; i<=nlstate;i++) {               */
                   7503: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7504: /*           } */
                   7505: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7506: /*         } */
                   7507: /*       } */
                   7508: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7509: /*     } */
                   7510: /*       } */
                   7511: /*     }  */
                   7512: /*   } */
1.218     brouard  7513:   
1.227     brouard  7514: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7515:   
1.227     brouard  7516: /*   if (popforecast==1) { */
                   7517: /*     free_ivector(popage,0,AGESUP); */
                   7518: /*     free_vector(popeffectif,0,AGESUP); */
                   7519: /*     free_vector(popcount,0,AGESUP); */
                   7520: /*   } */
                   7521: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7522: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7523: /*   fclose(ficrespop); */
                   7524: /* } /\* End of popforecast *\/ */
1.218     brouard  7525:  
1.126     brouard  7526: int fileappend(FILE *fichier, char *optionfich)
                   7527: {
                   7528:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7529:     printf("Problem with file: %s\n", optionfich);
                   7530:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7531:     return (0);
                   7532:   }
                   7533:   fflush(fichier);
                   7534:   return (1);
                   7535: }
                   7536: 
                   7537: 
                   7538: /**************** function prwizard **********************/
                   7539: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7540: {
                   7541: 
                   7542:   /* Wizard to print covariance matrix template */
                   7543: 
1.164     brouard  7544:   char ca[32], cb[32];
                   7545:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7546:   int numlinepar;
                   7547: 
                   7548:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7549:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7550:   for(i=1; i <=nlstate; i++){
                   7551:     jj=0;
                   7552:     for(j=1; j <=nlstate+ndeath; j++){
                   7553:       if(j==i) continue;
                   7554:       jj++;
                   7555:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7556:       printf("%1d%1d",i,j);
                   7557:       fprintf(ficparo,"%1d%1d",i,j);
                   7558:       for(k=1; k<=ncovmodel;k++){
                   7559:        /*        printf(" %lf",param[i][j][k]); */
                   7560:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7561:        printf(" 0.");
                   7562:        fprintf(ficparo," 0.");
                   7563:       }
                   7564:       printf("\n");
                   7565:       fprintf(ficparo,"\n");
                   7566:     }
                   7567:   }
                   7568:   printf("# Scales (for hessian or gradient estimation)\n");
                   7569:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7570:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7571:   for(i=1; i <=nlstate; i++){
                   7572:     jj=0;
                   7573:     for(j=1; j <=nlstate+ndeath; j++){
                   7574:       if(j==i) continue;
                   7575:       jj++;
                   7576:       fprintf(ficparo,"%1d%1d",i,j);
                   7577:       printf("%1d%1d",i,j);
                   7578:       fflush(stdout);
                   7579:       for(k=1; k<=ncovmodel;k++){
                   7580:        /*      printf(" %le",delti3[i][j][k]); */
                   7581:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7582:        printf(" 0.");
                   7583:        fprintf(ficparo," 0.");
                   7584:       }
                   7585:       numlinepar++;
                   7586:       printf("\n");
                   7587:       fprintf(ficparo,"\n");
                   7588:     }
                   7589:   }
                   7590:   printf("# Covariance matrix\n");
                   7591: /* # 121 Var(a12)\n\ */
                   7592: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7593: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7594: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7595: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7596: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7597: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7598: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7599:   fflush(stdout);
                   7600:   fprintf(ficparo,"# Covariance matrix\n");
                   7601:   /* # 121 Var(a12)\n\ */
                   7602:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7603:   /* #   ...\n\ */
                   7604:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7605:   
                   7606:   for(itimes=1;itimes<=2;itimes++){
                   7607:     jj=0;
                   7608:     for(i=1; i <=nlstate; i++){
                   7609:       for(j=1; j <=nlstate+ndeath; j++){
                   7610:        if(j==i) continue;
                   7611:        for(k=1; k<=ncovmodel;k++){
                   7612:          jj++;
                   7613:          ca[0]= k+'a'-1;ca[1]='\0';
                   7614:          if(itimes==1){
                   7615:            printf("#%1d%1d%d",i,j,k);
                   7616:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7617:          }else{
                   7618:            printf("%1d%1d%d",i,j,k);
                   7619:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7620:            /*  printf(" %.5le",matcov[i][j]); */
                   7621:          }
                   7622:          ll=0;
                   7623:          for(li=1;li <=nlstate; li++){
                   7624:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7625:              if(lj==li) continue;
                   7626:              for(lk=1;lk<=ncovmodel;lk++){
                   7627:                ll++;
                   7628:                if(ll<=jj){
                   7629:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7630:                  if(ll<jj){
                   7631:                    if(itimes==1){
                   7632:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7633:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7634:                    }else{
                   7635:                      printf(" 0.");
                   7636:                      fprintf(ficparo," 0.");
                   7637:                    }
                   7638:                  }else{
                   7639:                    if(itimes==1){
                   7640:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7641:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7642:                    }else{
                   7643:                      printf(" 0.");
                   7644:                      fprintf(ficparo," 0.");
                   7645:                    }
                   7646:                  }
                   7647:                }
                   7648:              } /* end lk */
                   7649:            } /* end lj */
                   7650:          } /* end li */
                   7651:          printf("\n");
                   7652:          fprintf(ficparo,"\n");
                   7653:          numlinepar++;
                   7654:        } /* end k*/
                   7655:       } /*end j */
                   7656:     } /* end i */
                   7657:   } /* end itimes */
                   7658: 
                   7659: } /* end of prwizard */
                   7660: /******************* Gompertz Likelihood ******************************/
                   7661: double gompertz(double x[])
                   7662: { 
                   7663:   double A,B,L=0.0,sump=0.,num=0.;
                   7664:   int i,n=0; /* n is the size of the sample */
                   7665: 
1.220     brouard  7666:   for (i=1;i<=imx ; i++) {
1.126     brouard  7667:     sump=sump+weight[i];
                   7668:     /*    sump=sump+1;*/
                   7669:     num=num+1;
                   7670:   }
                   7671:  
                   7672:  
                   7673:   /* for (i=0; i<=imx; i++) 
                   7674:      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]);*/
                   7675: 
                   7676:   for (i=1;i<=imx ; i++)
                   7677:     {
                   7678:       if (cens[i] == 1 && wav[i]>1)
                   7679:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7680:       
                   7681:       if (cens[i] == 0 && wav[i]>1)
                   7682:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7683:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7684:       
                   7685:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7686:       if (wav[i] > 1 ) { /* ??? */
                   7687:        L=L+A*weight[i];
                   7688:        /*      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]);*/
                   7689:       }
                   7690:     }
                   7691: 
                   7692:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7693:  
                   7694:   return -2*L*num/sump;
                   7695: }
                   7696: 
1.136     brouard  7697: #ifdef GSL
                   7698: /******************* Gompertz_f Likelihood ******************************/
                   7699: double gompertz_f(const gsl_vector *v, void *params)
                   7700: { 
                   7701:   double A,B,LL=0.0,sump=0.,num=0.;
                   7702:   double *x= (double *) v->data;
                   7703:   int i,n=0; /* n is the size of the sample */
                   7704: 
                   7705:   for (i=0;i<=imx-1 ; i++) {
                   7706:     sump=sump+weight[i];
                   7707:     /*    sump=sump+1;*/
                   7708:     num=num+1;
                   7709:   }
                   7710:  
                   7711:  
                   7712:   /* for (i=0; i<=imx; i++) 
                   7713:      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]);*/
                   7714:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7715:   for (i=1;i<=imx ; i++)
                   7716:     {
                   7717:       if (cens[i] == 1 && wav[i]>1)
                   7718:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7719:       
                   7720:       if (cens[i] == 0 && wav[i]>1)
                   7721:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7722:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7723:       
                   7724:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7725:       if (wav[i] > 1 ) { /* ??? */
                   7726:        LL=LL+A*weight[i];
                   7727:        /*      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]);*/
                   7728:       }
                   7729:     }
                   7730: 
                   7731:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7732:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7733:  
                   7734:   return -2*LL*num/sump;
                   7735: }
                   7736: #endif
                   7737: 
1.126     brouard  7738: /******************* Printing html file ***********/
1.201     brouard  7739: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7740:                  int lastpass, int stepm, int weightopt, char model[],\
                   7741:                  int imx,  double p[],double **matcov,double agemortsup){
                   7742:   int i,k;
                   7743: 
                   7744:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7745:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7746:   for (i=1;i<=2;i++) 
                   7747:     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  7748:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7749:   fprintf(fichtm,"</ul>");
                   7750: 
                   7751: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7752: 
                   7753:  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>");
                   7754: 
                   7755:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7756:    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]);
                   7757: 
                   7758:  
                   7759:   fflush(fichtm);
                   7760: }
                   7761: 
                   7762: /******************* Gnuplot file **************/
1.201     brouard  7763: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7764: 
                   7765:   char dirfileres[132],optfileres[132];
1.164     brouard  7766: 
1.126     brouard  7767:   int ng;
                   7768: 
                   7769: 
                   7770:   /*#ifdef windows */
                   7771:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7772:     /*#endif */
                   7773: 
                   7774: 
                   7775:   strcpy(dirfileres,optionfilefiname);
                   7776:   strcpy(optfileres,"vpl");
1.199     brouard  7777:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7778:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7779:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7780:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7781:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7782: 
                   7783: } 
                   7784: 
1.136     brouard  7785: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7786: {
1.126     brouard  7787: 
1.136     brouard  7788:   /*-------- data file ----------*/
                   7789:   FILE *fic;
                   7790:   char dummy[]="                         ";
1.223     brouard  7791:   int i=0, j=0, n=0, iv=0;
                   7792:   int lstra;
1.136     brouard  7793:   int linei, month, year,iout;
                   7794:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7795:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7796:   char *stratrunc;
1.223     brouard  7797: 
1.126     brouard  7798: 
                   7799: 
1.136     brouard  7800:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7801:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7802:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7803:   }
1.126     brouard  7804: 
1.136     brouard  7805:   i=1;
                   7806:   linei=0;
                   7807:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7808:     linei=linei+1;
                   7809:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7810:       if(line[j] == '\t')
                   7811:        line[j] = ' ';
                   7812:     }
                   7813:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7814:       ;
                   7815:     };
                   7816:     line[j+1]=0;  /* Trims blanks at end of line */
                   7817:     if(line[0]=='#'){
                   7818:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7819:       printf("Comment line\n%s\n",line);
                   7820:       continue;
                   7821:     }
                   7822:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7823:     strcpy(line, linetmp);
1.223     brouard  7824:     
                   7825:     /* Loops on waves */
                   7826:     for (j=maxwav;j>=1;j--){
                   7827:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238   ! brouard  7828:        cutv(stra, strb, line, ' '); 
        !          7829:        if(strb[0]=='.') { /* Missing value */
        !          7830:          lval=-1;
        !          7831:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
        !          7832:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
        !          7833:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
        !          7834:            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);
        !          7835:            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);
        !          7836:            return 1;
        !          7837:          }
        !          7838:        }else{
        !          7839:          errno=0;
        !          7840:          /* what_kind_of_number(strb); */
        !          7841:          dval=strtod(strb,&endptr); 
        !          7842:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
        !          7843:          /* if(strb != endptr && *endptr == '\0') */
        !          7844:          /*    dval=dlval; */
        !          7845:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
        !          7846:          if( strb[0]=='\0' || (*endptr != '\0')){
        !          7847:            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);
        !          7848:            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);
        !          7849:            return 1;
        !          7850:          }
        !          7851:          cotqvar[j][iv][i]=dval; 
        !          7852:          cotvar[j][ntv+iv][i]=dval; 
        !          7853:        }
        !          7854:        strcpy(line,stra);
1.223     brouard  7855:       }/* end loop ntqv */
1.225     brouard  7856:       
1.223     brouard  7857:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238   ! brouard  7858:        cutv(stra, strb, line, ' '); 
        !          7859:        if(strb[0]=='.') { /* Missing value */
        !          7860:          lval=-1;
        !          7861:        }else{
        !          7862:          errno=0;
        !          7863:          lval=strtol(strb,&endptr,10); 
        !          7864:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          7865:          if( strb[0]=='\0' || (*endptr != '\0')){
        !          7866:            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);
        !          7867:            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);
        !          7868:            return 1;
        !          7869:          }
        !          7870:        }
        !          7871:        if(lval <-1 || lval >1){
        !          7872:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7873:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7874:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238   ! brouard  7875:  For example, for multinomial values like 1, 2 and 3,\n                        \
        !          7876:  build V1=0 V2=0 for the reference value (1),\n                                \
        !          7877:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  7878:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238   ! brouard  7879:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  7880:  Exiting.\n",lval,linei, i,line,j);
1.238   ! brouard  7881:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7882:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7883:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238   ! brouard  7884:  For example, for multinomial values like 1, 2 and 3,\n                        \
        !          7885:  build V1=0 V2=0 for the reference value (1),\n                                \
        !          7886:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  7887:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238   ! brouard  7888:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  7889:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238   ! brouard  7890:          return 1;
        !          7891:        }
        !          7892:        cotvar[j][iv][i]=(double)(lval);
        !          7893:        strcpy(line,stra);
1.223     brouard  7894:       }/* end loop ntv */
1.225     brouard  7895:       
1.223     brouard  7896:       /* Statuses  at wave */
1.137     brouard  7897:       cutv(stra, strb, line, ' '); 
1.223     brouard  7898:       if(strb[0]=='.') { /* Missing value */
1.238   ! brouard  7899:        lval=-1;
1.136     brouard  7900:       }else{
1.238   ! brouard  7901:        errno=0;
        !          7902:        lval=strtol(strb,&endptr,10); 
        !          7903:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          7904:        if( strb[0]=='\0' || (*endptr != '\0')){
        !          7905:          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);
        !          7906:          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);
        !          7907:          return 1;
        !          7908:        }
1.136     brouard  7909:       }
1.225     brouard  7910:       
1.136     brouard  7911:       s[j][i]=lval;
1.225     brouard  7912:       
1.223     brouard  7913:       /* Date of Interview */
1.136     brouard  7914:       strcpy(line,stra);
                   7915:       cutv(stra, strb,line,' ');
1.169     brouard  7916:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7917:       }
1.169     brouard  7918:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  7919:        month=99;
                   7920:        year=9999;
1.136     brouard  7921:       }else{
1.225     brouard  7922:        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);
                   7923:        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);
                   7924:        return 1;
1.136     brouard  7925:       }
                   7926:       anint[j][i]= (double) year; 
                   7927:       mint[j][i]= (double)month; 
                   7928:       strcpy(line,stra);
1.223     brouard  7929:     } /* End loop on waves */
1.225     brouard  7930:     
1.223     brouard  7931:     /* Date of death */
1.136     brouard  7932:     cutv(stra, strb,line,' '); 
1.169     brouard  7933:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7934:     }
1.169     brouard  7935:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7936:       month=99;
                   7937:       year=9999;
                   7938:     }else{
1.141     brouard  7939:       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  7940:       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);
                   7941:       return 1;
1.136     brouard  7942:     }
                   7943:     andc[i]=(double) year; 
                   7944:     moisdc[i]=(double) month; 
                   7945:     strcpy(line,stra);
                   7946:     
1.223     brouard  7947:     /* Date of birth */
1.136     brouard  7948:     cutv(stra, strb,line,' '); 
1.169     brouard  7949:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7950:     }
1.169     brouard  7951:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7952:       month=99;
                   7953:       year=9999;
                   7954:     }else{
1.141     brouard  7955:       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);
                   7956:       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  7957:       return 1;
1.136     brouard  7958:     }
                   7959:     if (year==9999) {
1.141     brouard  7960:       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);
                   7961:       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  7962:       return 1;
                   7963:       
1.136     brouard  7964:     }
                   7965:     annais[i]=(double)(year);
                   7966:     moisnais[i]=(double)(month); 
                   7967:     strcpy(line,stra);
1.225     brouard  7968:     
1.223     brouard  7969:     /* Sample weight */
1.136     brouard  7970:     cutv(stra, strb,line,' '); 
                   7971:     errno=0;
                   7972:     dval=strtod(strb,&endptr); 
                   7973:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7974:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7975:       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  7976:       fflush(ficlog);
                   7977:       return 1;
                   7978:     }
                   7979:     weight[i]=dval; 
                   7980:     strcpy(line,stra);
1.225     brouard  7981:     
1.223     brouard  7982:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   7983:       cutv(stra, strb, line, ' '); 
                   7984:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  7985:        lval=-1;
1.223     brouard  7986:       }else{
1.225     brouard  7987:        errno=0;
                   7988:        /* what_kind_of_number(strb); */
                   7989:        dval=strtod(strb,&endptr);
                   7990:        /* if(strb != endptr && *endptr == '\0') */
                   7991:        /*   dval=dlval; */
                   7992:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7993:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7994:          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);
                   7995:          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);
                   7996:          return 1;
                   7997:        }
                   7998:        coqvar[iv][i]=dval; 
1.226     brouard  7999:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8000:       }
                   8001:       strcpy(line,stra);
                   8002:     }/* end loop nqv */
1.136     brouard  8003:     
1.223     brouard  8004:     /* Covariate values */
1.136     brouard  8005:     for (j=ncovcol;j>=1;j--){
                   8006:       cutv(stra, strb,line,' '); 
1.223     brouard  8007:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8008:        lval=-1;
1.136     brouard  8009:       }else{
1.225     brouard  8010:        errno=0;
                   8011:        lval=strtol(strb,&endptr,10); 
                   8012:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8013:          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);
                   8014:          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);
                   8015:          return 1;
                   8016:        }
1.136     brouard  8017:       }
                   8018:       if(lval <-1 || lval >1){
1.225     brouard  8019:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8020:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8021:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8022:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8023:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8024:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8025:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8026:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8027:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8028:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8029:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8030:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8031:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8032:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8033:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8034:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8035:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8036:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8037:        return 1;
1.136     brouard  8038:       }
                   8039:       covar[j][i]=(double)(lval);
                   8040:       strcpy(line,stra);
                   8041:     }  
                   8042:     lstra=strlen(stra);
1.225     brouard  8043:     
1.136     brouard  8044:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8045:       stratrunc = &(stra[lstra-9]);
                   8046:       num[i]=atol(stratrunc);
                   8047:     }
                   8048:     else
                   8049:       num[i]=atol(stra);
                   8050:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8051:       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;}*/
                   8052:     
                   8053:     i=i+1;
                   8054:   } /* End loop reading  data */
1.225     brouard  8055:   
1.136     brouard  8056:   *imax=i-1; /* Number of individuals */
                   8057:   fclose(fic);
1.225     brouard  8058:   
1.136     brouard  8059:   return (0);
1.164     brouard  8060:   /* endread: */
1.225     brouard  8061:   printf("Exiting readdata: ");
                   8062:   fclose(fic);
                   8063:   return (1);
1.223     brouard  8064: }
1.126     brouard  8065: 
1.234     brouard  8066: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8067:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8068:   while (*p2 == ' ')
1.234     brouard  8069:     p2++; 
                   8070:   /* while ((*p1++ = *p2++) !=0) */
                   8071:   /*   ; */
                   8072:   /* do */
                   8073:   /*   while (*p2 == ' ') */
                   8074:   /*     p2++; */
                   8075:   /* while (*p1++ == *p2++); */
                   8076:   *stri=p2; 
1.145     brouard  8077: }
                   8078: 
1.235     brouard  8079: int decoderesult ( char resultline[], int nres)
1.230     brouard  8080: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8081: {
1.235     brouard  8082:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8083:   char resultsav[MAXLINE];
1.234     brouard  8084:   int resultmodel[MAXLINE];
                   8085:   int modelresult[MAXLINE];
1.230     brouard  8086:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8087: 
1.234     brouard  8088:   removefirstspace(&resultline);
1.233     brouard  8089:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8090: 
                   8091:   if (strstr(resultline,"v") !=0){
                   8092:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8093:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8094:     return 1;
                   8095:   }
                   8096:   trimbb(resultsav, resultline);
                   8097:   if (strlen(resultsav) >1){
                   8098:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8099:   }
1.234     brouard  8100:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8101:     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);
                   8102:     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);
                   8103:   }
                   8104:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8105:     if(nbocc(resultsav,'=') >1){
                   8106:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8107:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8108:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8109:     }else
                   8110:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8111:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8112:     
1.230     brouard  8113:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8114:     Tvarsel[k]=atoi(strc);
                   8115:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8116:     /* cptcovsel++;     */
                   8117:     if (nbocc(stra,'=') >0)
                   8118:       strcpy(resultsav,stra); /* and analyzes it */
                   8119:   }
1.235     brouard  8120:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8121:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8122:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8123:       match=0;
1.236     brouard  8124:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8125:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8126:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8127:          match=1;
                   8128:          break;
                   8129:        }
                   8130:       }
                   8131:       if(match == 0){
                   8132:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8133:       }
                   8134:     }
                   8135:   }
1.235     brouard  8136:   /* Checking for missing or useless values in comparison of current model needs */
                   8137:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8138:     match=0;
1.235     brouard  8139:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8140:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8141:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8142:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8143:          ++match;
                   8144:        }
                   8145:       }
                   8146:     }
                   8147:     if(match == 0){
                   8148:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8149:     }else if(match > 1){
                   8150:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8151:     }
                   8152:   }
1.235     brouard  8153:       
1.234     brouard  8154:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8155:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8156:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8157:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8158:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8159:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8160:   /*    1 0 0 0 */
                   8161:   /*    2 1 0 0 */
                   8162:   /*    3 0 1 0 */ 
                   8163:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8164:   /*    5 0 0 1 */
                   8165:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8166:   /*    7 0 1 1 */
                   8167:   /*    8 1 1 1 */
1.237     brouard  8168:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8169:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8170:   /* V5*age V5 known which value for nres?  */
                   8171:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8172:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8173:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8174:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8175:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8176:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8177:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8178:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8179:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8180:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8181:       k4++;;
                   8182:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8183:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8184:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8185:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8186:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8187:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8188:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8189:       k4q++;;
                   8190:     }
                   8191:   }
1.234     brouard  8192:   
1.235     brouard  8193:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8194:   return (0);
                   8195: }
1.235     brouard  8196: 
1.230     brouard  8197: int decodemodel( char model[], int lastobs)
                   8198:  /**< This routine decodes the model and returns:
1.224     brouard  8199:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8200:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8201:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8202:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8203:        * - cptcovage number of covariates with age*products =2
                   8204:        * - cptcovs number of simple covariates
                   8205:        * - 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
                   8206:        *     which is a new column after the 9 (ncovcol) variables. 
                   8207:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8208:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8209:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8210:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8211:        */
1.136     brouard  8212: {
1.238   ! brouard  8213:   int i, j, k, ks, v;
1.227     brouard  8214:   int  j1, k1, k2, k3, k4;
1.136     brouard  8215:   char modelsav[80];
1.145     brouard  8216:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8217:   char *strpt;
1.136     brouard  8218: 
1.145     brouard  8219:   /*removespace(model);*/
1.136     brouard  8220:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8221:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8222:     if (strstr(model,"AGE") !=0){
1.192     brouard  8223:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8224:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8225:       return 1;
                   8226:     }
1.141     brouard  8227:     if (strstr(model,"v") !=0){
                   8228:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8229:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8230:       return 1;
                   8231:     }
1.187     brouard  8232:     strcpy(modelsav,model); 
                   8233:     if ((strpt=strstr(model,"age*age")) !=0){
                   8234:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8235:       if(strpt != model){
1.234     brouard  8236:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8237:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8238:  corresponding column of parameters.\n",model);
1.234     brouard  8239:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8240:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8241:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8242:        return 1;
1.225     brouard  8243:       }
1.187     brouard  8244:       nagesqr=1;
                   8245:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8246:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8247:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8248:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8249:       else 
1.234     brouard  8250:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8251:     }else
                   8252:       nagesqr=0;
                   8253:     if (strlen(modelsav) >1){
                   8254:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8255:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8256:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8257:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8258:                     * cst, age and age*age 
                   8259:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8260:       /* including age products which are counted in cptcovage.
                   8261:        * but the covariates which are products must be treated 
                   8262:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8263:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8264:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8265:       
                   8266:       
1.187     brouard  8267:       /*   Design
                   8268:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8269:        *  <          ncovcol=8                >
                   8270:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8271:        *   k=  1    2      3       4     5       6      7        8
                   8272:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8273:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8274:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8275:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8276:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8277:        *  Tage[++cptcovage]=k
                   8278:        *       if products, new covar are created after ncovcol with k1
                   8279:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8280:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8281:        *  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
                   8282:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8283:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8284:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8285:        *  <          ncovcol=8                >
                   8286:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8287:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8288:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8289:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8290:        * p Tprod[1]@2={                         6, 5}
                   8291:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8292:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8293:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8294:        *How to reorganize?
                   8295:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8296:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8297:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8298:        * Struct []
                   8299:        */
1.225     brouard  8300:       
1.187     brouard  8301:       /* This loop fills the array Tvar from the string 'model'.*/
                   8302:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8303:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8304:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8305:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8306:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8307:       /*       k=1 Tvar[1]=2 (from V2) */
                   8308:       /*       k=5 Tvar[5] */
                   8309:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8310:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8311:       /*       } */
1.198     brouard  8312:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8313:       /*
                   8314:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8315:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8316:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8317:       }
1.187     brouard  8318:       cptcovage=0;
                   8319:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8320:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8321:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8322:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8323:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8324:        /*scanf("%d",i);*/
                   8325:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8326:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8327:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8328:            /* covar is not filled and then is empty */
                   8329:            cptcovprod--;
                   8330:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8331:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8332:            Typevar[k]=1;  /* 1 for age product */
                   8333:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8334:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8335:            /*printf("stre=%s ", stre);*/
                   8336:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8337:            cptcovprod--;
                   8338:            cutl(stre,strb,strc,'V');
                   8339:            Tvar[k]=atoi(stre);
                   8340:            Typevar[k]=1;  /* 1 for age product */
                   8341:            cptcovage++;
                   8342:            Tage[cptcovage]=k;
                   8343:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8344:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8345:            cptcovn++;
                   8346:            cptcovprodnoage++;k1++;
                   8347:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8348:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8349:                                                because this model-covariate is a construction we invent a new column
                   8350:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8351:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8352:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8353:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8354:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8355:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8356:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8357:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8358:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8359:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8360:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8361:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8362:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8363:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8364:            for (i=1; i<=lastobs;i++){
                   8365:              /* Computes the new covariate which is a product of
                   8366:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8367:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8368:            }
                   8369:          } /* End age is not in the model */
                   8370:        } /* End if model includes a product */
                   8371:        else { /* no more sum */
                   8372:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8373:          /*  scanf("%d",i);*/
                   8374:          cutl(strd,strc,strb,'V');
                   8375:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8376:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8377:          Tvar[k]=atoi(strd);
                   8378:          Typevar[k]=0;  /* 0 for simple covariates */
                   8379:        }
                   8380:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8381:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8382:                                  scanf("%d",i);*/
1.187     brouard  8383:       } /* end of loop + on total covariates */
                   8384:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8385:   } /* end if strlen(model == 0) */
1.136     brouard  8386:   
                   8387:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8388:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8389:   
1.136     brouard  8390:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8391:      printf("cptcovprod=%d ", cptcovprod);
                   8392:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8393:      scanf("%d ",i);*/
                   8394: 
                   8395: 
1.230     brouard  8396: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8397:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8398: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8399:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8400:    k =           1    2   3     4       5       6      7      8        9
                   8401:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8402:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8403:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8404:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8405:          Tmodelind[combination of covar]=k;
1.225     brouard  8406: */  
                   8407: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8408:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8409:   /* 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  8410:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8411:   printf("Model=%s\n\
                   8412: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8413: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8414: 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);
                   8415:   fprintf(ficlog,"Model=%s\n\
                   8416: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8417: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8418: 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);
                   8419: 
1.238   ! brouard  8420:   for(v=1; v <=ncovcol;v++){
        !          8421:     DummyV[v]=0;
        !          8422:     FixedV[v]=0;
        !          8423:   }
        !          8424:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
        !          8425:     DummyV[v]=1;
        !          8426:     FixedV[v]=0;
        !          8427:   }
        !          8428:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
        !          8429:     DummyV[v]=0;
        !          8430:     FixedV[v]=1;
        !          8431:   }
        !          8432:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
        !          8433:     DummyV[v]=1;
        !          8434:     FixedV[v]=1;
        !          8435:   }
        !          8436:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
        !          8437:     printf("Decodemodel: V%d, Dummy(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
        !          8438:     fprintf(ficlog,"Decodemodel: V%d, Dummy(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
        !          8439:   }
1.234     brouard  8440:   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 */
                   8441:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8442:       Fixed[k]= 0;
                   8443:       Dummy[k]= 0;
1.225     brouard  8444:       ncoveff++;
1.232     brouard  8445:       ncovf++;
1.234     brouard  8446:       nsd++;
                   8447:       modell[k].maintype= FTYPE;
                   8448:       TvarsD[nsd]=Tvar[k];
                   8449:       TvarsDind[nsd]=k;
                   8450:       TvarF[ncovf]=Tvar[k];
                   8451:       TvarFind[ncovf]=k;
                   8452:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8453:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8454:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8455:       Fixed[k]= 0;
                   8456:       Dummy[k]= 0;
                   8457:       ncoveff++;
                   8458:       ncovf++;
                   8459:       modell[k].maintype= FTYPE;
                   8460:       TvarF[ncovf]=Tvar[k];
                   8461:       TvarFind[ncovf]=k;
1.230     brouard  8462:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8463:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8464:     }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  8465:       Fixed[k]= 0;
                   8466:       Dummy[k]= 1;
1.230     brouard  8467:       nqfveff++;
1.234     brouard  8468:       modell[k].maintype= FTYPE;
                   8469:       modell[k].subtype= FQ;
                   8470:       nsq++;
                   8471:       TvarsQ[nsq]=Tvar[k];
                   8472:       TvarsQind[nsq]=k;
1.232     brouard  8473:       ncovf++;
1.234     brouard  8474:       TvarF[ncovf]=Tvar[k];
                   8475:       TvarFind[ncovf]=k;
1.231     brouard  8476:       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  8477:       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  8478:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying variables */
1.227     brouard  8479:       Fixed[k]= 1;
                   8480:       Dummy[k]= 0;
1.225     brouard  8481:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8482:       modell[k].maintype= VTYPE;
                   8483:       modell[k].subtype= VD;
                   8484:       nsd++;
                   8485:       TvarsD[nsd]=Tvar[k];
                   8486:       TvarsDind[nsd]=k;
                   8487:       ncovv++; /* Only simple time varying variables */
                   8488:       TvarV[ncovv]=Tvar[k];
                   8489:       TvarVind[ncovv]=k;
1.231     brouard  8490:       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 */
                   8491:       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  8492:       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);
                   8493:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8494:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8495:       Fixed[k]= 1;
                   8496:       Dummy[k]= 1;
                   8497:       nqtveff++;
                   8498:       modell[k].maintype= VTYPE;
                   8499:       modell[k].subtype= VQ;
                   8500:       ncovv++; /* Only simple time varying variables */
                   8501:       nsq++;
                   8502:       TvarsQ[nsq]=Tvar[k];
                   8503:       TvarsQind[nsq]=k;
                   8504:       TvarV[ncovv]=Tvar[k];
                   8505:       TvarVind[ncovv]=k;
1.231     brouard  8506:       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 */
                   8507:       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  8508:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8509:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8510:       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  8511:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8512:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8513:       ncova++;
                   8514:       TvarA[ncova]=Tvar[k];
                   8515:       TvarAind[ncova]=k;
1.231     brouard  8516:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.234     brouard  8517:        Fixed[k]= 2;
                   8518:        Dummy[k]= 2;
                   8519:        modell[k].maintype= ATYPE;
                   8520:        modell[k].subtype= APFD;
                   8521:        /* ncoveff++; */
1.227     brouard  8522:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.234     brouard  8523:        Fixed[k]= 2;
                   8524:        Dummy[k]= 3;
                   8525:        modell[k].maintype= ATYPE;
                   8526:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8527:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8528:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.234     brouard  8529:        Fixed[k]= 3;
                   8530:        Dummy[k]= 2;
                   8531:        modell[k].maintype= ATYPE;
                   8532:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8533:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8534:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.234     brouard  8535:        Fixed[k]= 3;
                   8536:        Dummy[k]= 3;
                   8537:        modell[k].maintype= ATYPE;
                   8538:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8539:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8540:       }
                   8541:     }else if (Typevar[k] == 2) {  /* product without age */
                   8542:       k1=Tposprod[k];
                   8543:       if(Tvard[k1][1] <=ncovcol){
1.234     brouard  8544:        if(Tvard[k1][2] <=ncovcol){
                   8545:          Fixed[k]= 1;
                   8546:          Dummy[k]= 0;
                   8547:          modell[k].maintype= FTYPE;
                   8548:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8549:          ncovf++; /* Fixed variables without age */
                   8550:          TvarF[ncovf]=Tvar[k];
                   8551:          TvarFind[ncovf]=k;
                   8552:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8553:          Fixed[k]= 0;  /* or 2 ?*/
                   8554:          Dummy[k]= 1;
                   8555:          modell[k].maintype= FTYPE;
                   8556:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8557:          ncovf++; /* Varying variables without age */
                   8558:          TvarF[ncovf]=Tvar[k];
                   8559:          TvarFind[ncovf]=k;
                   8560:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8561:          Fixed[k]= 1;
                   8562:          Dummy[k]= 0;
                   8563:          modell[k].maintype= VTYPE;
                   8564:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8565:          ncovv++; /* Varying variables without age */
                   8566:          TvarV[ncovv]=Tvar[k];
                   8567:          TvarVind[ncovv]=k;
                   8568:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8569:          Fixed[k]= 1;
                   8570:          Dummy[k]= 1;
                   8571:          modell[k].maintype= VTYPE;
                   8572:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8573:          ncovv++; /* Varying variables without age */
                   8574:          TvarV[ncovv]=Tvar[k];
                   8575:          TvarVind[ncovv]=k;
                   8576:        } 
1.227     brouard  8577:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.234     brouard  8578:        if(Tvard[k1][2] <=ncovcol){
                   8579:          Fixed[k]= 0;  /* or 2 ?*/
                   8580:          Dummy[k]= 1;
                   8581:          modell[k].maintype= FTYPE;
                   8582:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8583:          ncovf++; /* Fixed variables without age */
                   8584:          TvarF[ncovf]=Tvar[k];
                   8585:          TvarFind[ncovf]=k;
                   8586:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8587:          Fixed[k]= 1;
                   8588:          Dummy[k]= 1;
                   8589:          modell[k].maintype= VTYPE;
                   8590:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8591:          ncovv++; /* Varying variables without age */
                   8592:          TvarV[ncovv]=Tvar[k];
                   8593:          TvarVind[ncovv]=k;
                   8594:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8595:          Fixed[k]= 1;
                   8596:          Dummy[k]= 1;
                   8597:          modell[k].maintype= VTYPE;
                   8598:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8599:          ncovv++; /* Varying variables without age */
                   8600:          TvarV[ncovv]=Tvar[k];
                   8601:          TvarVind[ncovv]=k;
                   8602:          ncovv++; /* Varying variables without age */
                   8603:          TvarV[ncovv]=Tvar[k];
                   8604:          TvarVind[ncovv]=k;
                   8605:        } 
1.227     brouard  8606:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.234     brouard  8607:        if(Tvard[k1][2] <=ncovcol){
                   8608:          Fixed[k]= 1;
                   8609:          Dummy[k]= 1;
                   8610:          modell[k].maintype= VTYPE;
                   8611:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8612:          ncovv++; /* Varying variables without age */
                   8613:          TvarV[ncovv]=Tvar[k];
                   8614:          TvarVind[ncovv]=k;
                   8615:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8616:          Fixed[k]= 1;
                   8617:          Dummy[k]= 1;
                   8618:          modell[k].maintype= VTYPE;
                   8619:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8620:          ncovv++; /* Varying variables without age */
                   8621:          TvarV[ncovv]=Tvar[k];
                   8622:          TvarVind[ncovv]=k;
                   8623:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8624:          Fixed[k]= 1;
                   8625:          Dummy[k]= 0;
                   8626:          modell[k].maintype= VTYPE;
                   8627:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8628:          ncovv++; /* Varying variables without age */
                   8629:          TvarV[ncovv]=Tvar[k];
                   8630:          TvarVind[ncovv]=k;
                   8631:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8632:          Fixed[k]= 1;
                   8633:          Dummy[k]= 1;
                   8634:          modell[k].maintype= VTYPE;
                   8635:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8636:          ncovv++; /* Varying variables without age */
                   8637:          TvarV[ncovv]=Tvar[k];
                   8638:          TvarVind[ncovv]=k;
                   8639:        } 
1.227     brouard  8640:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.234     brouard  8641:        if(Tvard[k1][2] <=ncovcol){
                   8642:          Fixed[k]= 1;
                   8643:          Dummy[k]= 1;
                   8644:          modell[k].maintype= VTYPE;
                   8645:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8646:          ncovv++; /* Varying variables without age */
                   8647:          TvarV[ncovv]=Tvar[k];
                   8648:          TvarVind[ncovv]=k;
                   8649:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8650:          Fixed[k]= 1;
                   8651:          Dummy[k]= 1;
                   8652:          modell[k].maintype= VTYPE;
                   8653:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8654:          ncovv++; /* Varying variables without age */
                   8655:          TvarV[ncovv]=Tvar[k];
                   8656:          TvarVind[ncovv]=k;
                   8657:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8658:          Fixed[k]= 1;
                   8659:          Dummy[k]= 1;
                   8660:          modell[k].maintype= VTYPE;
                   8661:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8662:          ncovv++; /* Varying variables without age */
                   8663:          TvarV[ncovv]=Tvar[k];
                   8664:          TvarVind[ncovv]=k;
                   8665:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8666:          Fixed[k]= 1;
                   8667:          Dummy[k]= 1;
                   8668:          modell[k].maintype= VTYPE;
                   8669:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8670:          ncovv++; /* Varying variables without age */
                   8671:          TvarV[ncovv]=Tvar[k];
                   8672:          TvarVind[ncovv]=k;
                   8673:        } 
1.227     brouard  8674:       }else{
1.234     brouard  8675:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8676:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
1.226     brouard  8677:       } /* end k1 */
1.225     brouard  8678:     }else{
1.226     brouard  8679:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8680:       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  8681:     }
1.227     brouard  8682:     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  8683:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8684:     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]);
                   8685:   }
                   8686:   /* Searching for doublons in the model */
                   8687:   for(k1=1; k1<= cptcovt;k1++){
                   8688:     for(k2=1; k2 <k1;k2++){
                   8689:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8690:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8691:          if(Tvar[k1]==Tvar[k2]){
                   8692:            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]]);
                   8693:            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);
                   8694:            return(1);
                   8695:          }
                   8696:        }else if (Typevar[k1] ==2){
                   8697:          k3=Tposprod[k1];
                   8698:          k4=Tposprod[k2];
                   8699:          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])) ){
                   8700:            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]]);
                   8701:            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);
                   8702:            return(1);
                   8703:          }
                   8704:        }
1.227     brouard  8705:       }
                   8706:     }
1.225     brouard  8707:   }
                   8708:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8709:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8710:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8711:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8712:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8713:   /*endread:*/
1.225     brouard  8714:   printf("Exiting decodemodel: ");
                   8715:   return (1);
1.136     brouard  8716: }
                   8717: 
1.169     brouard  8718: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8719: {
                   8720:   int i, m;
1.218     brouard  8721:   int firstone=0;
                   8722:   
1.136     brouard  8723:   for (i=1; i<=imx; i++) {
                   8724:     for(m=2; (m<= maxwav); m++) {
                   8725:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8726:        anint[m][i]=9999;
1.216     brouard  8727:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8728:          s[m][i]=-1;
1.136     brouard  8729:       }
                   8730:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8731:        *nberr = *nberr + 1;
1.218     brouard  8732:        if(firstone == 0){
                   8733:          firstone=1;
                   8734:        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);
                   8735:        }
                   8736:        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  8737:        s[m][i]=-1;
                   8738:       }
                   8739:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8740:        (*nberr)++;
1.136     brouard  8741:        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]); 
                   8742:        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]); 
                   8743:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8744:       }
                   8745:     }
                   8746:   }
                   8747: 
                   8748:   for (i=1; i<=imx; i++)  {
                   8749:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8750:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8751:       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  8752:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8753:          if(agedc[i]>0){
                   8754:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8755:              agev[m][i]=agedc[i];
1.214     brouard  8756:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8757:            }else {
1.136     brouard  8758:              if ((int)andc[i]!=9999){
                   8759:                nbwarn++;
                   8760:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8761:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8762:                agev[m][i]=-1;
                   8763:              }
                   8764:            }
1.169     brouard  8765:          } /* agedc > 0 */
1.214     brouard  8766:        } /* end if */
1.136     brouard  8767:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8768:                                 years but with the precision of a month */
                   8769:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8770:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8771:            agev[m][i]=1;
                   8772:          else if(agev[m][i] < *agemin){ 
                   8773:            *agemin=agev[m][i];
                   8774:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8775:          }
                   8776:          else if(agev[m][i] >*agemax){
                   8777:            *agemax=agev[m][i];
1.156     brouard  8778:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8779:          }
                   8780:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8781:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8782:        } /* en if 9*/
1.136     brouard  8783:        else { /* =9 */
1.214     brouard  8784:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8785:          agev[m][i]=1;
                   8786:          s[m][i]=-1;
                   8787:        }
                   8788:       }
1.214     brouard  8789:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8790:        agev[m][i]=1;
1.214     brouard  8791:       else{
                   8792:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8793:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8794:        agev[m][i]=0;
                   8795:       }
                   8796:     } /* End for lastpass */
                   8797:   }
1.136     brouard  8798:     
                   8799:   for (i=1; i<=imx; i++)  {
                   8800:     for(m=firstpass; (m<=lastpass); m++){
                   8801:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8802:        (*nberr)++;
1.136     brouard  8803:        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);     
                   8804:        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);     
                   8805:        return 1;
                   8806:       }
                   8807:     }
                   8808:   }
                   8809: 
                   8810:   /*for (i=1; i<=imx; i++){
                   8811:   for (m=firstpass; (m<lastpass); m++){
                   8812:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8813: }
                   8814: 
                   8815: }*/
                   8816: 
                   8817: 
1.139     brouard  8818:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8819:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8820: 
                   8821:   return (0);
1.164     brouard  8822:  /* endread:*/
1.136     brouard  8823:     printf("Exiting calandcheckages: ");
                   8824:     return (1);
                   8825: }
                   8826: 
1.172     brouard  8827: #if defined(_MSC_VER)
                   8828: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8829: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8830: //#include "stdafx.h"
                   8831: //#include <stdio.h>
                   8832: //#include <tchar.h>
                   8833: //#include <windows.h>
                   8834: //#include <iostream>
                   8835: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8836: 
                   8837: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8838: 
                   8839: BOOL IsWow64()
                   8840: {
                   8841:        BOOL bIsWow64 = FALSE;
                   8842: 
                   8843:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8844:        //  (HANDLE, PBOOL);
                   8845: 
                   8846:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8847: 
                   8848:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8849:        const char funcName[] = "IsWow64Process";
                   8850:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8851:                GetProcAddress(module, funcName);
                   8852: 
                   8853:        if (NULL != fnIsWow64Process)
                   8854:        {
                   8855:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8856:                        &bIsWow64))
                   8857:                        //throw std::exception("Unknown error");
                   8858:                        printf("Unknown error\n");
                   8859:        }
                   8860:        return bIsWow64 != FALSE;
                   8861: }
                   8862: #endif
1.177     brouard  8863: 
1.191     brouard  8864: void syscompilerinfo(int logged)
1.167     brouard  8865:  {
                   8866:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8867:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8868:    /* /GS /W3 /Gy
                   8869:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8870:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8871:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8872:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8873:    */ 
                   8874:    /* 64 bits */
1.185     brouard  8875:    /*
                   8876:      /GS /W3 /Gy
                   8877:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8878:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8879:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8880:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8881:    /* Optimization are useless and O3 is slower than O2 */
                   8882:    /*
                   8883:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8884:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8885:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8886:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8887:    */
1.186     brouard  8888:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8889:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8890:       /PDB:"visual studio
                   8891:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8892:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8893:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8894:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   8895:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   8896:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   8897:       uiAccess='false'"
                   8898:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   8899:       /NOLOGO /TLBID:1
                   8900:    */
1.177     brouard  8901: #if defined __INTEL_COMPILER
1.178     brouard  8902: #if defined(__GNUC__)
                   8903:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   8904: #endif
1.177     brouard  8905: #elif defined(__GNUC__) 
1.179     brouard  8906: #ifndef  __APPLE__
1.174     brouard  8907: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  8908: #endif
1.177     brouard  8909:    struct utsname sysInfo;
1.178     brouard  8910:    int cross = CROSS;
                   8911:    if (cross){
                   8912:           printf("Cross-");
1.191     brouard  8913:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  8914:    }
1.174     brouard  8915: #endif
                   8916: 
1.171     brouard  8917: #include <stdint.h>
1.178     brouard  8918: 
1.191     brouard  8919:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  8920: #if defined(__clang__)
1.191     brouard  8921:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  8922: #endif
                   8923: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  8924:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  8925: #endif
                   8926: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  8927:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  8928: #endif
                   8929: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  8930:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  8931: #endif
                   8932: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  8933:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  8934: #endif
                   8935: #if defined(_MSC_VER)
1.191     brouard  8936:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  8937: #endif
                   8938: #if defined(__PGI)
1.191     brouard  8939:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  8940: #endif
                   8941: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  8942:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  8943: #endif
1.191     brouard  8944:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  8945:    
1.167     brouard  8946: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   8947: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   8948:     // Windows (x64 and x86)
1.191     brouard  8949:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  8950: #elif __unix__ // all unices, not all compilers
                   8951:     // Unix
1.191     brouard  8952:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  8953: #elif __linux__
                   8954:     // linux
1.191     brouard  8955:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  8956: #elif __APPLE__
1.174     brouard  8957:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  8958:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  8959: #endif
                   8960: 
                   8961: /*  __MINGW32__          */
                   8962: /*  __CYGWIN__  */
                   8963: /* __MINGW64__  */
                   8964: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   8965: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   8966: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   8967: /* _WIN64  // Defined for applications for Win64. */
                   8968: /* _M_X64 // Defined for compilations that target x64 processors. */
                   8969: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  8970: 
1.167     brouard  8971: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  8972:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  8973: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  8974:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  8975: #else
1.191     brouard  8976:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  8977: #endif
                   8978: 
1.169     brouard  8979: #if defined(__GNUC__)
                   8980: # if defined(__GNUC_PATCHLEVEL__)
                   8981: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8982:                             + __GNUC_MINOR__ * 100 \
                   8983:                             + __GNUC_PATCHLEVEL__)
                   8984: # else
                   8985: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8986:                             + __GNUC_MINOR__ * 100)
                   8987: # endif
1.174     brouard  8988:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  8989:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  8990: 
                   8991:    if (uname(&sysInfo) != -1) {
                   8992:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  8993:         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  8994:    }
                   8995:    else
                   8996:       perror("uname() error");
1.179     brouard  8997:    //#ifndef __INTEL_COMPILER 
                   8998: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  8999:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9000:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9001: #endif
1.169     brouard  9002: #endif
1.172     brouard  9003: 
                   9004:    //   void main()
                   9005:    //   {
1.169     brouard  9006: #if defined(_MSC_VER)
1.174     brouard  9007:    if (IsWow64()){
1.191     brouard  9008:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9009:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9010:    }
                   9011:    else{
1.191     brouard  9012:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9013:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9014:    }
1.172     brouard  9015:    //     printf("\nPress Enter to continue...");
                   9016:    //     getchar();
                   9017:    //   }
                   9018: 
1.169     brouard  9019: #endif
                   9020:    
1.167     brouard  9021: 
1.219     brouard  9022: }
1.136     brouard  9023: 
1.219     brouard  9024: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9025:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9026:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9027:   /* double ftolpl = 1.e-10; */
1.180     brouard  9028:   double age, agebase, agelim;
1.203     brouard  9029:   double tot;
1.180     brouard  9030: 
1.202     brouard  9031:   strcpy(filerespl,"PL_");
                   9032:   strcat(filerespl,fileresu);
                   9033:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9034:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9035:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9036:   }
1.227     brouard  9037:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9038:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9039:   pstamp(ficrespl);
1.203     brouard  9040:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9041:   fprintf(ficrespl,"#Age ");
                   9042:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9043:   fprintf(ficrespl,"\n");
1.180     brouard  9044:   
1.219     brouard  9045:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9046: 
1.219     brouard  9047:   agebase=ageminpar;
                   9048:   agelim=agemaxpar;
1.180     brouard  9049: 
1.227     brouard  9050:   /* i1=pow(2,ncoveff); */
1.234     brouard  9051:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9052:   if (cptcovn < 1){i1=1;}
1.180     brouard  9053: 
1.238   ! brouard  9054:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
        !          9055:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          9056:       if(TKresult[nres]!= k)
        !          9057:        continue;
1.235     brouard  9058: 
1.238   ! brouard  9059:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
        !          9060:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
        !          9061:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
        !          9062:       /* k=k+1; */
        !          9063:       /* to clean */
        !          9064:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
        !          9065:       fprintf(ficrespl,"#******");
        !          9066:       printf("#******");
        !          9067:       fprintf(ficlog,"#******");
        !          9068:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
        !          9069:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
        !          9070:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9071:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9072:       }
        !          9073:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
        !          9074:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          9075:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          9076:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
        !          9077:       }
        !          9078:       fprintf(ficrespl,"******\n");
        !          9079:       printf("******\n");
        !          9080:       fprintf(ficlog,"******\n");
        !          9081:       if(invalidvarcomb[k]){
        !          9082:        printf("\nCombination (%d) ignored because no case \n",k); 
        !          9083:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
        !          9084:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
        !          9085:        continue;
        !          9086:       }
1.219     brouard  9087: 
1.238   ! brouard  9088:       fprintf(ficrespl,"#Age ");
        !          9089:       for(j=1;j<=cptcoveff;j++) {
        !          9090:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9091:       }
        !          9092:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
        !          9093:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9094:     
1.238   ! brouard  9095:       for (age=agebase; age<=agelim; age++){
        !          9096:        /* for (age=agebase; age<=agebase; age++){ */
        !          9097:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
        !          9098:        fprintf(ficrespl,"%.0f ",age );
        !          9099:        for(j=1;j<=cptcoveff;j++)
        !          9100:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9101:        tot=0.;
        !          9102:        for(i=1; i<=nlstate;i++){
        !          9103:          tot +=  prlim[i][i];
        !          9104:          fprintf(ficrespl," %.5f", prlim[i][i]);
        !          9105:        }
        !          9106:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
        !          9107:       } /* Age */
        !          9108:       /* was end of cptcod */
        !          9109:     } /* cptcov */
        !          9110:   } /* nres */
1.219     brouard  9111:   return 0;
1.180     brouard  9112: }
                   9113: 
1.218     brouard  9114: 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){
                   9115:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9116:        
                   9117:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9118:    * at any age between ageminpar and agemaxpar
                   9119:         */
1.235     brouard  9120:   int i, j, k, i1, nres=0 ;
1.217     brouard  9121:   /* double ftolpl = 1.e-10; */
                   9122:   double age, agebase, agelim;
                   9123:   double tot;
1.218     brouard  9124:   /* double ***mobaverage; */
                   9125:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9126: 
                   9127:   strcpy(fileresplb,"PLB_");
                   9128:   strcat(fileresplb,fileresu);
                   9129:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9130:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9131:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9132:   }
                   9133:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9134:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9135:   pstamp(ficresplb);
                   9136:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9137:   fprintf(ficresplb,"#Age ");
                   9138:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9139:   fprintf(ficresplb,"\n");
                   9140:   
1.218     brouard  9141:   
                   9142:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9143:   
                   9144:   agebase=ageminpar;
                   9145:   agelim=agemaxpar;
                   9146:   
                   9147:   
1.227     brouard  9148:   i1=pow(2,cptcoveff);
1.218     brouard  9149:   if (cptcovn < 1){i1=1;}
1.227     brouard  9150:   
1.238   ! brouard  9151:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          9152:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
        !          9153:       if(TKresult[nres]!= k)
        !          9154:        continue;
        !          9155:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
        !          9156:       fprintf(ficresplb,"#******");
        !          9157:       printf("#******");
        !          9158:       fprintf(ficlog,"#******");
        !          9159:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
        !          9160:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9161:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9162:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9163:       }
        !          9164:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
        !          9165:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          9166:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          9167:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          9168:       }
        !          9169:       fprintf(ficresplb,"******\n");
        !          9170:       printf("******\n");
        !          9171:       fprintf(ficlog,"******\n");
        !          9172:       if(invalidvarcomb[k]){
        !          9173:        printf("\nCombination (%d) ignored because no cases \n",k); 
        !          9174:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
        !          9175:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
        !          9176:        continue;
        !          9177:       }
1.218     brouard  9178:     
1.238   ! brouard  9179:       fprintf(ficresplb,"#Age ");
        !          9180:       for(j=1;j<=cptcoveff;j++) {
        !          9181:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9182:       }
        !          9183:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
        !          9184:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9185:     
                   9186:     
1.238   ! brouard  9187:       for (age=agebase; age<=agelim; age++){
        !          9188:        /* for (age=agebase; age<=agebase; age++){ */
        !          9189:        if(mobilavproj > 0){
        !          9190:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
        !          9191:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
        !          9192:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
        !          9193:        }else if (mobilavproj == 0){
        !          9194:          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);
        !          9195:          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);
        !          9196:          exit(1);
        !          9197:        }else{
        !          9198:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
        !          9199:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
        !          9200:        }
        !          9201:        fprintf(ficresplb,"%.0f ",age );
        !          9202:        for(j=1;j<=cptcoveff;j++)
        !          9203:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9204:        tot=0.;
        !          9205:        for(i=1; i<=nlstate;i++){
        !          9206:          tot +=  bprlim[i][i];
        !          9207:          fprintf(ficresplb," %.5f", bprlim[i][i]);
        !          9208:        }
        !          9209:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
        !          9210:       } /* Age */
        !          9211:       /* was end of cptcod */
        !          9212:     } /* end of any combination */
        !          9213:   } /* end of nres */  
1.218     brouard  9214:   /* hBijx(p, bage, fage); */
                   9215:   /* fclose(ficrespijb); */
                   9216:   
                   9217:   return 0;
1.217     brouard  9218: }
1.218     brouard  9219:  
1.180     brouard  9220: int hPijx(double *p, int bage, int fage){
                   9221:     /*------------- h Pij x at various ages ------------*/
                   9222: 
                   9223:   int stepsize;
                   9224:   int agelim;
                   9225:   int hstepm;
                   9226:   int nhstepm;
1.235     brouard  9227:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9228: 
                   9229:   double agedeb;
                   9230:   double ***p3mat;
                   9231: 
1.201     brouard  9232:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9233:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9234:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9235:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9236:     }
                   9237:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9238:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9239:   
                   9240:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9241:     /*if (stepm<=24) stepsize=2;*/
                   9242: 
                   9243:     agelim=AGESUP;
                   9244:     hstepm=stepsize*YEARM; /* Every year of age */
                   9245:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9246:                
1.180     brouard  9247:     /* hstepm=1;   aff par mois*/
                   9248:     pstamp(ficrespij);
                   9249:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9250:     i1= pow(2,cptcoveff);
1.218     brouard  9251:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9252:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9253:                /*      k=k+1;  */
1.235     brouard  9254:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9255:     for(k=1; k<=i1;k++){
                   9256:       if(TKresult[nres]!= k)
                   9257:        continue;
1.183     brouard  9258:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9259:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9260:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9261:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9262:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9263:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9264:       }
1.183     brouard  9265:       fprintf(ficrespij,"******\n");
                   9266:       
                   9267:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9268:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9269:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9270:        
                   9271:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9272:        
1.183     brouard  9273:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9274:        oldm=oldms;savm=savms;
1.235     brouard  9275:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9276:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9277:        for(i=1; i<=nlstate;i++)
                   9278:          for(j=1; j<=nlstate+ndeath;j++)
                   9279:            fprintf(ficrespij," %1d-%1d",i,j);
                   9280:        fprintf(ficrespij,"\n");
                   9281:        for (h=0; h<=nhstepm; h++){
                   9282:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9283:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9284:          for(i=1; i<=nlstate;i++)
                   9285:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9286:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9287:          fprintf(ficrespij,"\n");
                   9288:        }
1.183     brouard  9289:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9290:        fprintf(ficrespij,"\n");
                   9291:       }
1.180     brouard  9292:       /*}*/
                   9293:     }
1.218     brouard  9294:     return 0;
1.180     brouard  9295: }
1.218     brouard  9296:  
                   9297:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9298:     /*------------- h Bij x at various ages ------------*/
                   9299: 
                   9300:   int stepsize;
1.218     brouard  9301:   /* int agelim; */
                   9302:        int ageminl;
1.217     brouard  9303:   int hstepm;
                   9304:   int nhstepm;
1.238   ! brouard  9305:   int h, i, i1, j, k, nres;
1.218     brouard  9306:        
1.217     brouard  9307:   double agedeb;
                   9308:   double ***p3mat;
1.218     brouard  9309:        
                   9310:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9311:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9312:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9313:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9314:   }
                   9315:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9316:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9317:   
                   9318:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9319:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9320:   
1.218     brouard  9321:   /* agelim=AGESUP; */
                   9322:   ageminl=30;
                   9323:   hstepm=stepsize*YEARM; /* Every year of age */
                   9324:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9325:   
                   9326:   /* hstepm=1;   aff par mois*/
                   9327:   pstamp(ficrespijb);
                   9328:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9329:   i1= pow(2,cptcoveff);
1.218     brouard  9330:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9331:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9332:   /*   k=k+1;  */
1.238   ! brouard  9333:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          9334:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
        !          9335:       if(TKresult[nres]!= k)
        !          9336:        continue;
        !          9337:       fprintf(ficrespijb,"\n#****** ");
        !          9338:       for(j=1;j<=cptcoveff;j++)
        !          9339:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
        !          9340:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
        !          9341:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          9342:       }
        !          9343:       fprintf(ficrespijb,"******\n");
        !          9344:       if(invalidvarcomb[k]){
        !          9345:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
        !          9346:        continue;
        !          9347:       }
        !          9348:       
        !          9349:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
        !          9350:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
        !          9351:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
        !          9352:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
        !          9353:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
        !          9354:        
        !          9355:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
        !          9356:        
        !          9357:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          9358:        /* oldm=oldms;savm=savms; */
        !          9359:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
        !          9360:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
        !          9361:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
        !          9362:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9363:        for(i=1; i<=nlstate;i++)
                   9364:          for(j=1; j<=nlstate+ndeath;j++)
1.238   ! brouard  9365:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9366:        fprintf(ficrespijb,"\n");
1.238   ! brouard  9367:        for (h=0; h<=nhstepm; h++){
        !          9368:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
        !          9369:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
        !          9370:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
        !          9371:          for(i=1; i<=nlstate;i++)
        !          9372:            for(j=1; j<=nlstate+ndeath;j++)
        !          9373:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
        !          9374:          fprintf(ficrespijb,"\n");
        !          9375:        }
        !          9376:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          9377:        fprintf(ficrespijb,"\n");
        !          9378:       } /* end age deb */
        !          9379:     } /* end combination */
        !          9380:   } /* end nres */
1.218     brouard  9381:   return 0;
                   9382:  } /*  hBijx */
1.217     brouard  9383: 
1.180     brouard  9384: 
1.136     brouard  9385: /***********************************************/
                   9386: /**************** Main Program *****************/
                   9387: /***********************************************/
                   9388: 
                   9389: int main(int argc, char *argv[])
                   9390: {
                   9391: #ifdef GSL
                   9392:   const gsl_multimin_fminimizer_type *T;
                   9393:   size_t iteri = 0, it;
                   9394:   int rval = GSL_CONTINUE;
                   9395:   int status = GSL_SUCCESS;
                   9396:   double ssval;
                   9397: #endif
                   9398:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9399:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9400:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9401:   int jj, ll, li, lj, lk;
1.136     brouard  9402:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9403:   int num_filled;
1.136     brouard  9404:   int itimes;
                   9405:   int NDIM=2;
                   9406:   int vpopbased=0;
1.235     brouard  9407:   int nres=0;
1.136     brouard  9408: 
1.164     brouard  9409:   char ca[32], cb[32];
1.136     brouard  9410:   /*  FILE *fichtm; *//* Html File */
                   9411:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9412:   struct stat info;
1.191     brouard  9413:   double agedeb=0.;
1.194     brouard  9414: 
                   9415:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9416:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9417: 
1.165     brouard  9418:   double fret;
1.191     brouard  9419:   double dum=0.; /* Dummy variable */
1.136     brouard  9420:   double ***p3mat;
1.218     brouard  9421:   /* double ***mobaverage; */
1.164     brouard  9422: 
                   9423:   char line[MAXLINE];
1.197     brouard  9424:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9425: 
1.234     brouard  9426:   char  modeltemp[MAXLINE];
1.230     brouard  9427:   char resultline[MAXLINE];
                   9428:   
1.136     brouard  9429:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9430:   char *tok, *val; /* pathtot */
1.136     brouard  9431:   int firstobs=1, lastobs=10;
1.195     brouard  9432:   int c,  h , cpt, c2;
1.191     brouard  9433:   int jl=0;
                   9434:   int i1, j1, jk, stepsize=0;
1.194     brouard  9435:   int count=0;
                   9436: 
1.164     brouard  9437:   int *tab; 
1.136     brouard  9438:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9439:   int backcast=0;
1.136     brouard  9440:   int mobilav=0,popforecast=0;
1.191     brouard  9441:   int hstepm=0, nhstepm=0;
1.136     brouard  9442:   int agemortsup;
                   9443:   float  sumlpop=0.;
                   9444:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9445:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9446: 
1.191     brouard  9447:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9448:   double ftolpl=FTOL;
                   9449:   double **prlim;
1.217     brouard  9450:   double **bprlim;
1.136     brouard  9451:   double ***param; /* Matrix of parameters */
                   9452:   double  *p;
                   9453:   double **matcov; /* Matrix of covariance */
1.203     brouard  9454:   double **hess; /* Hessian matrix */
1.136     brouard  9455:   double ***delti3; /* Scale */
                   9456:   double *delti; /* Scale */
                   9457:   double ***eij, ***vareij;
                   9458:   double **varpl; /* Variances of prevalence limits by age */
                   9459:   double *epj, vepp;
1.164     brouard  9460: 
1.136     brouard  9461:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9462:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9463: 
1.136     brouard  9464:   double **ximort;
1.145     brouard  9465:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9466:   int *dcwave;
                   9467: 
1.164     brouard  9468:   char z[1]="c";
1.136     brouard  9469: 
                   9470:   /*char  *strt;*/
                   9471:   char strtend[80];
1.126     brouard  9472: 
1.164     brouard  9473: 
1.126     brouard  9474: /*   setlocale (LC_ALL, ""); */
                   9475: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9476: /*   textdomain (PACKAGE); */
                   9477: /*   setlocale (LC_CTYPE, ""); */
                   9478: /*   setlocale (LC_MESSAGES, ""); */
                   9479: 
                   9480:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9481:   rstart_time = time(NULL);  
                   9482:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9483:   start_time = *localtime(&rstart_time);
1.126     brouard  9484:   curr_time=start_time;
1.157     brouard  9485:   /*tml = *localtime(&start_time.tm_sec);*/
                   9486:   /* strcpy(strstart,asctime(&tml)); */
                   9487:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9488: 
                   9489: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9490: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9491: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9492: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9493: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9494: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9495: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9496: /*   strt=asctime(&tmg); */
                   9497: /*   printf("Time(after) =%s",strstart);  */
                   9498: /*  (void) time (&time_value);
                   9499: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9500: *  tm = *localtime(&time_value);
                   9501: *  strstart=asctime(&tm);
                   9502: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9503: */
                   9504: 
                   9505:   nberr=0; /* Number of errors and warnings */
                   9506:   nbwarn=0;
1.184     brouard  9507: #ifdef WIN32
                   9508:   _getcwd(pathcd, size);
                   9509: #else
1.126     brouard  9510:   getcwd(pathcd, size);
1.184     brouard  9511: #endif
1.191     brouard  9512:   syscompilerinfo(0);
1.196     brouard  9513:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9514:   if(argc <=1){
                   9515:     printf("\nEnter the parameter file name: ");
1.205     brouard  9516:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9517:       printf("ERROR Empty parameter file name\n");
                   9518:       goto end;
                   9519:     }
1.126     brouard  9520:     i=strlen(pathr);
                   9521:     if(pathr[i-1]=='\n')
                   9522:       pathr[i-1]='\0';
1.156     brouard  9523:     i=strlen(pathr);
1.205     brouard  9524:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9525:       pathr[i-1]='\0';
1.205     brouard  9526:     }
                   9527:     i=strlen(pathr);
                   9528:     if( i==0 ){
                   9529:       printf("ERROR Empty parameter file name\n");
                   9530:       goto end;
                   9531:     }
                   9532:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9533:       printf("Pathr |%s|\n",pathr);
                   9534:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9535:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9536:       strcpy (pathtot, val);
                   9537:       if(pathr[0] == '\0') break; /* Dirty */
                   9538:     }
                   9539:   }
                   9540:   else{
                   9541:     strcpy(pathtot,argv[1]);
                   9542:   }
                   9543:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9544:   /*cygwin_split_path(pathtot,path,optionfile);
                   9545:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9546:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9547: 
                   9548:   /* Split argv[0], imach program to get pathimach */
                   9549:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9550:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9551:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9552:  /*   strcpy(pathimach,argv[0]); */
                   9553:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9554:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9555:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9556: #ifdef WIN32
                   9557:   _chdir(path); /* Can be a relative path */
                   9558:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9559: #else
1.126     brouard  9560:   chdir(path); /* Can be a relative path */
1.184     brouard  9561:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9562: #endif
                   9563:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9564:   strcpy(command,"mkdir ");
                   9565:   strcat(command,optionfilefiname);
                   9566:   if((outcmd=system(command)) != 0){
1.169     brouard  9567:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9568:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9569:     /* fclose(ficlog); */
                   9570: /*     exit(1); */
                   9571:   }
                   9572: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9573: /*     perror("mkdir"); */
                   9574: /*   } */
                   9575: 
                   9576:   /*-------- arguments in the command line --------*/
                   9577: 
1.186     brouard  9578:   /* Main Log file */
1.126     brouard  9579:   strcat(filelog, optionfilefiname);
                   9580:   strcat(filelog,".log");    /* */
                   9581:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9582:     printf("Problem with logfile %s\n",filelog);
                   9583:     goto end;
                   9584:   }
                   9585:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9586:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9587:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9588:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9589:  path=%s \n\
                   9590:  optionfile=%s\n\
                   9591:  optionfilext=%s\n\
1.156     brouard  9592:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9593: 
1.197     brouard  9594:   syscompilerinfo(1);
1.167     brouard  9595: 
1.126     brouard  9596:   printf("Local time (at start):%s",strstart);
                   9597:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9598:   fflush(ficlog);
                   9599: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9600: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9601: 
                   9602:   /* */
                   9603:   strcpy(fileres,"r");
                   9604:   strcat(fileres, optionfilefiname);
1.201     brouard  9605:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9606:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9607:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9608: 
1.186     brouard  9609:   /* Main ---------arguments file --------*/
1.126     brouard  9610: 
                   9611:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9612:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9613:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9614:     fflush(ficlog);
1.149     brouard  9615:     /* goto end; */
                   9616:     exit(70); 
1.126     brouard  9617:   }
                   9618: 
                   9619: 
                   9620: 
                   9621:   strcpy(filereso,"o");
1.201     brouard  9622:   strcat(filereso,fileresu);
1.126     brouard  9623:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9624:     printf("Problem with Output resultfile: %s\n", filereso);
                   9625:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9626:     fflush(ficlog);
                   9627:     goto end;
                   9628:   }
                   9629: 
                   9630:   /* Reads comments: lines beginning with '#' */
                   9631:   numlinepar=0;
1.197     brouard  9632: 
                   9633:     /* First parameter line */
                   9634:   while(fgets(line, MAXLINE, ficpar)) {
                   9635:     /* If line starts with a # it is a comment */
                   9636:     if (line[0] == '#') {
                   9637:       numlinepar++;
                   9638:       fputs(line,stdout);
                   9639:       fputs(line,ficparo);
                   9640:       fputs(line,ficlog);
                   9641:       continue;
                   9642:     }else
                   9643:       break;
                   9644:   }
                   9645:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9646:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9647:     if (num_filled != 5) {
                   9648:       printf("Should be 5 parameters\n");
                   9649:     }
1.126     brouard  9650:     numlinepar++;
1.197     brouard  9651:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9652:   }
                   9653:   /* Second parameter line */
                   9654:   while(fgets(line, MAXLINE, ficpar)) {
                   9655:     /* If line starts with a # it is a comment */
                   9656:     if (line[0] == '#') {
                   9657:       numlinepar++;
                   9658:       fputs(line,stdout);
                   9659:       fputs(line,ficparo);
                   9660:       fputs(line,ficlog);
                   9661:       continue;
                   9662:     }else
                   9663:       break;
                   9664:   }
1.223     brouard  9665:   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", \
                   9666:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9667:     if (num_filled != 11) {
                   9668:       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  9669:       printf("but line=%s\n",line);
1.197     brouard  9670:     }
1.223     brouard  9671:     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  9672:   }
1.203     brouard  9673:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9674:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9675:   /* Third parameter line */
                   9676:   while(fgets(line, MAXLINE, ficpar)) {
                   9677:     /* If line starts with a # it is a comment */
                   9678:     if (line[0] == '#') {
                   9679:       numlinepar++;
                   9680:       fputs(line,stdout);
                   9681:       fputs(line,ficparo);
                   9682:       fputs(line,ficlog);
                   9683:       continue;
                   9684:     }else
                   9685:       break;
                   9686:   }
1.201     brouard  9687:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9688:     if (num_filled == 0)
                   9689:             model[0]='\0';
                   9690:     else if (num_filled != 1){
1.197     brouard  9691:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9692:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9693:       model[0]='\0';
                   9694:       goto end;
                   9695:     }
                   9696:     else{
                   9697:       if (model[0]=='+'){
                   9698:        for(i=1; i<=strlen(model);i++)
                   9699:          modeltemp[i-1]=model[i];
1.201     brouard  9700:        strcpy(model,modeltemp); 
1.197     brouard  9701:       }
                   9702:     }
1.199     brouard  9703:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9704:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9705:   }
                   9706:   /* 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); */
                   9707:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9708:   /* 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  9709:   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);
                   9710:   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  9711:   fflush(ficlog);
1.190     brouard  9712:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9713:   if(model[0]=='#'){
1.187     brouard  9714:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9715:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9716:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9717:     if(mle != -1){
                   9718:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9719:       exit(1);
                   9720:     }
                   9721:   }
1.126     brouard  9722:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9723:     ungetc(c,ficpar);
                   9724:     fgets(line, MAXLINE, ficpar);
                   9725:     numlinepar++;
1.195     brouard  9726:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9727:       z[0]=line[1];
                   9728:     }
                   9729:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9730:     fputs(line, stdout);
                   9731:     //puts(line);
1.126     brouard  9732:     fputs(line,ficparo);
                   9733:     fputs(line,ficlog);
                   9734:   }
                   9735:   ungetc(c,ficpar);
                   9736: 
                   9737:    
1.145     brouard  9738:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9739:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9740:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9741:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9742:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9743:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9744:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9745:   */
                   9746:   if (strlen(model)>1) 
1.187     brouard  9747:     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  9748:   else
1.187     brouard  9749:     ncovmodel=2; /* Constant and age */
1.133     brouard  9750:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9751:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9752:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9753:     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);
                   9754:     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);
                   9755:     fflush(stdout);
                   9756:     fclose (ficlog);
                   9757:     goto end;
                   9758:   }
1.126     brouard  9759:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9760:   delti=delti3[1][1];
                   9761:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9762:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9763:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9764:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9765:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9766:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9767:     fclose (ficparo);
                   9768:     fclose (ficlog);
                   9769:     goto end;
                   9770:     exit(0);
1.220     brouard  9771:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9772:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9773:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9774:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9775:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9776:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9777:     hess=matrix(1,npar,1,npar);
1.220     brouard  9778:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9779:     /* Read guessed parameters */
1.126     brouard  9780:     /* Reads comments: lines beginning with '#' */
                   9781:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9782:       ungetc(c,ficpar);
                   9783:       fgets(line, MAXLINE, ficpar);
                   9784:       numlinepar++;
1.141     brouard  9785:       fputs(line,stdout);
1.126     brouard  9786:       fputs(line,ficparo);
                   9787:       fputs(line,ficlog);
                   9788:     }
                   9789:     ungetc(c,ficpar);
                   9790:     
                   9791:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9792:     for(i=1; i <=nlstate; i++){
1.234     brouard  9793:       j=0;
1.126     brouard  9794:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9795:        if(jj==i) continue;
                   9796:        j++;
                   9797:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9798:        if ((i1 != i) || (j1 != jj)){
                   9799:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9800: It might be a problem of design; if ncovcol and the model are correct\n \
                   9801: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9802:          exit(1);
                   9803:        }
                   9804:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9805:        if(mle==1)
                   9806:          printf("%1d%1d",i,jj);
                   9807:        fprintf(ficlog,"%1d%1d",i,jj);
                   9808:        for(k=1; k<=ncovmodel;k++){
                   9809:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9810:          if(mle==1){
                   9811:            printf(" %lf",param[i][j][k]);
                   9812:            fprintf(ficlog," %lf",param[i][j][k]);
                   9813:          }
                   9814:          else
                   9815:            fprintf(ficlog," %lf",param[i][j][k]);
                   9816:          fprintf(ficparo," %lf",param[i][j][k]);
                   9817:        }
                   9818:        fscanf(ficpar,"\n");
                   9819:        numlinepar++;
                   9820:        if(mle==1)
                   9821:          printf("\n");
                   9822:        fprintf(ficlog,"\n");
                   9823:        fprintf(ficparo,"\n");
1.126     brouard  9824:       }
                   9825:     }  
                   9826:     fflush(ficlog);
1.234     brouard  9827:     
1.145     brouard  9828:     /* Reads scales values */
1.126     brouard  9829:     p=param[1][1];
                   9830:     
                   9831:     /* Reads comments: lines beginning with '#' */
                   9832:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9833:       ungetc(c,ficpar);
                   9834:       fgets(line, MAXLINE, ficpar);
                   9835:       numlinepar++;
1.141     brouard  9836:       fputs(line,stdout);
1.126     brouard  9837:       fputs(line,ficparo);
                   9838:       fputs(line,ficlog);
                   9839:     }
                   9840:     ungetc(c,ficpar);
                   9841: 
                   9842:     for(i=1; i <=nlstate; i++){
                   9843:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9844:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9845:        if ( (i1-i) * (j1-j) != 0){
                   9846:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9847:          exit(1);
                   9848:        }
                   9849:        printf("%1d%1d",i,j);
                   9850:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9851:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9852:        for(k=1; k<=ncovmodel;k++){
                   9853:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9854:          printf(" %le",delti3[i][j][k]);
                   9855:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9856:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9857:        }
                   9858:        fscanf(ficpar,"\n");
                   9859:        numlinepar++;
                   9860:        printf("\n");
                   9861:        fprintf(ficparo,"\n");
                   9862:        fprintf(ficlog,"\n");
1.126     brouard  9863:       }
                   9864:     }
                   9865:     fflush(ficlog);
1.234     brouard  9866:     
1.145     brouard  9867:     /* Reads covariance matrix */
1.126     brouard  9868:     delti=delti3[1][1];
1.220     brouard  9869:                
                   9870:                
1.126     brouard  9871:     /* 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  9872:                
1.126     brouard  9873:     /* Reads comments: lines beginning with '#' */
                   9874:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9875:       ungetc(c,ficpar);
                   9876:       fgets(line, MAXLINE, ficpar);
                   9877:       numlinepar++;
1.141     brouard  9878:       fputs(line,stdout);
1.126     brouard  9879:       fputs(line,ficparo);
                   9880:       fputs(line,ficlog);
                   9881:     }
                   9882:     ungetc(c,ficpar);
1.220     brouard  9883:                
1.126     brouard  9884:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9885:     hess=matrix(1,npar,1,npar);
1.131     brouard  9886:     for(i=1; i <=npar; i++)
                   9887:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9888:                
1.194     brouard  9889:     /* Scans npar lines */
1.126     brouard  9890:     for(i=1; i <=npar; i++){
1.226     brouard  9891:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  9892:       if(count != 3){
1.226     brouard  9893:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9894: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9895: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9896:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9897: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9898: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9899:        exit(1);
1.220     brouard  9900:       }else{
1.226     brouard  9901:        if(mle==1)
                   9902:          printf("%1d%1d%d",i1,j1,jk);
                   9903:       }
                   9904:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   9905:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  9906:       for(j=1; j <=i; j++){
1.226     brouard  9907:        fscanf(ficpar," %le",&matcov[i][j]);
                   9908:        if(mle==1){
                   9909:          printf(" %.5le",matcov[i][j]);
                   9910:        }
                   9911:        fprintf(ficlog," %.5le",matcov[i][j]);
                   9912:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  9913:       }
                   9914:       fscanf(ficpar,"\n");
                   9915:       numlinepar++;
                   9916:       if(mle==1)
1.220     brouard  9917:                                printf("\n");
1.126     brouard  9918:       fprintf(ficlog,"\n");
                   9919:       fprintf(ficparo,"\n");
                   9920:     }
1.194     brouard  9921:     /* End of read covariance matrix npar lines */
1.126     brouard  9922:     for(i=1; i <=npar; i++)
                   9923:       for(j=i+1;j<=npar;j++)
1.226     brouard  9924:        matcov[i][j]=matcov[j][i];
1.126     brouard  9925:     
                   9926:     if(mle==1)
                   9927:       printf("\n");
                   9928:     fprintf(ficlog,"\n");
                   9929:     
                   9930:     fflush(ficlog);
                   9931:     
                   9932:     /*-------- Rewriting parameter file ----------*/
                   9933:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   9934:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   9935:     strcat(rfileres,".");    /* */
                   9936:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   9937:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  9938:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   9939:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  9940:     }
                   9941:     fprintf(ficres,"#%s\n",version);
                   9942:   }    /* End of mle != -3 */
1.218     brouard  9943:   
1.186     brouard  9944:   /*  Main data
                   9945:    */
1.126     brouard  9946:   n= lastobs;
                   9947:   num=lvector(1,n);
                   9948:   moisnais=vector(1,n);
                   9949:   annais=vector(1,n);
                   9950:   moisdc=vector(1,n);
                   9951:   andc=vector(1,n);
1.220     brouard  9952:   weight=vector(1,n);
1.126     brouard  9953:   agedc=vector(1,n);
                   9954:   cod=ivector(1,n);
1.220     brouard  9955:   for(i=1;i<=n;i++){
1.234     brouard  9956:     num[i]=0;
                   9957:     moisnais[i]=0;
                   9958:     annais[i]=0;
                   9959:     moisdc[i]=0;
                   9960:     andc[i]=0;
                   9961:     agedc[i]=0;
                   9962:     cod[i]=0;
                   9963:     weight[i]=1.0; /* Equal weights, 1 by default */
                   9964:   }
1.126     brouard  9965:   mint=matrix(1,maxwav,1,n);
                   9966:   anint=matrix(1,maxwav,1,n);
1.131     brouard  9967:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  9968:   tab=ivector(1,NCOVMAX);
1.144     brouard  9969:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  9970:   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  9971: 
1.136     brouard  9972:   /* Reads data from file datafile */
                   9973:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   9974:     goto end;
                   9975: 
                   9976:   /* Calculation of the number of parameters from char model */
1.234     brouard  9977:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  9978:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   9979:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   9980:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   9981:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  9982:   */
                   9983:   
                   9984:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   9985:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   9986:   TvarsD=ivector(1,NCOVMAX); /*  */
                   9987:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   9988:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  9989:   TvarF=ivector(1,NCOVMAX); /*  */
                   9990:   TvarFind=ivector(1,NCOVMAX); /*  */
                   9991:   TvarV=ivector(1,NCOVMAX); /*  */
                   9992:   TvarVind=ivector(1,NCOVMAX); /*  */
                   9993:   TvarA=ivector(1,NCOVMAX); /*  */
                   9994:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  9995:   TvarFD=ivector(1,NCOVMAX); /*  */
                   9996:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   9997:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   9998:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   9999:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10000:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10001:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10002:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10003: 
1.230     brouard  10004:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10005:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10006:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10007:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10008:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.238   ! brouard  10009:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
        !          10010:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.137     brouard  10011:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10012:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10013:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10014:   */
                   10015:   /* For model-covariate k tells which data-covariate to use but
                   10016:     because this model-covariate is a construction we invent a new column
                   10017:     ncovcol + k1
                   10018:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10019:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10020:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10021:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10022:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10023:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10024:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10025:   */
1.145     brouard  10026:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10027:   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  10028:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10029:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10030:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10031:                         4 covariates (3 plus signs)
                   10032:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10033:                      */  
1.230     brouard  10034:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10035:                                * individual dummy, fixed or varying:
                   10036:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10037:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10038:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10039:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10040:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10041:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10042:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10043:                                * individual quantitative, fixed or varying:
                   10044:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10045:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10046:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10047: /* Main decodemodel */
                   10048: 
1.187     brouard  10049: 
1.223     brouard  10050:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10051:     goto end;
                   10052: 
1.137     brouard  10053:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10054:     nbwarn++;
                   10055:     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); 
                   10056:     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); 
                   10057:   }
1.136     brouard  10058:     /*  if(mle==1){*/
1.137     brouard  10059:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10060:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10061:   }
                   10062: 
                   10063:     /*-calculation of age at interview from date of interview and age at death -*/
                   10064:   agev=matrix(1,maxwav,1,imx);
                   10065: 
                   10066:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10067:     goto end;
                   10068: 
1.126     brouard  10069: 
1.136     brouard  10070:   agegomp=(int)agemin;
                   10071:   free_vector(moisnais,1,n);
                   10072:   free_vector(annais,1,n);
1.126     brouard  10073:   /* free_matrix(mint,1,maxwav,1,n);
                   10074:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10075:   /* free_vector(moisdc,1,n); */
                   10076:   /* free_vector(andc,1,n); */
1.145     brouard  10077:   /* */
                   10078:   
1.126     brouard  10079:   wav=ivector(1,imx);
1.214     brouard  10080:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10081:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10082:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10083:   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.*/
                   10084:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10085:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10086:    
                   10087:   /* Concatenates waves */
1.214     brouard  10088:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10089:      Death is a valid wave (if date is known).
                   10090:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10091:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10092:      and mw[mi+1][i]. dh depends on stepm.
                   10093:   */
                   10094: 
1.126     brouard  10095:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  10096:   /* */
                   10097:  
1.215     brouard  10098:   free_vector(moisdc,1,n);
                   10099:   free_vector(andc,1,n);
                   10100: 
1.126     brouard  10101:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10102:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10103:   ncodemax[1]=1;
1.145     brouard  10104:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10105:   cptcoveff=0;
1.220     brouard  10106:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10107:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10108:   }
                   10109:   
                   10110:   ncovcombmax=pow(2,cptcoveff);
                   10111:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10112:   for(i=1;i<ncovcombmax;i++)
                   10113:     invalidvarcomb[i]=0;
                   10114:   
1.211     brouard  10115:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10116:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10117:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10118:   
1.200     brouard  10119:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10120:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10121:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10122:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10123:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10124:    * (currently 0 or 1) in the data.
                   10125:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10126:    * corresponding modality (h,j).
                   10127:    */
                   10128: 
1.145     brouard  10129:   h=0;
                   10130:   /*if (cptcovn > 0) */
1.126     brouard  10131:   m=pow(2,cptcoveff);
                   10132:  
1.144     brouard  10133:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10134:           * For k=4 covariates, h goes from 1 to m=2**k
                   10135:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10136:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10137:           *     h\k   1     2     3     4
1.143     brouard  10138:           *______________________________  
                   10139:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10140:           *     2     2     1     1     1
                   10141:           *     3 i=2 1     2     1     1
                   10142:           *     4     2     2     1     1
                   10143:           *     5 i=3 1 i=2 1     2     1
                   10144:           *     6     2     1     2     1
                   10145:           *     7 i=4 1     2     2     1
                   10146:           *     8     2     2     2     1
1.197     brouard  10147:           *     9 i=5 1 i=3 1 i=2 1     2
                   10148:           *    10     2     1     1     2
                   10149:           *    11 i=6 1     2     1     2
                   10150:           *    12     2     2     1     2
                   10151:           *    13 i=7 1 i=4 1     2     2    
                   10152:           *    14     2     1     2     2
                   10153:           *    15 i=8 1     2     2     2
                   10154:           *    16     2     2     2     2
1.143     brouard  10155:           */
1.212     brouard  10156:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10157:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10158:      * and the value of each covariate?
                   10159:      * V1=1, V2=1, V3=2, V4=1 ?
                   10160:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10161:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10162:      * In order to get the real value in the data, we use nbcode
                   10163:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10164:      * We are keeping this crazy system in order to be able (in the future?) 
                   10165:      * to have more than 2 values (0 or 1) for a covariate.
                   10166:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10167:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10168:      *              bbbbbbbb
                   10169:      *              76543210     
                   10170:      *   h-1        00000101 (6-1=5)
1.219     brouard  10171:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10172:      *           &
                   10173:      *     1        00000001 (1)
1.219     brouard  10174:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10175:      *          +1= 00000001 =1 
1.211     brouard  10176:      *
                   10177:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10178:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10179:      *    >>k'            11
                   10180:      *          &   00000001
                   10181:      *            = 00000001
                   10182:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10183:      * Reverse h=6 and m=16?
                   10184:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10185:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10186:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10187:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10188:      * V3=decodtabm(14,3,2**4)=2
                   10189:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10190:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10191:      *          &1 000000001
                   10192:      *           = 000000001
                   10193:      *         +1= 000000010 =2
                   10194:      *                  2211
                   10195:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10196:      *                  V3=2
1.220     brouard  10197:                 * codtabm and decodtabm are identical
1.211     brouard  10198:      */
                   10199: 
1.145     brouard  10200: 
                   10201:  free_ivector(Ndum,-1,NCOVMAX);
                   10202: 
                   10203: 
1.126     brouard  10204:     
1.186     brouard  10205:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10206:   strcpy(optionfilegnuplot,optionfilefiname);
                   10207:   if(mle==-3)
1.201     brouard  10208:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10209:   strcat(optionfilegnuplot,".gp");
                   10210: 
                   10211:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10212:     printf("Problem with file %s",optionfilegnuplot);
                   10213:   }
                   10214:   else{
1.204     brouard  10215:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10216:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10217:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10218:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10219:   }
                   10220:   /*  fclose(ficgp);*/
1.186     brouard  10221: 
                   10222: 
                   10223:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10224: 
                   10225:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10226:   if(mle==-3)
1.201     brouard  10227:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10228:   strcat(optionfilehtm,".htm");
                   10229:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10230:     printf("Problem with %s \n",optionfilehtm);
                   10231:     exit(0);
1.126     brouard  10232:   }
                   10233: 
                   10234:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10235:   strcat(optionfilehtmcov,"-cov.htm");
                   10236:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10237:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10238:   }
                   10239:   else{
                   10240:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10241: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10242: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10243:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10244:   }
                   10245: 
1.213     brouard  10246:   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  10247: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10248: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10249: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10250: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10251: \n\
                   10252: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10253:  <ul><li><h4>Parameter files</h4>\n\
                   10254:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10255:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10256:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10257:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10258:  - Date and time at start: %s</ul>\n",\
                   10259:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10260:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10261:          fileres,fileres,\
                   10262:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10263:   fflush(fichtm);
                   10264: 
                   10265:   strcpy(pathr,path);
                   10266:   strcat(pathr,optionfilefiname);
1.184     brouard  10267: #ifdef WIN32
                   10268:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10269: #else
1.126     brouard  10270:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10271: #endif
                   10272:          
1.126     brouard  10273:   
1.220     brouard  10274:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10275:                 and for any valid combination of covariates
1.126     brouard  10276:      and prints on file fileres'p'. */
1.227     brouard  10277:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10278:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10279: 
                   10280:   fprintf(fichtm,"\n");
                   10281:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10282: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10283: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10284:          imx,agemin,agemax,jmin,jmax,jmean);
                   10285:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10286:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10287:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10288:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10289:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10290: 
1.126     brouard  10291:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10292:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10293:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10294: 
                   10295:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10296:   /* For mortality only */
1.126     brouard  10297:   if (mle==-3){
1.136     brouard  10298:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10299:                for(i=1;i<=NDIM;i++)
                   10300:                        for(j=1;j<=NDIM;j++)
                   10301:                                ximort[i][j]=0.;
1.186     brouard  10302:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10303:     cens=ivector(1,n);
                   10304:     ageexmed=vector(1,n);
                   10305:     agecens=vector(1,n);
                   10306:     dcwave=ivector(1,n);
1.223     brouard  10307:                
1.126     brouard  10308:     for (i=1; i<=imx; i++){
                   10309:       dcwave[i]=-1;
                   10310:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10311:        if (s[m][i]>nlstate) {
                   10312:          dcwave[i]=m;
                   10313:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10314:          break;
                   10315:        }
1.126     brouard  10316:     }
1.226     brouard  10317:     
1.126     brouard  10318:     for (i=1; i<=imx; i++) {
                   10319:       if (wav[i]>0){
1.226     brouard  10320:        ageexmed[i]=agev[mw[1][i]][i];
                   10321:        j=wav[i];
                   10322:        agecens[i]=1.; 
                   10323:        
                   10324:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10325:          agecens[i]=agev[mw[j][i]][i];
                   10326:          cens[i]= 1;
                   10327:        }else if (ageexmed[i]< 1) 
                   10328:          cens[i]= -1;
                   10329:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10330:          cens[i]=0 ;
1.126     brouard  10331:       }
                   10332:       else cens[i]=-1;
                   10333:     }
                   10334:     
                   10335:     for (i=1;i<=NDIM;i++) {
                   10336:       for (j=1;j<=NDIM;j++)
1.226     brouard  10337:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10338:     }
                   10339:     
1.145     brouard  10340:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10341:     /*printf("%lf %lf", p[1], p[2]);*/
                   10342:     
                   10343:     
1.136     brouard  10344: #ifdef GSL
                   10345:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10346: #else
1.126     brouard  10347:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10348: #endif
1.201     brouard  10349:     strcpy(filerespow,"POW-MORT_"); 
                   10350:     strcat(filerespow,fileresu);
1.126     brouard  10351:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10352:       printf("Problem with resultfile: %s\n", filerespow);
                   10353:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10354:     }
1.136     brouard  10355: #ifdef GSL
                   10356:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10357: #else
1.126     brouard  10358:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10359: #endif
1.126     brouard  10360:     /*  for (i=1;i<=nlstate;i++)
                   10361:        for(j=1;j<=nlstate+ndeath;j++)
                   10362:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10363:     */
                   10364:     fprintf(ficrespow,"\n");
1.136     brouard  10365: #ifdef GSL
                   10366:     /* gsl starts here */ 
                   10367:     T = gsl_multimin_fminimizer_nmsimplex;
                   10368:     gsl_multimin_fminimizer *sfm = NULL;
                   10369:     gsl_vector *ss, *x;
                   10370:     gsl_multimin_function minex_func;
                   10371: 
                   10372:     /* Initial vertex size vector */
                   10373:     ss = gsl_vector_alloc (NDIM);
                   10374:     
                   10375:     if (ss == NULL){
                   10376:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10377:     }
                   10378:     /* Set all step sizes to 1 */
                   10379:     gsl_vector_set_all (ss, 0.001);
                   10380: 
                   10381:     /* Starting point */
1.126     brouard  10382:     
1.136     brouard  10383:     x = gsl_vector_alloc (NDIM);
                   10384:     
                   10385:     if (x == NULL){
                   10386:       gsl_vector_free(ss);
                   10387:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10388:     }
                   10389:   
                   10390:     /* Initialize method and iterate */
                   10391:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10392:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10393:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10394:     gsl_vector_set(x, 0, p[1]);
                   10395:     gsl_vector_set(x, 1, p[2]);
                   10396: 
                   10397:     minex_func.f = &gompertz_f;
                   10398:     minex_func.n = NDIM;
                   10399:     minex_func.params = (void *)&p; /* ??? */
                   10400:     
                   10401:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10402:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10403:     
                   10404:     printf("Iterations beginning .....\n\n");
                   10405:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10406: 
                   10407:     iteri=0;
                   10408:     while (rval == GSL_CONTINUE){
                   10409:       iteri++;
                   10410:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10411:       
                   10412:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10413:       fflush(0);
                   10414:       
                   10415:       if (status) 
                   10416:         break;
                   10417:       
                   10418:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10419:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10420:       
                   10421:       if (rval == GSL_SUCCESS)
                   10422:         printf ("converged to a local maximum at\n");
                   10423:       
                   10424:       printf("%5d ", iteri);
                   10425:       for (it = 0; it < NDIM; it++){
                   10426:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10427:       }
                   10428:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10429:     }
                   10430:     
                   10431:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10432:     
                   10433:     gsl_vector_free(x); /* initial values */
                   10434:     gsl_vector_free(ss); /* inital step size */
                   10435:     for (it=0; it<NDIM; it++){
                   10436:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10437:       fprintf(ficrespow," %.12lf", p[it]);
                   10438:     }
                   10439:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10440: #endif
                   10441: #ifdef POWELL
                   10442:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10443: #endif  
1.126     brouard  10444:     fclose(ficrespow);
                   10445:     
1.203     brouard  10446:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10447: 
                   10448:     for(i=1; i <=NDIM; i++)
                   10449:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10450:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10451:     
                   10452:     printf("\nCovariance matrix\n ");
1.203     brouard  10453:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10454:     for(i=1; i <=NDIM; i++) {
                   10455:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10456:                                printf("%f ",matcov[i][j]);
                   10457:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10458:       }
1.203     brouard  10459:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10460:     }
                   10461:     
                   10462:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10463:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10464:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10465:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10466:     }
1.126     brouard  10467:     lsurv=vector(1,AGESUP);
                   10468:     lpop=vector(1,AGESUP);
                   10469:     tpop=vector(1,AGESUP);
                   10470:     lsurv[agegomp]=100000;
                   10471:     
                   10472:     for (k=agegomp;k<=AGESUP;k++) {
                   10473:       agemortsup=k;
                   10474:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10475:     }
                   10476:     
                   10477:     for (k=agegomp;k<agemortsup;k++)
                   10478:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10479:     
                   10480:     for (k=agegomp;k<agemortsup;k++){
                   10481:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10482:       sumlpop=sumlpop+lpop[k];
                   10483:     }
                   10484:     
                   10485:     tpop[agegomp]=sumlpop;
                   10486:     for (k=agegomp;k<(agemortsup-3);k++){
                   10487:       /*  tpop[k+1]=2;*/
                   10488:       tpop[k+1]=tpop[k]-lpop[k];
                   10489:     }
                   10490:     
                   10491:     
                   10492:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10493:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10494:       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]);
                   10495:     
                   10496:     
                   10497:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10498:                ageminpar=50;
                   10499:                agemaxpar=100;
1.194     brouard  10500:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10501:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10502: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10503: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10504:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10505: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10506: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10507:     }else{
                   10508:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10509:                        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  10510:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10511:                }
1.201     brouard  10512:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10513:                     stepm, weightopt,\
                   10514:                     model,imx,p,matcov,agemortsup);
                   10515:     
                   10516:     free_vector(lsurv,1,AGESUP);
                   10517:     free_vector(lpop,1,AGESUP);
                   10518:     free_vector(tpop,1,AGESUP);
1.220     brouard  10519:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10520:     free_ivector(cens,1,n);
                   10521:     free_vector(agecens,1,n);
                   10522:     free_ivector(dcwave,1,n);
1.220     brouard  10523: #ifdef GSL
1.136     brouard  10524: #endif
1.186     brouard  10525:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10526:   /* Standard  */
                   10527:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10528:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10529:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10530:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10531:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10532:     for (k=1; k<=npar;k++)
                   10533:       printf(" %d %8.5f",k,p[k]);
                   10534:     printf("\n");
1.205     brouard  10535:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10536:       /* mlikeli uses func not funcone */
                   10537:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10538:     }
                   10539:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10540:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10541:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10542:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10543:     }
                   10544:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10545:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10546:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10547:     for (k=1; k<=npar;k++)
                   10548:       printf(" %d %8.5f",k,p[k]);
                   10549:     printf("\n");
                   10550:     
                   10551:     /*--------- results files --------------*/
1.224     brouard  10552:     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  10553:     
                   10554:     
                   10555:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10556:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10557:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10558:     for(i=1,jk=1; i <=nlstate; i++){
                   10559:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10560:        if (k != i) {
                   10561:          printf("%d%d ",i,k);
                   10562:          fprintf(ficlog,"%d%d ",i,k);
                   10563:          fprintf(ficres,"%1d%1d ",i,k);
                   10564:          for(j=1; j <=ncovmodel; j++){
                   10565:            printf("%12.7f ",p[jk]);
                   10566:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10567:            fprintf(ficres,"%12.7f ",p[jk]);
                   10568:            jk++; 
                   10569:          }
                   10570:          printf("\n");
                   10571:          fprintf(ficlog,"\n");
                   10572:          fprintf(ficres,"\n");
                   10573:        }
1.126     brouard  10574:       }
                   10575:     }
1.203     brouard  10576:     if(mle != 0){
                   10577:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10578:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10579:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10580:       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");
                   10581:       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");
                   10582:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10583:        for(k=1; k <=(nlstate+ndeath); k++){
                   10584:          if (k != i) {
                   10585:            printf("%d%d ",i,k);
                   10586:            fprintf(ficlog,"%d%d ",i,k);
                   10587:            for(j=1; j <=ncovmodel; j++){
                   10588:              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]));
                   10589:              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]));
                   10590:              jk++; 
                   10591:            }
                   10592:            printf("\n");
                   10593:            fprintf(ficlog,"\n");
                   10594:          }
                   10595:        }
1.193     brouard  10596:       }
1.203     brouard  10597:     } /* end of hesscov and Wald tests */
1.225     brouard  10598:     
1.203     brouard  10599:     /*  */
1.126     brouard  10600:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10601:     printf("# Scales (for hessian or gradient estimation)\n");
                   10602:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10603:     for(i=1,jk=1; i <=nlstate; i++){
                   10604:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10605:        if (j!=i) {
                   10606:          fprintf(ficres,"%1d%1d",i,j);
                   10607:          printf("%1d%1d",i,j);
                   10608:          fprintf(ficlog,"%1d%1d",i,j);
                   10609:          for(k=1; k<=ncovmodel;k++){
                   10610:            printf(" %.5e",delti[jk]);
                   10611:            fprintf(ficlog," %.5e",delti[jk]);
                   10612:            fprintf(ficres," %.5e",delti[jk]);
                   10613:            jk++;
                   10614:          }
                   10615:          printf("\n");
                   10616:          fprintf(ficlog,"\n");
                   10617:          fprintf(ficres,"\n");
                   10618:        }
1.126     brouard  10619:       }
                   10620:     }
                   10621:     
                   10622:     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  10623:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10624:       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");
                   10625:     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");
                   10626:     /* # 121 Var(a12)\n\ */
                   10627:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10628:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10629:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10630:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10631:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10632:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10633:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10634:     
                   10635:     
                   10636:     /* Just to have a covariance matrix which will be more understandable
                   10637:        even is we still don't want to manage dictionary of variables
                   10638:     */
                   10639:     for(itimes=1;itimes<=2;itimes++){
                   10640:       jj=0;
                   10641:       for(i=1; i <=nlstate; i++){
1.225     brouard  10642:        for(j=1; j <=nlstate+ndeath; j++){
                   10643:          if(j==i) continue;
                   10644:          for(k=1; k<=ncovmodel;k++){
                   10645:            jj++;
                   10646:            ca[0]= k+'a'-1;ca[1]='\0';
                   10647:            if(itimes==1){
                   10648:              if(mle>=1)
                   10649:                printf("#%1d%1d%d",i,j,k);
                   10650:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10651:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10652:            }else{
                   10653:              if(mle>=1)
                   10654:                printf("%1d%1d%d",i,j,k);
                   10655:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10656:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10657:            }
                   10658:            ll=0;
                   10659:            for(li=1;li <=nlstate; li++){
                   10660:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10661:                if(lj==li) continue;
                   10662:                for(lk=1;lk<=ncovmodel;lk++){
                   10663:                  ll++;
                   10664:                  if(ll<=jj){
                   10665:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10666:                    if(ll<jj){
                   10667:                      if(itimes==1){
                   10668:                        if(mle>=1)
                   10669:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10670:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10671:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10672:                      }else{
                   10673:                        if(mle>=1)
                   10674:                          printf(" %.5e",matcov[jj][ll]); 
                   10675:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10676:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10677:                      }
                   10678:                    }else{
                   10679:                      if(itimes==1){
                   10680:                        if(mle>=1)
                   10681:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10682:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10683:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10684:                      }else{
                   10685:                        if(mle>=1)
                   10686:                          printf(" %.7e",matcov[jj][ll]); 
                   10687:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10688:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10689:                      }
                   10690:                    }
                   10691:                  }
                   10692:                } /* end lk */
                   10693:              } /* end lj */
                   10694:            } /* end li */
                   10695:            if(mle>=1)
                   10696:              printf("\n");
                   10697:            fprintf(ficlog,"\n");
                   10698:            fprintf(ficres,"\n");
                   10699:            numlinepar++;
                   10700:          } /* end k*/
                   10701:        } /*end j */
1.126     brouard  10702:       } /* end i */
                   10703:     } /* end itimes */
                   10704:     
                   10705:     fflush(ficlog);
                   10706:     fflush(ficres);
1.225     brouard  10707:     while(fgets(line, MAXLINE, ficpar)) {
                   10708:       /* If line starts with a # it is a comment */
                   10709:       if (line[0] == '#') {
                   10710:        numlinepar++;
                   10711:        fputs(line,stdout);
                   10712:        fputs(line,ficparo);
                   10713:        fputs(line,ficlog);
                   10714:        continue;
                   10715:       }else
                   10716:        break;
                   10717:     }
                   10718:     
1.209     brouard  10719:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10720:     /*   ungetc(c,ficpar); */
                   10721:     /*   fgets(line, MAXLINE, ficpar); */
                   10722:     /*   fputs(line,stdout); */
                   10723:     /*   fputs(line,ficparo); */
                   10724:     /* } */
                   10725:     /* ungetc(c,ficpar); */
1.126     brouard  10726:     
                   10727:     estepm=0;
1.209     brouard  10728:     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  10729:       
                   10730:       if (num_filled != 6) {
                   10731:        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);
                   10732:        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);
                   10733:        goto end;
                   10734:       }
                   10735:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10736:     }
                   10737:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10738:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10739:     
1.209     brouard  10740:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10741:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10742:     if (fage <= 2) {
                   10743:       bage = ageminpar;
                   10744:       fage = agemaxpar;
                   10745:     }
                   10746:     
                   10747:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10748:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10749:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10750:                
1.186     brouard  10751:     /* Other stuffs, more or less useful */    
1.126     brouard  10752:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10753:       ungetc(c,ficpar);
                   10754:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10755:       fputs(line,stdout);
1.126     brouard  10756:       fputs(line,ficparo);
                   10757:     }
                   10758:     ungetc(c,ficpar);
                   10759:     
                   10760:     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);
                   10761:     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);
                   10762:     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);
                   10763:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10764:     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);
                   10765:     
                   10766:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10767:       ungetc(c,ficpar);
                   10768:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10769:       fputs(line,stdout);
1.126     brouard  10770:       fputs(line,ficparo);
                   10771:     }
                   10772:     ungetc(c,ficpar);
                   10773:     
                   10774:     
                   10775:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10776:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10777:     
                   10778:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10779:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10780:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10781:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10782:     
                   10783:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10784:       ungetc(c,ficpar);
                   10785:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10786:       fputs(line,stdout);
1.238   ! brouard  10787:       fputs(line,ficres);
1.126     brouard  10788:       fputs(line,ficparo);
                   10789:     }
                   10790:     ungetc(c,ficpar);
                   10791:     
                   10792:     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);
                   10793:     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);
                   10794:     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);
                   10795:     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);
                   10796:     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);
                   10797:     /* day and month of proj2 are not used but only year anproj2.*/
                   10798:     
1.217     brouard  10799:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10800:       ungetc(c,ficpar);
                   10801:       fgets(line, MAXLINE, ficpar);
                   10802:       fputs(line,stdout);
                   10803:       fputs(line,ficparo);
1.238   ! brouard  10804:       fputs(line,ficres);
1.217     brouard  10805:     }
                   10806:     ungetc(c,ficpar);
                   10807:     
                   10808:     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  10809:     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);
                   10810:     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);
                   10811:     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  10812:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10813:     
1.230     brouard  10814:     /* Results */
1.235     brouard  10815:     nresult=0;
1.230     brouard  10816:     while(fgets(line, MAXLINE, ficpar)) {
                   10817:       /* If line starts with a # it is a comment */
                   10818:       if (line[0] == '#') {
                   10819:        numlinepar++;
                   10820:        fputs(line,stdout);
                   10821:        fputs(line,ficparo);
                   10822:        fputs(line,ficlog);
1.238   ! brouard  10823:        fputs(line,ficres);
1.230     brouard  10824:        continue;
                   10825:       }else
                   10826:        break;
                   10827:     }
                   10828:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   10829:       if (num_filled == 0)
                   10830:        resultline[0]='\0';
                   10831:       else if (num_filled != 1){
                   10832:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10833:       }
1.235     brouard  10834:       nresult++; /* Sum of resultlines */
                   10835:       printf("Result %d: result=%s\n",nresult, resultline);
                   10836:       if(nresult > MAXRESULTLINES){
                   10837:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10838:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10839:        goto end;
                   10840:       }
                   10841:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238   ! brouard  10842:       fprintf(ficparo,"result: %s\n",resultline);
        !          10843:       fprintf(ficres,"result: %s\n",resultline);
        !          10844:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  10845:       while(fgets(line, MAXLINE, ficpar)) {
                   10846:        /* If line starts with a # it is a comment */
                   10847:        if (line[0] == '#') {
                   10848:          numlinepar++;
                   10849:          fputs(line,stdout);
                   10850:          fputs(line,ficparo);
1.238   ! brouard  10851:          fputs(line,ficres);
1.230     brouard  10852:          fputs(line,ficlog);
                   10853:          continue;
                   10854:        }else
                   10855:          break;
                   10856:       }
                   10857:       if (feof(ficpar))
                   10858:        break;
                   10859:       else{ /* Processess output results for this combination of covariate values */
                   10860:       }                                   
                   10861:     }
                   10862: 
                   10863: 
1.126     brouard  10864:     
1.230     brouard  10865:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10866:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10867:     
                   10868:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10869:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10870:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10871: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10872: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10873:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10874: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10875: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10876:     }else{
1.218     brouard  10877:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10878:     }
                   10879:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10880:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10881:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10882:                
1.225     brouard  10883:     /*------------ free_vector  -------------*/
                   10884:     /*  chdir(path); */
1.220     brouard  10885:                
1.215     brouard  10886:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10887:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10888:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   10889:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  10890:     free_lvector(num,1,n);
                   10891:     free_vector(agedc,1,n);
                   10892:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   10893:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   10894:     fclose(ficparo);
                   10895:     fclose(ficres);
1.220     brouard  10896:                
                   10897:                
1.186     brouard  10898:     /* Other results (useful)*/
1.220     brouard  10899:                
                   10900:                
1.126     brouard  10901:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  10902:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   10903:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  10904:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  10905:     fclose(ficrespl);
                   10906: 
                   10907:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  10908:     /*#include "hpijx.h"*/
                   10909:     hPijx(p, bage, fage);
1.145     brouard  10910:     fclose(ficrespij);
1.227     brouard  10911:     
1.220     brouard  10912:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  10913:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  10914:     k=1;
1.126     brouard  10915:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  10916:     
1.219     brouard  10917:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  10918:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  10919:     for(i=1;i<=AGESUP;i++)
1.219     brouard  10920:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  10921:        for(k=1;k<=ncovcombmax;k++)
                   10922:          probs[i][j][k]=0.;
1.219     brouard  10923:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   10924:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   10925:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  10926:       for(i=1;i<=AGESUP;i++)
                   10927:        for(j=1;j<=nlstate;j++)
                   10928:          for(k=1;k<=ncovcombmax;k++)
                   10929:            mobaverages[i][j][k]=0.;
1.219     brouard  10930:       mobaverage=mobaverages;
                   10931:       if (mobilav!=0) {
1.235     brouard  10932:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  10933:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   10934:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   10935:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   10936:        }
1.219     brouard  10937:       }
                   10938:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   10939:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10940:       else if (mobilavproj !=0) {
1.235     brouard  10941:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  10942:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   10943:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10944:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10945:        }
1.219     brouard  10946:       }
                   10947:     }/* end if moving average */
1.227     brouard  10948:     
1.126     brouard  10949:     /*---------- Forecasting ------------------*/
                   10950:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   10951:     if(prevfcast==1){
                   10952:       /*    if(stepm ==1){*/
1.225     brouard  10953:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  10954:     }
1.217     brouard  10955:     if(backcast==1){
1.219     brouard  10956:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   10957:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   10958:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   10959: 
                   10960:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   10961: 
                   10962:       bprlim=matrix(1,nlstate,1,nlstate);
                   10963:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   10964:       fclose(ficresplb);
                   10965: 
1.222     brouard  10966:       hBijx(p, bage, fage, mobaverage);
                   10967:       fclose(ficrespijb);
1.219     brouard  10968:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10969: 
                   10970:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  10971:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  10972:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10973:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10974:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10975:     }
1.217     brouard  10976:     
1.186     brouard  10977:  
                   10978:     /* ------ Other prevalence ratios------------ */
1.126     brouard  10979: 
1.215     brouard  10980:     free_ivector(wav,1,imx);
                   10981:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   10982:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   10983:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  10984:                
                   10985:                
1.127     brouard  10986:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  10987:                
1.201     brouard  10988:     strcpy(filerese,"E_");
                   10989:     strcat(filerese,fileresu);
1.126     brouard  10990:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   10991:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   10992:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   10993:     }
1.208     brouard  10994:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   10995:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238   ! brouard  10996: 
        !          10997:     pstamp(ficreseij);
1.219     brouard  10998:                
1.235     brouard  10999:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11000:     if (cptcovn < 1){i1=1;}
                   11001:     
                   11002:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11003:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11004:       if(TKresult[nres]!= k)
                   11005:        continue;
1.219     brouard  11006:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11007:       printf("\n#****** ");
1.225     brouard  11008:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11009:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11010:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11011:       }
                   11012:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11013:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11014:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11015:       }
                   11016:       fprintf(ficreseij,"******\n");
1.235     brouard  11017:       printf("******\n");
1.219     brouard  11018:       
                   11019:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11020:       oldm=oldms;savm=savms;
1.235     brouard  11021:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11022:       
1.219     brouard  11023:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11024:     }
                   11025:     fclose(ficreseij);
1.208     brouard  11026:     printf("done evsij\n");fflush(stdout);
                   11027:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11028:                
1.227     brouard  11029:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11030:                
                   11031:                
1.201     brouard  11032:     strcpy(filerest,"T_");
                   11033:     strcat(filerest,fileresu);
1.127     brouard  11034:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11035:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11036:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11037:     }
1.208     brouard  11038:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11039:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11040:                
1.126     brouard  11041: 
1.201     brouard  11042:     strcpy(fileresstde,"STDE_");
                   11043:     strcat(fileresstde,fileresu);
1.126     brouard  11044:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11045:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11046:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11047:     }
1.227     brouard  11048:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11049:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11050: 
1.201     brouard  11051:     strcpy(filerescve,"CVE_");
                   11052:     strcat(filerescve,fileresu);
1.126     brouard  11053:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11054:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11055:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11056:     }
1.227     brouard  11057:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11058:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11059: 
1.201     brouard  11060:     strcpy(fileresv,"V_");
                   11061:     strcat(fileresv,fileresu);
1.126     brouard  11062:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11063:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11064:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11065:     }
1.227     brouard  11066:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11067:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11068: 
1.145     brouard  11069:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11070:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11071:           
1.235     brouard  11072:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11073:     if (cptcovn < 1){i1=1;}
                   11074:     
                   11075:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11076:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11077:       if(TKresult[nres]!= k)
                   11078:        continue;
                   11079:       printf("\n#****** Selected:");
                   11080:       fprintf(ficrest,"\n#****** Selected:");
                   11081:       fprintf(ficlog,"\n#****** Selected:");
1.227     brouard  11082:       for(j=1;j<=cptcoveff;j++){ 
                   11083:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11084:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11085:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11086:       }
1.235     brouard  11087:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11088:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11089:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11090:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11091:       }        
1.208     brouard  11092:       fprintf(ficrest,"******\n");
1.227     brouard  11093:       fprintf(ficlog,"******\n");
                   11094:       printf("******\n");
1.208     brouard  11095:       
                   11096:       fprintf(ficresstdeij,"\n#****** ");
                   11097:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11098:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11099:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11100:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11101:       }
1.235     brouard  11102:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11103:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11104:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11105:       }        
1.208     brouard  11106:       fprintf(ficresstdeij,"******\n");
                   11107:       fprintf(ficrescveij,"******\n");
                   11108:       
                   11109:       fprintf(ficresvij,"\n#****** ");
1.238   ! brouard  11110:       /* pstamp(ficresvij); */
1.225     brouard  11111:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11112:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11113:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11114:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11115:       }        
1.208     brouard  11116:       fprintf(ficresvij,"******\n");
                   11117:       
                   11118:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11119:       oldm=oldms;savm=savms;
1.235     brouard  11120:       printf(" cvevsij ");
                   11121:       fprintf(ficlog, " cvevsij ");
                   11122:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11123:       printf(" end cvevsij \n ");
                   11124:       fprintf(ficlog, " end cvevsij \n ");
                   11125:       
                   11126:       /*
                   11127:        */
                   11128:       /* goto endfree; */
                   11129:       
                   11130:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11131:       pstamp(ficrest);
                   11132:       
                   11133:       
                   11134:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11135:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11136:        cptcod= 0; /* To be deleted */
                   11137:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11138:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11139:        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  11140:        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 ");
                   11141:        if(vpopbased==1)
                   11142:          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);
                   11143:        else
                   11144:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11145:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11146:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11147:        fprintf(ficrest,"\n");
                   11148:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11149:        epj=vector(1,nlstate+1);
                   11150:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11151:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11152:        for(age=bage; age <=fage ;age++){
1.235     brouard  11153:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11154:          if (vpopbased==1) {
                   11155:            if(mobilav ==0){
                   11156:              for(i=1; i<=nlstate;i++)
                   11157:                prlim[i][i]=probs[(int)age][i][k];
                   11158:            }else{ /* mobilav */ 
                   11159:              for(i=1; i<=nlstate;i++)
                   11160:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11161:            }
                   11162:          }
1.219     brouard  11163:          
1.227     brouard  11164:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11165:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11166:          /* printf(" age %4.0f ",age); */
                   11167:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11168:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11169:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11170:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11171:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11172:            }
                   11173:            epj[nlstate+1] +=epj[j];
                   11174:          }
                   11175:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11176:          
1.227     brouard  11177:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11178:            for(j=1;j <=nlstate;j++)
                   11179:              vepp += vareij[i][j][(int)age];
                   11180:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11181:          for(j=1;j <=nlstate;j++){
                   11182:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11183:          }
                   11184:          fprintf(ficrest,"\n");
                   11185:        }
1.208     brouard  11186:       } /* End vpopbased */
                   11187:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11188:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11189:       free_vector(epj,1,nlstate+1);
1.235     brouard  11190:       printf("done selection\n");fflush(stdout);
                   11191:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11192:       
1.145     brouard  11193:       /*}*/
1.235     brouard  11194:     } /* End k selection */
1.227     brouard  11195: 
                   11196:     printf("done State-specific expectancies\n");fflush(stdout);
                   11197:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11198: 
1.126     brouard  11199:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11200:     
1.201     brouard  11201:     strcpy(fileresvpl,"VPL_");
                   11202:     strcat(fileresvpl,fileresu);
1.126     brouard  11203:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11204:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11205:       exit(0);
                   11206:     }
1.208     brouard  11207:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11208:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11209:     
1.145     brouard  11210:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11211:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11212:     
1.235     brouard  11213:     i1=pow(2,cptcoveff);
                   11214:     if (cptcovn < 1){i1=1;}
                   11215: 
                   11216:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11217:     for(k=1; k<=i1;k++){
                   11218:       if(TKresult[nres]!= k)
                   11219:        continue;
1.227     brouard  11220:       fprintf(ficresvpl,"\n#****** ");
                   11221:       printf("\n#****** ");
                   11222:       fprintf(ficlog,"\n#****** ");
                   11223:       for(j=1;j<=cptcoveff;j++) {
                   11224:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11225:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11226:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11227:       }
1.235     brouard  11228:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11229:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11230:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11231:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11232:       }        
1.227     brouard  11233:       fprintf(ficresvpl,"******\n");
                   11234:       printf("******\n");
                   11235:       fprintf(ficlog,"******\n");
                   11236:       
                   11237:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11238:       oldm=oldms;savm=savms;
1.235     brouard  11239:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11240:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11241:       /*}*/
1.126     brouard  11242:     }
1.227     brouard  11243:     
1.126     brouard  11244:     fclose(ficresvpl);
1.208     brouard  11245:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11246:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11247:     
                   11248:     free_vector(weight,1,n);
                   11249:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11250:     free_imatrix(s,1,maxwav+1,1,n);
                   11251:     free_matrix(anint,1,maxwav,1,n); 
                   11252:     free_matrix(mint,1,maxwav,1,n);
                   11253:     free_ivector(cod,1,n);
                   11254:     free_ivector(tab,1,NCOVMAX);
                   11255:     fclose(ficresstdeij);
                   11256:     fclose(ficrescveij);
                   11257:     fclose(ficresvij);
                   11258:     fclose(ficrest);
                   11259:     fclose(ficpar);
                   11260:     
                   11261:     
1.126     brouard  11262:     /*---------- End : free ----------------*/
1.219     brouard  11263:     if (mobilav!=0 ||mobilavproj !=0)
                   11264:       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  11265:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11266:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11267:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11268:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11269:   /* endfree:*/
                   11270:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11271:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11272:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11273:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11274:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11275:   free_matrix(coqvar,1,maxwav,1,n);
                   11276:   free_matrix(covar,0,NCOVMAX,1,n);
                   11277:   free_matrix(matcov,1,npar,1,npar);
                   11278:   free_matrix(hess,1,npar,1,npar);
                   11279:   /*free_vector(delti,1,npar);*/
                   11280:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11281:   free_matrix(agev,1,maxwav,1,imx);
                   11282:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11283:   
                   11284:   free_ivector(ncodemax,1,NCOVMAX);
                   11285:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11286:   free_ivector(Dummy,-1,NCOVMAX);
                   11287:   free_ivector(Fixed,-1,NCOVMAX);
1.238   ! brouard  11288:   free_ivector(DummyV,1,NCOVMAX);
        !          11289:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11290:   free_ivector(Typevar,-1,NCOVMAX);
                   11291:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11292:   free_ivector(TvarsQ,1,NCOVMAX);
                   11293:   free_ivector(TvarsQind,1,NCOVMAX);
                   11294:   free_ivector(TvarsD,1,NCOVMAX);
                   11295:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11296:   free_ivector(TvarFD,1,NCOVMAX);
                   11297:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11298:   free_ivector(TvarF,1,NCOVMAX);
                   11299:   free_ivector(TvarFind,1,NCOVMAX);
                   11300:   free_ivector(TvarV,1,NCOVMAX);
                   11301:   free_ivector(TvarVind,1,NCOVMAX);
                   11302:   free_ivector(TvarA,1,NCOVMAX);
                   11303:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11304:   free_ivector(TvarFQ,1,NCOVMAX);
                   11305:   free_ivector(TvarFQind,1,NCOVMAX);
                   11306:   free_ivector(TvarVD,1,NCOVMAX);
                   11307:   free_ivector(TvarVDind,1,NCOVMAX);
                   11308:   free_ivector(TvarVQ,1,NCOVMAX);
                   11309:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11310:   free_ivector(Tvarsel,1,NCOVMAX);
                   11311:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11312:   free_ivector(Tposprod,1,NCOVMAX);
                   11313:   free_ivector(Tprod,1,NCOVMAX);
                   11314:   free_ivector(Tvaraff,1,NCOVMAX);
                   11315:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11316:   free_ivector(Tage,1,NCOVMAX);
                   11317:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11318:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11319:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11320:   
                   11321:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11322:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11323:   fflush(fichtm);
                   11324:   fflush(ficgp);
                   11325:   
1.227     brouard  11326:   
1.126     brouard  11327:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11328:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11329:     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  11330:   }else{
                   11331:     printf("End of Imach\n");
                   11332:     fprintf(ficlog,"End of Imach\n");
                   11333:   }
                   11334:   printf("See log file on %s\n",filelog);
                   11335:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11336:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11337:   rend_time = time(NULL);  
                   11338:   end_time = *localtime(&rend_time);
                   11339:   /* tml = *localtime(&end_time.tm_sec); */
                   11340:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11341:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11342:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11343:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11344:   
1.157     brouard  11345:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11346:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11347:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11348:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11349: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11350:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11351:   fclose(fichtm);
                   11352:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11353:   fclose(fichtmcov);
                   11354:   fclose(ficgp);
                   11355:   fclose(ficlog);
                   11356:   /*------ End -----------*/
1.227     brouard  11357:   
                   11358:   
                   11359:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11360: #ifdef WIN32
1.227     brouard  11361:   if (_chdir(pathcd) != 0)
                   11362:     printf("Can't move to directory %s!\n",path);
                   11363:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11364: #else
1.227     brouard  11365:     if(chdir(pathcd) != 0)
                   11366:       printf("Can't move to directory %s!\n", path);
                   11367:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11368: #endif 
1.126     brouard  11369:     printf("Current directory %s!\n",pathcd);
                   11370:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11371:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11372: #ifdef _WIN32
1.126     brouard  11373:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11374: #endif
                   11375:   if(!stat(plotcmd,&info)){
1.158     brouard  11376:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11377:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11378:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11379:     }else
                   11380:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11381: #ifdef __unix
1.126     brouard  11382:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11383:     if(!stat(plotcmd,&info)){
1.158     brouard  11384:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11385:     }else
                   11386:       strcpy(pplotcmd,plotcmd);
                   11387: #endif
                   11388:   }else
                   11389:     strcpy(pplotcmd,plotcmd);
                   11390:   
                   11391:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11392:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11393:   
1.126     brouard  11394:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11395:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11396:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11397:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11398:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11399:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11400:   }
1.158     brouard  11401:   printf(" Successful, please wait...");
1.126     brouard  11402:   while (z[0] != 'q') {
                   11403:     /* chdir(path); */
1.154     brouard  11404:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11405:     scanf("%s",z);
                   11406: /*     if (z[0] == 'c') system("./imach"); */
                   11407:     if (z[0] == 'e') {
1.158     brouard  11408: #ifdef __APPLE__
1.152     brouard  11409:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11410: #elif __linux
                   11411:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11412: #else
1.152     brouard  11413:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11414: #endif
                   11415:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11416:       system(pplotcmd);
1.126     brouard  11417:     }
                   11418:     else if (z[0] == 'g') system(plotcmd);
                   11419:     else if (z[0] == 'q') exit(0);
                   11420:   }
1.227     brouard  11421: end:
1.126     brouard  11422:   while (z[0] != 'q') {
1.195     brouard  11423:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11424:     scanf("%s",z);
                   11425:   }
                   11426: }

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